//! The schema of a fresh file: ONE flat DDL, [`SCHEMA_DDL`].//!//! The ladder in `crate::migrate` has exactly one rung, and it issues this//! list. There are no migrations. A shape change edits this file, bumps//! [`SCHEMA_VERSION`], re-records `tests/fixtures/schema-snapshot.json` (the//! ignored test in `tests/schema_snapshot.rs`) and adds a SHAPE line to the//! shape ledger.//!//! A file stamped below [`SCHEMA_VERSION`] is refused by//! `migrate::migration_plan`, never climbed. A file stamped from//! `shape_move::LEDGER_BASE` (141) up crosses to it in place first, by the//! difference between its flat DDL and this one (`shape_move`).//!//! The list is issued in an order that executes on an empty database://! ordinary tables, then the FTS5 virtual tables, then indexes, then//! triggers./// The version a fresh file is stamped with. Bump it with every shape change/// to [`SCHEMA_DDL`]; a file stamped below it is refused, never climbed. It is/// held equal to `migrate::SCHEMA_VERSION` by a const assertion there./// With the bump, run `pnpm gen:stack-probe`: the iPhone suite's fixture is/// stamped with this number, and `scripts/__tests__/stack-probe-fixture.test.ts`/// fails until it matches (left behind at 148, 151, 152).pubconst SCHEMA_VERSION: u32 = 158;// ---------------------------------------------------------------------------// Version 6 — the vault (Cotton note "The vault — the honest sentence").//// Every object here is in `SCHEMA_DDL` below AND in `VAULT_DDL`, in the same// bytes, the way `SESSION_LAUNCHES_TABLE` is: a fresh file runs version 1// (this whole list) and then every rung over the top of it, and a file already// on disk gets each object from its own rung. One declaration, two paths in.// ---------------------------------------------------------------------------/// `cotton_secrets` — the vault's table, version 2 of it.////// The v5 shape was `name, service, value_enc, hint` and nothing else: one/// credential kind, sealed under a server environment string, with `service`/// mandatory and a table-level `UNIQUE (workspace_id, service, name)`. Version/// 6 rebuilds it, and three of the changes cannot be expressed as an ALTER:////// * `service` becomes NULLABLE — a login has no service, and the GLOB that/// validated it now guards only the rows that carry one;/// * the UNIQUE moves OFF the table and into a PARTIAL index, because two/// rows may share `(workspace_id, NULL, name)` — a person has two Gmail/// logins — and SQLite's table-level UNIQUE would not let them;/// * `kind` arrives NOT NULL with no default, so no writer can add a row/// without saying what it is.////// `value_enc` holds the SEALED payload (`cotton_core::vault::seal`), never a/// value; the plain columns beside it are what `fts_secrets` indexes and what/// `list_secrets` answers. The payload is never indexed.////// Schema 147 (Cotton Keys, 12 Nov 2026): `kind` is the object's to decide (its/// definition's choices), so the copy keeps no CHECK of its own on it; Keys/// adds `favourite_at` (the Favourites view), `uses` (how often AutoFill has/// filled it), `passkey_id` (the passkey a login is paired with), `changed_at`/// (when its password last changed, Health's "old") and `history_enc` (its/// last ten passwords, sealed v2 as `value_enc` is).pubconst SECRETS_TABLE: &str = r#"CREATE TABLE cotton_secrets ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL, name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120), site TEXT CHECK (site IS NULL OR length(site) BETWEEN 1 AND 255), username TEXT CHECK (username IS NULL OR length(username) BETWEEN 1 AND 255), service TEXT CHECK (service IS NULL OR (length(service) BETWEEN 1 AND 60 AND service GLOB '[a-z0-9]*' AND NOT service GLOB '*[^a-z0-9._-]*')), value_enc TEXT CHECK (value_enc IS NULL OR length(value_enc) > 0), vmk_version INTEGER NOT NULL DEFAULT 0, hint TEXT CHECK (hint IS NULL OR length(hint) <= 4), last_used_at TEXT, expires_at TEXT, trashed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, favourite_at TEXT, uses INTEGER NOT NULL DEFAULT 0, passkey_id TEXT, changed_at TEXT, history_enc TEXT CHECK (history_enc IS NULL OR length(history_enc) > 0), CHECK (vmk_version >= 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// BYOK's lookup: the api key for a service.pubconst SECRETS_SERVICE_INDEX: &str = r#"CREATE INDEX idx_cotton_secrets_service ON cotton_secrets (workspace_id, service)"#;/// The v5 table-level `UNIQUE (workspace_id, service, name)`, made PARTIAL.////// A `service` is what makes a row addressable by name — the BYOK key for/// `anthropic`, the password of a filed document — and two of those must not/// collide. A row with no service is a login, and a person has two logins/// called "Gmail".pubconst SECRETS_SERVICE_NAME_INDEX: &str = r#"CREATE UNIQUE INDEX uq_cotton_secrets_service_name ON cotton_secrets (workspace_id, service, name) WHERE service IS NOT NULL"#;/// The bin's read, and the page's: what is not in the bin, newest first.pubconst SECRETS_LIVE_INDEX: &str = r#"CREATE INDEX idx_cotton_secrets_live ON cotton_secrets (workspace_id, kind, updated_at DESC) WHERE trashed_at IS NULL"#;/// `cotton_vault_keys` — one row per device that can open this workspace's/// passwords, plus the literal `recovery` row for the age identity.////// `public_key` is the device's X25519 public half, published by the device/// itself; `wrapped_vmk` is the vault master key wrapped FOR that public half/// (`cotton_core::vault::wrap`), written by whichever server holds the VMK, and/// NULL until it has. The private halves live in a Keychain and never in this/// file.////// The natural key is `(workspace_id, device_id)`; the primary key is the/// synthetic `id` every composite-keyed table in this file carries, because a/// `TableSpec` names exactly one primary-key column.pubconst VAULT_KEYS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_vault_keys ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(device_id) > 0), public_key TEXT NOT NULL CHECK (length(public_key) > 0), wrapped_vmk TEXT CHECK (wrapped_vmk IS NULL OR length(wrapped_vmk) > 0), vmk_version INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, device_id), CHECK (vmk_version >= 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// What the re-wrap worker reads: the rows that are not wrapped at the current/// version yet.pubconst VAULT_KEYS_VERSION_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_vault_keys_version ON cotton_vault_keys (workspace_id, vmk_version)"#;/// `cotton_vault_state` — one row per workspace: which version of the vault/// master key is current, and when it was last rotated.////// A revoke rotates: every secret is re-sealed and every remaining/// `cotton_vault_keys` row re-wrapped, and this row is what says a device's/// wrap is stale.pubconst VAULT_STATE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_vault_state ( workspace_id TEXT PRIMARY KEY, vmk_version INTEGER NOT NULL, rotated_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (vmk_version >= 1), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_secret_placements` — a secret written onto a paired Mac as a file.////// `path` must start with `~/` and carry no `..` segment: the applier expands/// the tilde on the device and a placement is never a way to write outside a/// person's own home. `applied_hash` is what was last written, so an unchanged/// secret is not rewritten.pubconst SECRET_PLACEMENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_secret_placements ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, secret_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(device_id) > 0), path TEXT NOT NULL, mode INTEGER NOT NULL DEFAULT 384, format TEXT NOT NULL DEFAULT 'raw', env_name TEXT, applied_at TEXT, applied_hash TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, apply_problem TEXT, UNIQUE (workspace_id, device_id, path), CHECK (format IN ('raw', 'env')), CHECK ((format = 'env') = (env_name IS NOT NULL)), CHECK (mode BETWEEN 0 AND 511), CHECK (path GLOB '~/?*' AND NOT path GLOB '*/../*' AND NOT path GLOB '*/..'), CHECK (applied_hash IS NULL OR (length(applied_hash) = 64 AND NOT applied_hash GLOB '*[^0-9a-f]*')), FOREIGN KEY (secret_id) REFERENCES cotton_secrets(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_placement_proposals` — secrets an assistant asks the owner to put/// on Macs (version 93): one list the owner approves or declines whole, from/// "Asked of you". `items` is a JSON array of placement requests/// (`{secretId, deviceId, path, format, envName, mode}`, the shape/// `cotton_core::vault::placement` judges) — where each secret goes, never a/// value. Approving writes every placement in one act; a proposal is never a/// placement until then, so a Mac's applier never sees an unapproved one.pubconst PLACEMENT_PROPOSALS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_placement_proposals ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT NOT NULL, items TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open', decided_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(title) > 0), CHECK (length(items) > 0), CHECK (status IN ('open', 'approved', 'declined')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_PLACEMENT_PROPOSALS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_placement_proposals_author ON cotton_placement_proposals (substr(_hlc, 20), _hlc)"#;/// What the applier on one Mac reads: the placements addressed to this device.pubconst SECRET_PLACEMENTS_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_secret_placements_device ON cotton_secret_placements (workspace_id, device_id)"#;/// What the secret's page reads: the placements of one secret.pubconst SECRET_PLACEMENTS_SECRET_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_secret_placements_secret ON cotton_secret_placements (secret_id)"#;/// `cotton_links` — the record-to-record edge, with `secret` in its vocabulary/// since version 6 and `repository`, `pull` and `issue` since version 19.////// A CHECK cannot be widened by an ALTER, so the rung REBUILDS the table. The/// name stays quoted because that is how SQLite stored it when an earlier era/// renamed it, and a fresh file and an upgraded one have to be the same/// database down to the byte.////// `to_database` (version 53) names the database the target lives in when it/// is not this one; NULL is this one. So the ends are unique per target/// database, not alone — [`LINKS_ENDS_INDEX`] replaces the table-level/// UNIQUE, because a link to one id in this database and to the same id in/// another are two links. Created empty and read by nothing yet.pubconst LINKS_TABLE: &str = r#"CREATE TABLE "cotton_links" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, from_kind TEXT NOT NULL, from_id TEXT NOT NULL, to_kind TEXT NOT NULL, to_id TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, to_database TEXT CHECK (to_database IS NULL OR length(to_database) > 0), CHECK (from_kind IN ('todo', 'event', 'note', 'person', 'person_note', 'thought', 'location', 'page', 'transaction', 'meeting', 'document', 'photo', 'video', 'news_edition', 'secret', 'repository', 'pull', 'issue', 'decision', 'email_thread')), CHECK (to_kind IN ('todo', 'event', 'note', 'person', 'person_note', 'thought', 'location', 'page', 'transaction', 'meeting', 'document', 'photo', 'video', 'news_edition', 'secret', 'repository', 'pull', 'issue', 'decision', 'email_thread')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst LINKS_FROM_INDEX: &str = r#"CREATE INDEX idx_cotton_links_from ON cotton_links (from_kind, from_id)"#;pubconst LINKS_TO_INDEX: &str = r#"CREATE INDEX idx_cotton_links_to ON cotton_links (to_kind, to_id)"#;pubconst LINKS_WORKSPACE_INDEX: &str = r#"CREATE INDEX idx_cotton_links_workspace ON cotton_links (workspace_id)"#;/// One link per ends and target database — the empty string standing for/// NULL, this database, as `link_id_for` reads it.pubconst LINKS_ENDS_INDEX: &str = r#"CREATE UNIQUE INDEX uq_cotton_links_ends ON cotton_links (from_kind, from_id, to_kind, to_id, coalesce(to_database, ''))"#;/// `cotton_project_links` — project membership, with `secret` in its/// vocabulary since version 6: a client's portal login belongs to the client's/// project. `repository` joined it at version 19, where a project naming a/// repository became the source of the membership rather than a JSON field on/// the project. `walkthrough` and `walkthrough_run` LEFT it at version 33, with/// the two record kinds themselves. `store` LEFT it at version 105, with the/// Stores tables: the shape move points each store's link at the note the/// store's words were kept in. Rebuilt for the same reason [`LINKS_TABLE`] is.////// The CHECK here is held equal to the registry's `projectLinkable` kinds by/// `cotton_core::primitives_tests::cotton_project_links_check_equals_the_registrys_project_linkable_kinds`,/// which reads THIS text — so a kind that leaves the registry has to leave here/// in the same PR.pubconst PROJECT_LINKS_TABLE: &str = r#"CREATE TABLE "cotton_project_links" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, project_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, note TEXT, applied_by TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, pinned INTEGER NOT NULL DEFAULT 0, "position" REAL, origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), UNIQUE (project_id, record_kind, record_id), CHECK (record_kind IN ('thread', 'email_thread', 'person', 'note', 'journal', 'todo', 'event', 'meeting', 'document', 'screenplay', 'page', 'location', 'transaction', 'goal', 'feedback', 'thought', 'photo', 'video', 'memory', 'call', 'album', 'secret', 'repository', 'decision')), CHECK (pinned IN (0, 1)), CHECK (record_kind <> 'memory' OR "position" IS NOT NULL), CHECK (applied_by IN ('router', 'user', 'agent')), CHECK (length(record_id) > 0), CHECK (note IS NULL OR length(note) <= 500), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (project_id) REFERENCES cotton_memory_projects(id) )"#;pubconst PROJECT_LINKS_RECORD_INDEX: &str = r#"CREATE INDEX idx_cotton_project_links_record ON cotton_project_links (record_kind, record_id)"#;pubconst PROJECT_LINKS_WORKSPACE_INDEX: &str = r#"CREATE INDEX idx_cotton_project_links_workspace ON cotton_project_links (workspace_id)"#;pubconst PROJECT_LINKS_ARRANGED_INDEX: &str = r#"CREATE INDEX idx_cotton_project_links_arranged ON cotton_project_links (workspace_id, project_id, record_kind, pinned DESC, "position")"#;pubconst PROJECT_LINKS_ORIGIN_INDEX: &str = r#"CREATE INDEX idx_cotton_project_links_origin ON cotton_project_links (origin_handle) WHERE origin_handle IS NOT NULL"#;// ---------------------------------------------------------------------------// The search indexes and their triggers, each named so that version 3 can// reference the same bytes version 1 issues rather than restate them — the// idiom SESSION_LAUNCHES_TABLE established for version 2.//// Every one of these is DERIVED from `schema::fts::FTS_SOURCES` and held to it// by `tests/fts_declared.rs`. Edit the source entry, then edit here; the guard// says what the text must become.// ---------------------------------------------------------------------------/// `fts_todos` — the external-content index over `cotton_todos`.pubconst FTS_TODOS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_todos USING fts5( title, notes, content = 'cotton_todos', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_events` — the external-content index over `cotton_events`.pubconst FTS_EVENTS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_events USING fts5( title, notes, location, content = 'cotton_events', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_notes` — the external-content index over `cotton_notes`.pubconst FTS_NOTES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_notes USING fts5( title, body, content = 'cotton_notes', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_locations` — the external-content index over `cotton_locations`.pubconst FTS_LOCATIONS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_locations USING fts5( name, address, note, content = 'cotton_locations', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_meetings` — the external-content index over `cotton_meetings`.pubconst FTS_MEETINGS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_meetings USING fts5( title, summary_md, content = 'cotton_meetings', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_pages` — the external-content index over `cotton_pages`.pubconst FTS_PAGES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_pages USING fts5( title, text, content = 'cotton_pages', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_memories` — the external-content index over `cotton_memories`.pubconst FTS_MEMORIES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_memories USING fts5( title, body, content = 'cotton_memories', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_documents` — the external-content index over `cotton_documents`.pubconst FTS_DOCUMENTS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_documents USING fts5( title, issuer, summary, original_name, content = 'cotton_documents', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_document_pages` — the external-content index over `cotton_document_pages`.pubconst FTS_DOCUMENT_PAGES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_document_pages USING fts5( text, content = 'cotton_document_pages', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_prompts` — the external-content index over `cotton_prompts`.pubconst FTS_PROMPTS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_prompts USING fts5( text, content = 'cotton_prompts', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_emails` — the external-content index over `cotton_emails`.pubconst FTS_EMAILS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_emails USING fts5( subject, body, content = 'cotton_emails', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_mail` — the WIDE index over `cotton_emails`: subject, body, and who it/// is from by name and by address, so one index answers a typed word, a name/// and an address (mailsearch brief, 12 Oct 2026). Version 122 creates it/// EMPTY beside `fts_emails` and fills it in the background/// (`crate::fts_fill`); `fts_emails` answers search until the fill is done.pubconst FTS_MAIL_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_mail USING fts5( subject, body, from_name, from_email, content = 'cotton_emails', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_moods` — the external-content index over `cotton_moods`.pubconst FTS_MOODS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_moods USING fts5( line, content = 'cotton_moods', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_thoughts` — the external-content index over `cotton_inbox_items`.pubconst FTS_THOUGHTS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_thoughts USING fts5( raw_text, content = 'cotton_inbox_items', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_session_messages` — the external-content index over `cotton_session_messages`.pubconst FTS_SESSION_MESSAGES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_session_messages USING fts5( body, content = 'cotton_session_messages', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_videos` — the external-content index over `cotton_videos`.pubconst FTS_VIDEOS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_videos USING fts5( caption, summary, content = 'cotton_videos', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_chat` — Cotton Chat's search over message text, by any three/// characters in a row (`trigram`), so a search needs no word boundary:/// Indian scripts, whose vowel signs `unicode61` splits words at, and scripts/// written without spaces, find a match inside a word (chat-search, 21 Nov/// 2026). Case is folded; nothing else is. Version 149 creates it EMPTY in a/// file that already held messages and fills it in the background, newest/// first (`crate::fts_fill`); the phone's own copy answers it, never the/// server, which holds the messages sealed.pubconst FTS_CHAT_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_chat USING fts5( body, content = 'cotton_msg_messages', content_rowid = 'rowid', tokenize = 'trigram' )"#;/// `fts_messages` — the external-content index over `cotton_msg_messages`.pubconst FTS_MESSAGES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_messages USING fts5( body, content = 'cotton_msg_messages', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_photos` — the external-content index over `cotton_photos`.pubconst FTS_PHOTOS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_photos USING fts5( caption, summary, ocr_text, content = 'cotton_photos', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_people` — the external-content index over `cotton_people`.pubconst FTS_PEOPLE_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_people USING fts5( full_name, org, role_title, summary, content = 'cotton_people', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_todos` on insert./// `fts_secrets` — the external-content index over `cotton_secrets` (version 6).////// The PLAIN columns only. `value_enc` is the sealed payload and is never/// indexed: an index over it would put the ciphertext's tokens in a table the/// snapshot carries to every device, and a search index of a secret is a/// search index of the secret.pubconst FTS_SECRETS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_secrets USING fts5( name, site, username, service, content = 'cotton_secrets', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;pubconst FTS_TODOS_AI: &str = r#"CREATE TRIGGER fts_todos_ai AFTER INSERT ON cotton_todos WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_todos'), 0) BEGIN INSERT INTO fts_todos (rowid, title, notes) VALUES (new.rowid, new.title, new.notes); END"#;/// `fts_todos` on delete.pubconst FTS_TODOS_AD: &str = r#"CREATE TRIGGER fts_todos_ad AFTER DELETE ON cotton_todos WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_todos'), 0) BEGIN INSERT INTO fts_todos (fts_todos, rowid, title, notes) VALUES ('delete', old.rowid, old.title, old.notes); END"#;/// `fts_events` on insert.pubconst FTS_EVENTS_AI: &str = r#"CREATE TRIGGER fts_events_ai AFTER INSERT ON cotton_events WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_events'), 0) BEGIN INSERT INTO fts_events (rowid, title, notes, location) VALUES (new.rowid, new.title, new.notes, new.location); END"#;/// `fts_events` on delete.pubconst FTS_EVENTS_AD: &str = r#"CREATE TRIGGER fts_events_ad AFTER DELETE ON cotton_events WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_events'), 0) BEGIN INSERT INTO fts_events (fts_events, rowid, title, notes, location) VALUES ('delete', old.rowid, old.title, old.notes, old.location); END"#;/// `fts_notes` on insert.pubconst FTS_NOTES_AI: &str = r#"CREATE TRIGGER fts_notes_ai AFTER INSERT ON cotton_notes WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_notes'), 0) BEGIN INSERT INTO fts_notes (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_notes` on delete.pubconst FTS_NOTES_AD: &str = r#"CREATE TRIGGER fts_notes_ad AFTER DELETE ON cotton_notes WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_notes'), 0) BEGIN INSERT INTO fts_notes (fts_notes, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); END"#;/// `fts_locations` on insert.pubconst FTS_LOCATIONS_AI: &str = r#"CREATE TRIGGER fts_locations_ai AFTER INSERT ON cotton_locations WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_locations'), 0) BEGIN INSERT INTO fts_locations (rowid, name, address, note) VALUES (new.rowid, new.name, new.address, new.note); END"#;/// `fts_locations` on delete.pubconst FTS_LOCATIONS_AD: &str = r#"CREATE TRIGGER fts_locations_ad AFTER DELETE ON cotton_locations WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_locations'), 0) BEGIN INSERT INTO fts_locations (fts_locations, rowid, name, address, note) VALUES ('delete', old.rowid, old.name, old.address, old.note); END"#;/// `fts_meetings` on insert.pubconst FTS_MEETINGS_AI: &str = r#"CREATE TRIGGER fts_meetings_ai AFTER INSERT ON cotton_meetings WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_meetings'), 0) BEGIN INSERT INTO fts_meetings (rowid, title, summary_md) VALUES (new.rowid, new.title, new.summary_md); END"#;/// `fts_meetings` on delete.pubconst FTS_MEETINGS_AD: &str = r#"CREATE TRIGGER fts_meetings_ad AFTER DELETE ON cotton_meetings WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_meetings'), 0) BEGIN INSERT INTO fts_meetings (fts_meetings, rowid, title, summary_md) VALUES ('delete', old.rowid, old.title, old.summary_md); END"#;/// `fts_pages` on insert.pubconst FTS_PAGES_AI: &str = r#"CREATE TRIGGER fts_pages_ai AFTER INSERT ON cotton_pages WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_pages'), 0) BEGIN INSERT INTO fts_pages (rowid, title, text) VALUES (new.rowid, new.title, new.text); END"#;/// `fts_pages` on delete.pubconst FTS_PAGES_AD: &str = r#"CREATE TRIGGER fts_pages_ad AFTER DELETE ON cotton_pages WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_pages'), 0) BEGIN INSERT INTO fts_pages (fts_pages, rowid, title, text) VALUES ('delete', old.rowid, old.title, old.text); END"#;/// `fts_document_pages` on insert.pubconst FTS_DOCUMENT_PAGES_AI: &str = r#"CREATE TRIGGER fts_document_pages_ai AFTER INSERT ON cotton_document_pages WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_document_pages'), 0) BEGIN INSERT INTO fts_document_pages (rowid, text) VALUES (new.rowid, new.text); END"#;/// `fts_document_pages` on delete.pubconst FTS_DOCUMENT_PAGES_AD: &str = r#"CREATE TRIGGER fts_document_pages_ad AFTER DELETE ON cotton_document_pages WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_document_pages'), 0) BEGIN INSERT INTO fts_document_pages (fts_document_pages, rowid, text) VALUES ('delete', old.rowid, old.text); END"#;/// `fts_prompts` on insert.pubconst FTS_PROMPTS_AI: &str = r#"CREATE TRIGGER fts_prompts_ai AFTER INSERT ON cotton_prompts WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_prompts'), 0) BEGIN INSERT INTO fts_prompts (rowid, text) VALUES (new.rowid, new.text); END"#;/// `fts_prompts` on delete.pubconst FTS_PROMPTS_AD: &str = r#"CREATE TRIGGER fts_prompts_ad AFTER DELETE ON cotton_prompts WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_prompts'), 0) BEGIN INSERT INTO fts_prompts (fts_prompts, rowid, text) VALUES ('delete', old.rowid, old.text); END"#;/// `fts_emails` on insert.pubconst FTS_EMAILS_AI: &str = r#"CREATE TRIGGER fts_emails_ai AFTER INSERT ON cotton_emails WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_emails'), 0) BEGIN INSERT INTO fts_emails (rowid, subject, body) VALUES (new.rowid, new.subject, new.body); END"#;/// `fts_emails` on delete.pubconst FTS_EMAILS_AD: &str = r#"CREATE TRIGGER fts_emails_ad AFTER DELETE ON cotton_emails WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_emails'), 0) BEGIN INSERT INTO fts_emails (fts_emails, rowid, subject, body) VALUES ('delete', old.rowid, old.subject, old.body); END"#;/// `fts_mail` on insert.pubconst FTS_MAIL_AI: &str = r#"CREATE TRIGGER fts_mail_ai AFTER INSERT ON cotton_emails WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_mail'), 0) BEGIN INSERT INTO fts_mail (rowid, subject, body, from_name, from_email) VALUES (new.rowid, new.subject, new.body, new.from_name, new.from_email); END"#;/// `fts_mail` on delete.pubconst FTS_MAIL_AD: &str = r#"CREATE TRIGGER fts_mail_ad AFTER DELETE ON cotton_emails WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_mail'), 0) BEGIN INSERT INTO fts_mail (fts_mail, rowid, subject, body, from_name, from_email) VALUES ('delete', old.rowid, old.subject, old.body, old.from_name, old.from_email); END"#;/// `fts_mail` on update.pubconst FTS_MAIL_AU: &str = r#"CREATE TRIGGER fts_mail_au AFTER UPDATE OF subject, body, from_name, from_email ON cotton_emails FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_mail'), 0) AND (new.subject IS NOT old.subject OR new.body IS NOT old.body OR new.from_name IS NOT old.from_name OR new.from_email IS NOT old.from_email) BEGIN INSERT INTO fts_mail (fts_mail, rowid, subject, body, from_name, from_email) VALUES ('delete', old.rowid, old.subject, old.body, old.from_name, old.from_email); INSERT INTO fts_mail (rowid, subject, body, from_name, from_email) VALUES (new.rowid, new.subject, new.body, new.from_name, new.from_email); END"#;/// `fts_moods` on insert.pubconst FTS_MOODS_AI: &str = r#"CREATE TRIGGER fts_moods_ai AFTER INSERT ON cotton_moods WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_moods'), 0) BEGIN INSERT INTO fts_moods (rowid, line) VALUES (new.rowid, new.line); END"#;/// `fts_moods` on delete.pubconst FTS_MOODS_AD: &str = r#"CREATE TRIGGER fts_moods_ad AFTER DELETE ON cotton_moods WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_moods'), 0) BEGIN INSERT INTO fts_moods (fts_moods, rowid, line) VALUES ('delete', old.rowid, old.line); END"#;/// `fts_session_messages` on insert.pubconst FTS_SESSION_MESSAGES_AI: &str = r#"CREATE TRIGGER fts_session_messages_ai AFTER INSERT ON cotton_session_messages WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_session_messages'), 0) BEGIN INSERT INTO fts_session_messages (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_session_messages` on delete.pubconst FTS_SESSION_MESSAGES_AD: &str = r#"CREATE TRIGGER fts_session_messages_ad AFTER DELETE ON cotton_session_messages WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_session_messages'), 0) BEGIN INSERT INTO fts_session_messages (fts_session_messages, rowid, body) VALUES ('delete', old.rowid, old.body); END"#;/// `fts_todos` on update.pubconst FTS_TODOS_AU: &str = r#"CREATE TRIGGER fts_todos_au AFTER UPDATE OF title, notes ON cotton_todos FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_todos'), 0) AND (new.title IS NOT old.title OR new.notes IS NOT old.notes) BEGIN INSERT INTO fts_todos (fts_todos, rowid, title, notes) VALUES ('delete', old.rowid, old.title, old.notes); INSERT INTO fts_todos (rowid, title, notes) VALUES (new.rowid, new.title, new.notes); END"#;/// `fts_events` on update.pubconst FTS_EVENTS_AU: &str = r#"CREATE TRIGGER fts_events_au AFTER UPDATE OF title, notes, location ON cotton_events FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_events'), 0) AND (new.title IS NOT old.title OR new.notes IS NOT old.notes OR new.location IS NOT old.location) BEGIN INSERT INTO fts_events (fts_events, rowid, title, notes, location) VALUES ('delete', old.rowid, old.title, old.notes, old.location); INSERT INTO fts_events (rowid, title, notes, location) VALUES (new.rowid, new.title, new.notes, new.location); END"#;/// `fts_notes` on update.pubconst FTS_NOTES_AU: &str = r#"CREATE TRIGGER fts_notes_au AFTER UPDATE OF title, body ON cotton_notes FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_notes'), 0) AND (new.title IS NOT old.title OR new.body IS NOT old.body) BEGIN INSERT INTO fts_notes (fts_notes, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); INSERT INTO fts_notes (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_locations` on update.pubconst FTS_LOCATIONS_AU: &str = r#"CREATE TRIGGER fts_locations_au AFTER UPDATE OF name, address, note ON cotton_locations FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_locations'), 0) AND (new.name IS NOT old.name OR new.address IS NOT old.address OR new.note IS NOT old.note) BEGIN INSERT INTO fts_locations (fts_locations, rowid, name, address, note) VALUES ('delete', old.rowid, old.name, old.address, old.note); INSERT INTO fts_locations (rowid, name, address, note) VALUES (new.rowid, new.name, new.address, new.note); END"#;/// `fts_meetings` on update.pubconst FTS_MEETINGS_AU: &str = r#"CREATE TRIGGER fts_meetings_au AFTER UPDATE OF title, summary_md ON cotton_meetings FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_meetings'), 0) AND (new.title IS NOT old.title OR new.summary_md IS NOT old.summary_md) BEGIN INSERT INTO fts_meetings (fts_meetings, rowid, title, summary_md) VALUES ('delete', old.rowid, old.title, old.summary_md); INSERT INTO fts_meetings (rowid, title, summary_md) VALUES (new.rowid, new.title, new.summary_md); END"#;/// `fts_pages` on update.pubconst FTS_PAGES_AU: &str = r#"CREATE TRIGGER fts_pages_au AFTER UPDATE OF title, text ON cotton_pages FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_pages'), 0) AND (new.title IS NOT old.title OR new.text IS NOT old.text) BEGIN INSERT INTO fts_pages (fts_pages, rowid, title, text) VALUES ('delete', old.rowid, old.title, old.text); INSERT INTO fts_pages (rowid, title, text) VALUES (new.rowid, new.title, new.text); END"#;/// `fts_document_pages` on update.pubconst FTS_DOCUMENT_PAGES_AU: &str = r#"CREATE TRIGGER fts_document_pages_au AFTER UPDATE OF text ON cotton_document_pages FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_document_pages'), 0) AND (new.text IS NOT old.text) BEGIN INSERT INTO fts_document_pages (fts_document_pages, rowid, text) VALUES ('delete', old.rowid, old.text); INSERT INTO fts_document_pages (rowid, text) VALUES (new.rowid, new.text); END"#;/// `fts_prompts` on update.pubconst FTS_PROMPTS_AU: &str = r#"CREATE TRIGGER fts_prompts_au AFTER UPDATE OF text ON cotton_prompts FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_prompts'), 0) AND (new.text IS NOT old.text) BEGIN INSERT INTO fts_prompts (fts_prompts, rowid, text) VALUES ('delete', old.rowid, old.text); INSERT INTO fts_prompts (rowid, text) VALUES (new.rowid, new.text); END"#;/// `fts_emails` on update.pubconst FTS_EMAILS_AU: &str = r#"CREATE TRIGGER fts_emails_au AFTER UPDATE OF subject, body ON cotton_emails FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_emails'), 0) AND (new.subject IS NOT old.subject OR new.body IS NOT old.body) BEGIN INSERT INTO fts_emails (fts_emails, rowid, subject, body) VALUES ('delete', old.rowid, old.subject, old.body); INSERT INTO fts_emails (rowid, subject, body) VALUES (new.rowid, new.subject, new.body); END"#;/// `fts_documents` on insert.pubconst FTS_DOCUMENTS_AI: &str = r#"CREATE TRIGGER fts_documents_ai AFTER INSERT ON cotton_documents WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_documents'), 0) BEGIN INSERT INTO fts_documents (rowid, title, issuer, summary, original_name) VALUES (new.rowid, new.title, new.issuer, new.summary, new.original_name); END"#;/// `fts_documents` on delete.pubconst FTS_DOCUMENTS_AD: &str = r#"CREATE TRIGGER fts_documents_ad AFTER DELETE ON cotton_documents WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_documents'), 0) BEGIN INSERT INTO fts_documents (fts_documents, rowid, title, issuer, summary, original_name) VALUES ('delete', old.rowid, old.title, old.issuer, old.summary, old.original_name); END"#;/// `fts_documents` on update.pubconst FTS_DOCUMENTS_AU: &str = r#"CREATE TRIGGER fts_documents_au AFTER UPDATE OF title, issuer, summary, original_name ON cotton_documents FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_documents'), 0) AND (new.title IS NOT old.title OR new.issuer IS NOT old.issuer OR new.summary IS NOT old.summary OR new.original_name IS NOT old.original_name) BEGIN INSERT INTO fts_documents (fts_documents, rowid, title, issuer, summary, original_name) VALUES ('delete', old.rowid, old.title, old.issuer, old.summary, old.original_name); INSERT INTO fts_documents (rowid, title, issuer, summary, original_name) VALUES (new.rowid, new.title, new.issuer, new.summary, new.original_name); END"#;/// `fts_moods` on update.pubconst FTS_MOODS_AU: &str = r#"CREATE TRIGGER fts_moods_au AFTER UPDATE OF line ON cotton_moods FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_moods'), 0) AND (new.line IS NOT old.line) BEGIN INSERT INTO fts_moods (fts_moods, rowid, line) VALUES ('delete', old.rowid, old.line); INSERT INTO fts_moods (rowid, line) VALUES (new.rowid, new.line); END"#;/// `fts_thoughts` on insert.pubconst FTS_THOUGHTS_AI: &str = r#"CREATE TRIGGER fts_thoughts_ai AFTER INSERT ON cotton_inbox_items WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_thoughts'), 0) BEGIN INSERT INTO fts_thoughts (rowid, raw_text) VALUES (new.rowid, new.raw_text); END"#;/// `fts_thoughts` on delete.pubconst FTS_THOUGHTS_AD: &str = r#"CREATE TRIGGER fts_thoughts_ad AFTER DELETE ON cotton_inbox_items WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_thoughts'), 0) BEGIN INSERT INTO fts_thoughts (fts_thoughts, rowid, raw_text) VALUES ('delete', old.rowid, old.raw_text); END"#;/// `fts_thoughts` on update.pubconst FTS_THOUGHTS_AU: &str = r#"CREATE TRIGGER fts_thoughts_au AFTER UPDATE OF raw_text ON cotton_inbox_items FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_thoughts'), 0) AND (new.raw_text IS NOT old.raw_text) BEGIN INSERT INTO fts_thoughts (fts_thoughts, rowid, raw_text) VALUES ('delete', old.rowid, old.raw_text); INSERT INTO fts_thoughts (rowid, raw_text) VALUES (new.rowid, new.raw_text); END"#;/// `fts_session_messages` on update.pubconst FTS_SESSION_MESSAGES_AU: &str = r#"CREATE TRIGGER fts_session_messages_au AFTER UPDATE OF body ON cotton_session_messages FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_session_messages'), 0) AND (new.body IS NOT old.body) BEGIN INSERT INTO fts_session_messages (fts_session_messages, rowid, body) VALUES ('delete', old.rowid, old.body); INSERT INTO fts_session_messages (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_memories` on insert.pubconst FTS_MEMORIES_AI: &str = r#"CREATE TRIGGER fts_memories_ai AFTER INSERT ON cotton_memories WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_memories'), 0) BEGIN INSERT INTO fts_memories (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_memories` on delete.pubconst FTS_MEMORIES_AD: &str = r#"CREATE TRIGGER fts_memories_ad AFTER DELETE ON cotton_memories WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_memories'), 0) BEGIN INSERT INTO fts_memories (fts_memories, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); END"#;/// `fts_memories` on update.pubconst FTS_MEMORIES_AU: &str = r#"CREATE TRIGGER fts_memories_au AFTER UPDATE OF title, body ON cotton_memories FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_memories'), 0) AND (new.title IS NOT old.title OR new.body IS NOT old.body) BEGIN INSERT INTO fts_memories (fts_memories, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); INSERT INTO fts_memories (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_chat` on insert.pubconst FTS_CHAT_AI: &str = r#"CREATE TRIGGER fts_chat_ai AFTER INSERT ON cotton_msg_messages WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_chat'), 0) BEGIN INSERT INTO fts_chat (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_chat` on delete.pubconst FTS_CHAT_AD: &str = r#"CREATE TRIGGER fts_chat_ad AFTER DELETE ON cotton_msg_messages WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_chat'), 0) BEGIN INSERT INTO fts_chat (fts_chat, rowid, body) VALUES ('delete', old.rowid, old.body); END"#;/// `fts_chat` on update.pubconst FTS_CHAT_AU: &str = r#"CREATE TRIGGER fts_chat_au AFTER UPDATE OF body ON cotton_msg_messages FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_chat'), 0) AND (new.body IS NOT old.body) BEGIN INSERT INTO fts_chat (fts_chat, rowid, body) VALUES ('delete', old.rowid, old.body); INSERT INTO fts_chat (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_messages` on insert.pubconst FTS_MESSAGES_AI: &str = r#"CREATE TRIGGER fts_messages_ai AFTER INSERT ON cotton_msg_messages WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_messages'), 0) BEGIN INSERT INTO fts_messages (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_messages` on delete.pubconst FTS_MESSAGES_AD: &str = r#"CREATE TRIGGER fts_messages_ad AFTER DELETE ON cotton_msg_messages WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_messages'), 0) BEGIN INSERT INTO fts_messages (fts_messages, rowid, body) VALUES ('delete', old.rowid, old.body); END"#;/// `fts_messages` on update.pubconst FTS_MESSAGES_AU: &str = r#"CREATE TRIGGER fts_messages_au AFTER UPDATE OF body ON cotton_msg_messages FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_messages'), 0) AND (new.body IS NOT old.body) BEGIN INSERT INTO fts_messages (fts_messages, rowid, body) VALUES ('delete', old.rowid, old.body); INSERT INTO fts_messages (rowid, body) VALUES (new.rowid, new.body); END"#;/// `fts_videos` on insert.pubconst FTS_VIDEOS_AI: &str = r#"CREATE TRIGGER fts_videos_ai AFTER INSERT ON cotton_videos WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_videos'), 0) BEGIN INSERT INTO fts_videos (rowid, caption, summary) VALUES (new.rowid, new.caption, new.summary); END"#;/// `fts_videos` on delete.pubconst FTS_VIDEOS_AD: &str = r#"CREATE TRIGGER fts_videos_ad AFTER DELETE ON cotton_videos WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_videos'), 0) BEGIN INSERT INTO fts_videos (fts_videos, rowid, caption, summary) VALUES ('delete', old.rowid, old.caption, old.summary); END"#;/// `fts_videos` on update.pubconst FTS_VIDEOS_AU: &str = r#"CREATE TRIGGER fts_videos_au AFTER UPDATE OF caption, summary ON cotton_videos FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_videos'), 0) AND (new.caption IS NOT old.caption OR new.summary IS NOT old.summary) BEGIN INSERT INTO fts_videos (fts_videos, rowid, caption, summary) VALUES ('delete', old.rowid, old.caption, old.summary); INSERT INTO fts_videos (rowid, caption, summary) VALUES (new.rowid, new.caption, new.summary); END"#;/// `fts_photos` on insert.pubconst FTS_PHOTOS_AI: &str = r#"CREATE TRIGGER fts_photos_ai AFTER INSERT ON cotton_photos WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_photos'), 0) BEGIN INSERT INTO fts_photos (rowid, caption, summary, ocr_text) VALUES (new.rowid, new.caption, new.summary, new.ocr_text); END"#;/// `fts_photos` on delete.pubconst FTS_PHOTOS_AD: &str = r#"CREATE TRIGGER fts_photos_ad AFTER DELETE ON cotton_photos WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_photos'), 0) BEGIN INSERT INTO fts_photos (fts_photos, rowid, caption, summary, ocr_text) VALUES ('delete', old.rowid, old.caption, old.summary, old.ocr_text); END"#;/// `fts_photos` on update.pubconst FTS_PHOTOS_AU: &str = r#"CREATE TRIGGER fts_photos_au AFTER UPDATE OF caption, summary, ocr_text ON cotton_photos FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_photos'), 0) AND (new.caption IS NOT old.caption OR new.summary IS NOT old.summary OR new.ocr_text IS NOT old.ocr_text) BEGIN INSERT INTO fts_photos (fts_photos, rowid, caption, summary, ocr_text) VALUES ('delete', old.rowid, old.caption, old.summary, old.ocr_text); INSERT INTO fts_photos (rowid, caption, summary, ocr_text) VALUES (new.rowid, new.caption, new.summary, new.ocr_text); END"#;/// `fts_people` on insert.pubconst FTS_PEOPLE_AI: &str = r#"CREATE TRIGGER fts_people_ai AFTER INSERT ON cotton_people WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_people'), 0) BEGIN INSERT INTO fts_people (rowid, full_name, org, role_title, summary) VALUES (new.rowid, new.full_name, new.org, new.role_title, new.summary); END"#;/// `fts_people` on delete.pubconst FTS_PEOPLE_AD: &str = r#"CREATE TRIGGER fts_people_ad AFTER DELETE ON cotton_people WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_people'), 0) BEGIN INSERT INTO fts_people (fts_people, rowid, full_name, org, role_title, summary) VALUES ('delete', old.rowid, old.full_name, old.org, old.role_title, old.summary); END"#;/// `fts_people` on update.pubconst FTS_PEOPLE_AU: &str = r#"CREATE TRIGGER fts_people_au AFTER UPDATE OF full_name, org, role_title, summary ON cotton_people FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_people'), 0) AND (new.full_name IS NOT old.full_name OR new.org IS NOT old.org OR new.role_title IS NOT old.role_title OR new.summary IS NOT old.summary) BEGIN INSERT INTO fts_people (fts_people, rowid, full_name, org, role_title, summary) VALUES ('delete', old.rowid, old.full_name, old.org, old.role_title, old.summary); INSERT INTO fts_people (rowid, full_name, org, role_title, summary) VALUES (new.rowid, new.full_name, new.org, new.role_title, new.summary); END"#;/// `fts_secrets` on insert.pubconst FTS_SECRETS_AI: &str = r#"CREATE TRIGGER fts_secrets_ai AFTER INSERT ON cotton_secrets WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_secrets'), 0) BEGIN INSERT INTO fts_secrets (rowid, name, site, username, service) VALUES (new.rowid, new.name, new.site, new.username, new.service); END"#;/// `fts_secrets` on delete.pubconst FTS_SECRETS_AD: &str = r#"CREATE TRIGGER fts_secrets_ad AFTER DELETE ON cotton_secrets WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_secrets'), 0) BEGIN INSERT INTO fts_secrets (fts_secrets, rowid, name, site, username, service) VALUES ('delete', old.rowid, old.name, old.site, old.username, old.service); END"#;/// `fts_secrets` on update.pubconst FTS_SECRETS_AU: &str = r#"CREATE TRIGGER fts_secrets_au AFTER UPDATE OF name, site, username, service ON cotton_secrets FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_secrets'), 0) AND (new.name IS NOT old.name OR new.site IS NOT old.site OR new.username IS NOT old.username OR new.service IS NOT old.service) BEGIN INSERT INTO fts_secrets (fts_secrets, rowid, name, site, username, service) VALUES ('delete', old.rowid, old.name, old.site, old.username, old.service); INSERT INTO fts_secrets (rowid, name, site, username, service) VALUES (new.rowid, new.name, new.site, new.username, new.service); END"#;// ── version 9 — the devices and the grants, in the person's own file ────────//// Until version 9 the list of keys that may open a database lived in the// SERVER's `registry.db`, one table across every workspace. That was right// while one Mac held the file. A household of Macs makes it wrong: the file// travels and the list does not, so a phone admitted on the Mac in the study// is a stranger to the Mac in the kitchen the moment the kitchen answers.//// The DURABLE half moves into the file — the approved row, the grant, the// client — and the EPHEMERAL half stays in `registry.db`, where losing it costs// one pairing: the pending entries, the nonces, and the two per-machine numbers// (`last_seen_at`, `pull_cursor`) that are facts about one machine's traffic// rather than about the person's life.//// **No live token crosses.** `cotton_oauth_grants` is the standing consent and// syncs; the access and refresh token hashes stay on the machine that minted// them, because a token hash on a disk that never issued it is a bearer at rest// on three disks. The consequence is named and accepted: a token minted on one// Mac is refused by another after a hand-over, and the refresh re-mints against// the grant that did travel.// ── The built-now set (slice 9a) ─────────────────────────────────────────//// Every table and column the sync rebuild names, created EMPTY and read by// nothing yet: each later slice starts writing into a shape that is already// in every file, so no slice after this one changes the file format to begin./// `_writes` — the per-write log a file keeps for itself: one row per/// (table, row, stamp), its author, the op that carried it and the signed/// bytes. `held = 1` is a write kept back from its author's stream./// Device-local, never synced.pubconst WRITES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _writes ( tbl TEXT NOT NULL, row_id TEXT NOT NULL, hlc TEXT NOT NULL, author TEXT, op_id TEXT UNIQUE, kind TEXT CHECK (kind IS NULL OR kind IN ('create','change','retract')), actor TEXT, held INTEGER NOT NULL DEFAULT 0, mint_cont INTEGER, mint_boot TEXT, bytes BLOB, fields TEXT, sig BLOB, implied INTEGER, PRIMARY KEY (tbl, row_id, hlc) )"#;/// Schema 151 (TRIM, 21 Nov 2026): a receipt the object served is kept as/// its identity alone while its row says exactly what it says/// (`crate::receipts::implied`): `bytes` and `fields` go, and `implied` names/// the set of its field names (and the schema it was minted at) here, which/// every such receipt of one shape shares. Device-local.pubconst FIELD_SETS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _field_sets ( id INTEGER PRIMARY KEY, schema INTEGER NOT NULL, names TEXT NOT NULL, UNIQUE (schema, names) )"#;/// Schema 151: how far the in-place trim of a copy made before 151 has/// walked `_writes` (`crate::receipts::implied::carry`), one row. Device-local.pubconst TRIM_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _trim ( only_one INTEGER PRIMARY KEY CHECK (only_one = 1), after INTEGER NOT NULL DEFAULT 0, done INTEGER NOT NULL DEFAULT 0 )"#;/// A receipt may name several owning parents. This is a device-local/// projection of its canonical fields; the foreign key removes every entry/// with its receipt, including bulk keep, erase and snapshot deletions.pubconst WRITES_OWNERS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _writes_owners ( receipt TEXT NOT NULL REFERENCES _writes(op_id) ON DELETE CASCADE, tbl TEXT NOT NULL, owner TEXT NOT NULL, PRIMARY KEY (receipt, tbl, owner) ) WITHOUT ROWID"#;pubconst WRITES_OWNERS_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_writes_owners ON _writes_owners (tbl, owner)"#;/// Clock recovery seeks the newest receipt without walking every table and row.pubconst WRITES_HLC_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_writes_hlc ON _writes (hlc)"#;pubconst TOMBSTONES_HLC_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_tombstones_hlc ON _tombstones (hlc)"#;/// An author's own stream through `_writes`, the held ones left out.pubconst WRITES_AUTHOR_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_writes_author ON _writes (author, hlc) WHERE held = 0"#;/// The held receipts, and nothing else: the release pass (`mint::clock::/// release_held`) asks for `held = 1` on every fresh handle and every judge/// pass, and without this it read all of `_writes` — 916k rows, 8.0 s under/// the serving Mac's writer lock on 11 Oct 2026 — to find none.pubconst WRITES_HELD_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_writes_held ON _writes (held) WHERE held = 1"#;/// `_parked` — an op this file could not apply yet, kept whole (`bytes`),/// with the class that says why (`crate::rejected`). Version 58 makes it the/// one park table (`_parked` is gone) and adds `tbl` and `row_id`, the/// receipt's own address copied out of its bytes, so a touched row finds its/// parks by `idx_parked_row`. Version 61 adds `handover_epoch` and/// `handover_offers`: the serving epoch a hand-over pass last offered the park/// to and how many times, so a pass that never completes stops re-offering a/// refused park to that epoch at `rejected::HANDOVER_OFFER_CEILING`/// (`tries` is the sweep's count, not the hand-over's). Device-local.pubconst PARKED_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _parked ( op_id TEXT PRIMARY KEY, direction TEXT, class TEXT NOT NULL CHECK (class IN ('waiting','conflict','gone','unverified','newer-shape')), reason TEXT, first_at TEXT, tried_at TEXT, tries INTEGER NOT NULL DEFAULT 0, bytes BLOB, sig BLOB, tbl TEXT NOT NULL, row_id TEXT NOT NULL, handover_epoch INTEGER, handover_offers INTEGER NOT NULL DEFAULT 0 )"#;/// The parks of a row, by direction — what a touched row's retry reads.pubconst PARKED_ROW_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_parked_row ON _parked (direction, tbl, row_id)"#;/// `_gone` — a row this file erased, one entry per (table, row): the stamp of/// the erasure and the signed bytes that carried it. Device-local. Version/// 59 makes `bytes` NOT NULL: its one writer, `erase::apply`, keeps the/// erase's minted receipt, so a `_gone` row without it is not an erase.pubconst GONE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _gone ( tbl TEXT NOT NULL, row_id TEXT NOT NULL, hlc TEXT NOT NULL, reason TEXT, op_id TEXT, author TEXT, actor TEXT, bytes BLOB NOT NULL, sig BLOB, PRIMARY KEY (tbl, row_id) )"#;/// `_media_key_names` — which rows name which media object key, so "who still/// names these bytes" is a lookup. Device-local, derived.pubconst MEDIA_KEY_NAMES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _media_key_names ( key TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL, PRIMARY KEY (key, tbl, row_id) )"#;/// `_media_unlinks` — this device's queue of DEAD media keys to unlink/// (slice 7, `crate::media_erasure`): a key enters when an erasure leaves no/// present or dormant row naming it, leaves when a row names it again before/// the unlink, and is marked `done_at` once its bytes are gone. Device-local,/// never synced, born empty (version 60).pubconst MEDIA_UNLINKS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _media_unlinks ( key TEXT PRIMARY KEY, queued_at TEXT NOT NULL, done_at TEXT )"#;/// `_computed` — what this device worked out for every computed column/// (`crate::derived`): one row per (table, record, column), the value as the/// reads answer it. Derived inside the fold's own transaction by the one/// core, so a list can sort, filter and search on it before its LIMIT./// Device-local, never synced — two devices derive the same rows from the/// same records, so there is nothing to disagree about — and born empty/// (version 63). `value` has no declared type: a number stays a number.pubconst COMPUTED_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _computed ( table_id TEXT NOT NULL, record_id TEXT NOT NULL, key TEXT NOT NULL, value, PRIMARY KEY (table_id, record_id, key) )"#;/// `cotton_authors` — one row per AUTHOR a device minted: the stamp identity its writes carry, why it was minted, and the first stamp it wrote.pubconst AUTHORS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_authors ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(device_id) > 0), device_name TEXT, minted_at TEXT NOT NULL, reason TEXT NOT NULL CHECK (reason IN ('first','take-over','redate','keys')), first_stamp TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_revocations` — one row per revocation of a device, author, grant or key: what was revoked, by whom, why, and what succeeded it.pubconst REVOCATIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_revocations ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, subject_table TEXT NOT NULL, subject_id TEXT NOT NULL, revoked_at TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL CHECK (reason IN ('revoked','lost','succeeded','stolen','erased','restored','spent','pruned')), successor TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, p_sig TEXT, signer_person TEXT, replaced_by TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_serving_machine` — one row per serving EPOCH: which device served the workspace from when, under which author, and where each author's stream stood at the hand-over.pubconst SERVING_MACHINE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_serving_machine ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, epoch INTEGER NOT NULL, device_credential_id TEXT NOT NULL, author_id TEXT NOT NULL, relay_key TEXT, backup_access_key_id TEXT, since TEXT NOT NULL, confirmed_by TEXT, start_positions TEXT CHECK (start_positions IS NULL OR json_type(start_positions) = 'object'), _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_vault_retired_keys` — a vault master key version retired by a rotation, kept wrapped under its successor so an older sealed value still opens. `wrapped` is TEXT (base64), as `cotton_secrets.value_enc` is.pubconst VAULT_RETIRED_KEYS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_vault_retired_keys ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, version INTEGER NOT NULL, under_version INTEGER NOT NULL, under_kcv TEXT NOT NULL, wrapped TEXT NOT NULL, retired_at TEXT NOT NULL, actor TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_media_erasures` — one row per media object the owner ERASED (not binned): the key, the record that named it, when and by whom.pubconst MEDIA_ERASURES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_media_erasures ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, key TEXT NOT NULL, record_table TEXT NOT NULL, record_id TEXT NOT NULL, erased_at TEXT NOT NULL, actor TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_undos` — one row per undo: the change undone and the change that undid it.pubconst UNDOS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_undos ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, change_id TEXT NOT NULL, undo_change_id TEXT NOT NULL, at TEXT NOT NULL, actor TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_grant_rotations` — one row per rotation of a standing grant's credential: the generation reached and the digest it stands at.pubconst GRANT_ROTATIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_grant_rotations ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, grant_id TEXT NOT NULL, generation INTEGER NOT NULL, digest TEXT NOT NULL, rotated_at TEXT NOT NULL, actor TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_AUTHORS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_authors_author ON cotton_authors (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_REVOCATIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_revocations_author ON cotton_revocations (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SERVING_MACHINE: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_serving_machine_author ON cotton_serving_machine (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_VAULT_RETIRED_KEYS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_vault_retired_keys_author ON cotton_vault_retired_keys (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_ERASURES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_erasures_author ON cotton_media_erasures (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_UNDOS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_undos_author ON cotton_undos (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_GRANT_ROTATIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_grant_rotations_author ON cotton_grant_rotations (substr(_hlc, 20), _hlc)"#;pubconst AUTHORS_MINTED_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_authors_minted ON cotton_authors (workspace_id, minted_at)"#;pubconst REVOCATIONS_SUBJECT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_revocations_subject ON cotton_revocations (workspace_id, subject_table, subject_id)"#;/// A SUBJECT'S FACTS, BY THE SUBJECT (version 96).////// Every reader of a revocation asks "the facts of THIS row" — `subject_table`/// and `subject_id`, and nothing else: a device's standing on every signed/// request ([`crate::revocation::device_standing`]), a token's, an invite's, a/// member's. [`REVOCATIONS_SUBJECT_INDEX`] leads with `workspace_id`, which/// none of them names, so none could use it and each read every fact in the/// file — 17,378 on the owner's personal database, nearly all of them pruned/// runner registrations, growing by the day: 52,000 to 104,000 steps to admit/// one request, and 3.3 s of one when the pages were cold (the serving Mac, 02:06:55Z/// 11 Oct 2026, the hold named at `cotton-server/src/auth.rs:668`).pubconst REVOCATIONS_OF_SUBJECT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_revocations_of_subject ON cotton_revocations (subject_table, subject_id)"#;pubconst SERVING_MACHINE_EPOCH_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_serving_machine_epoch ON cotton_serving_machine (workspace_id, epoch)"#;pubconst VAULT_RETIRED_KEYS_VERSION_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_vault_retired_keys_version ON cotton_vault_retired_keys (workspace_id, version)"#;pubconst MEDIA_ERASURES_KEY_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_erasures_key ON cotton_media_erasures (key)"#;pubconst UNDOS_CHANGE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_undos_change ON cotton_undos (workspace_id, change_id)"#;pubconst GRANT_ROTATIONS_GRANT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_grant_rotations_grant ON cotton_grant_rotations (workspace_id, grant_id, generation)"#;// ── Keys and sharing (KS0) ───────────────────────────────────────────────//// Who is in a database is written in that database's own file, as facts made// on its serving Mac. These tables land empty; KS3 to KS5 write them. A// signature is TEXT (base64url), as `cotton_vault_retired_keys.wrapped` is:// a replicated table has no blob codec./// `cotton_admissions` — one row per admission of a person to this database: their person key, their rights, the invite it answered, and the admitter's signature.pubconst ADMISSIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_admissions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, person_key TEXT NOT NULL CHECK (length(person_key) > 0), person_name TEXT NOT NULL, rights TEXT NOT NULL CHECK (rights IN ('owner','member','admin')), invite_id TEXT UNIQUE, admitted_by_person TEXT NOT NULL, p_sig TEXT NOT NULL, admitted_at TEXT NOT NULL, suggested_person_id TEXT, suggested_person_sig TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_device_statements` — one row per statement that a device key is a member's device: signed by the person key, and by the device in consent.pubconst DEVICE_STATEMENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_device_statements ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, person_key TEXT NOT NULL CHECK (length(person_key) > 0), device_key TEXT NOT NULL CHECK (length(device_key) > 0), vault_public_key TEXT NOT NULL, device_name TEXT NOT NULL, p_sig TEXT NOT NULL, d_sig TEXT NOT NULL, made_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_invites` — one row per invite to this database: the hash of its secret, the rights it offers, when it lapses, and the maker's signature./// Version 141 appends `recipient` (the recipient's phone identity as sign-in stores it, NULL for an open invite) and `hands_over` (1 = a handover: the claimant is admitted as owner; `rights` stays 'admin' on such a row and the word 'owner' is a code rule until the next floor move). Both are native appends; the `rights` CHECK is frozen.pubconst INVITES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_invites ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, secret_hash TEXT NOT NULL CHECK (length(secret_hash) > 0), rights TEXT NOT NULL CHECK (rights IN ('member','admin')), expires_at TEXT NOT NULL, made_by_person TEXT NOT NULL, p_sig TEXT NOT NULL, made_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, recipient TEXT NULL, hands_over INTEGER NOT NULL DEFAULT 0 CHECK (hands_over IN (0,1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_ADMISSIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_admissions_author ON cotton_admissions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_DEVICE_STATEMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_statements_author ON cotton_device_statements (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_INVITES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_invites_author ON cotton_invites (substr(_hlc, 20), _hlc)"#;pubconst ADMISSIONS_PERSON_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_admissions_person ON cotton_admissions (workspace_id, person_key)"#;/// A member's own signed binding to a People row in this database. Admission/// facts stay immutable; a later claim is another fact, never a row update.pubconst MEMBER_PERSON_CLAIMS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_member_person_claims ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, admission_id TEXT NOT NULL CHECK (length(admission_id) > 0), person_key TEXT NOT NULL CHECK (length(person_key) > 0), person_id TEXT NOT NULL CHECK (length(person_id) > 0), p_sig TEXT NOT NULL, claimed_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst MEMBER_PERSON_CLAIMS_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_member_person_claims_admission ON cotton_member_person_claims (workspace_id, admission_id, claimed_at, _hlc)"#;pubconst DEVICE_STATEMENTS_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_statements_device ON cotton_device_statements (workspace_id, device_key)"#;pubconst DEVICE_STATEMENTS_PERSON_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_statements_person ON cotton_device_statements (workspace_id, person_key)"#;// ── A place the person joined (v62) ──────────────────────────────────────/// `cotton_joined_places` — in the PERSONAL database, one row per database the/// person joined at ANOTHER person's Mac by an invite: the database's id, its/// name, the serving Mac's URL (`origin`) and the Mac it pinned/// (`server_device_id`), so every device of the person learns of it and can/// present itself there as another device of the same person. It syncs, and a/// phone may push it — the phone is the device that joins. NOT insert-only: a/// leave deletes the row. One row per database, `UNIQUE (workspace_id,/// database_id)`.pubconst JOINED_PLACES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_joined_places ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, database_id TEXT NOT NULL, name TEXT, origin TEXT NOT NULL, server_device_id TEXT NOT NULL, joined_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, database_id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_JOINED_PLACES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_joined_places_author ON cotton_joined_places (substr(_hlc, 20), _hlc)"#;// ── The imports a database took (v70) ────────────────────────────────────/// `cotton_imports` — one row per IMPORT RUN that changed this database: the/// phone's contacts, a chat export, a recording, a Dashlane export, the Mac's/// ingest of messages, call history, a WhatsApp backup or photos. What was/// imported in words (`title`), how many records it added and how many it/// skipped as already there, the device that ran it and when it finished. It is/// the history the Imports tool lists; nothing before this version kept one, so/// an old database has none. Synced, written by the phone and the Mac alike;/// a run that changed nothing writes no row.pubconst IMPORTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_imports ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, source TEXT NOT NULL CHECK (source IN ('contacts','chat_export','recording','passwords','messages','call_history','whatsapp_backup','photos','instagram_export')), title TEXT NOT NULL CHECK (length(trim(title)) > 0), added INTEGER NOT NULL DEFAULT 0, skipped INTEGER NOT NULL DEFAULT 0, device_id TEXT, finished_at TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_IMPORTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_imports_author ON cotton_imports (substr(_hlc, 20), _hlc)"#;// ── The connections Cotton reads from outside (v73) ──────────────────────/// `cotton_connections` — one row per thing Cotton KEEPS READING from/// outside: a WhatsApp number, a Google account, a mailbox, a calendar,/// Cloudflare, a git host, an MCP server, later the Mac's own readers (Cotton/// note 7767ed9c, Spec 9.7). The code that reads is a source built once per/// protocol; everything that varies per person is here: what it reaches (a/// number, an address, a host, a URL), the vault secret that signs it in/// (`secret_id`, a/// plain id: a binned or erased secret reads as no credential, never as an error), the schedule, and per-kind `config` (an MCP server's URL/// and its `mapping` of calls into tables). `state` and `last_read_at` //// `last_error` are written by the serving Mac's reader; `read_requested_at`/// is a phone's "Read now", which the reader answers when it is newer than/// `last_read_at`. `database_id` names the database its rows land in (NULL:/// this one). Synced so every device lists the same connections; the/// readers' cursors stay in unsynced tables on the serving Mac, and only the/// active Mac runs a connection.pubconst CONNECTIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_connections ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('whatsapp','google','mail','calendar','cloudflare','git_host','mcp_server','mac_source','browser','tailscale')), name TEXT NOT NULL CHECK (length(trim(name)) > 0), reaches TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT 'needs_sign_in' CHECK (state IN ('reading','paused','needs_sign_in','failed')), last_read_at TEXT, last_error TEXT, read_requested_at TEXT, secret_id TEXT, schedule TEXT, config TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(config)), database_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_CONNECTIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_connections_author ON cotton_connections (substr(_hlc, 20), _hlc)"#;// ── One person across apps (v90, owner ruling 7 Oct 2026, note 1e50d25b) ──/// `cotton_person_handles` — every way a person is reached: a phone, an/// email, an Instagram, Facebook or LinkedIn handle, one row each. It is the/// ONLY place a person's phones and emails live (they were JSON columns on/// `cotton_people` until v90). `value` is as the source spelled it, shown;/// `normalised` is what matching reads, and `(workspace_id, kind, normalised)`/// is unique, so one handle names at most one person and a sender found by/// it is never ambiguous. `source` is where the handle came from; `verified_at`/// is when the owner confirmed it (a suggestion they accepted), NULL otherwise.pubconst PERSON_HANDLES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_person_handles ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, person_id TEXT NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('phone','email','instagram','facebook','linkedin')), value TEXT NOT NULL CHECK (length(trim(value)) > 0), normalised TEXT NOT NULL CHECK (length(normalised) > 0), source TEXT NOT NULL CHECK (source IN ('manual','contacts','import','suggestion','whatsapp','instagram','facebook','linkedin')), verified_at TEXT, position INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, FOREIGN KEY (person_id) REFERENCES cotton_people(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_PERSON_HANDLES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_person_handles_author ON cotton_person_handles (substr(_hlc, 20), _hlc)"#;// ── Me (v109, owner 11 Oct 2026) ─────────────────────────────────────────/// `cotton_person_languages` — the languages a person speaks, one row each/// with how well: the owner's on Me, anybody's on their People page. A small/// linked table because one person has several. `language` is as the owner/// wrote it ("Hindi", "Portuguese"); `position` is the person's own order.pubconst PERSON_LANGUAGES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_person_languages ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, person_id TEXT NOT NULL, language TEXT NOT NULL CHECK (length(trim(language)) > 0), proficiency TEXT NOT NULL DEFAULT 'fluent' CHECK (proficiency IN ('native','fluent','conversational','basic')), position INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, FOREIGN KEY (person_id) REFERENCES cotton_people(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_PERSON_LANGUAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_person_languages_author ON cotton_person_languages (substr(_hlc, 20), _hlc)"#;// ── Filing a chat (v114, owner and architect 11 Oct 2026) ────────────────/// `cotton_msg_thread_filings` — a chat in the personal Messages the owner/// FILED in a shared database: one row per (chat, database), in the personal/// database only, because the personal copy is the inbox of record and the/// filing is a live copy of it, never a move. `database_id` is the shared/// database's own id (another file, so not a foreign key). `state` is/// `filed` (new messages keep flowing there), `paused` (somebody joined the/// chat who is not a person in that database — `paused_by` holds their names/// as a JSON array — and nothing flows until they are admitted or the chat is/// unfiled) or `unfiled` (the flow stopped; what was filed stays where it/// is). `copied_through` is the copier's own mark of what it has written.pubconst MSG_THREAD_FILINGS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_msg_thread_filings ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thread_id TEXT NOT NULL, database_id TEXT NOT NULL CHECK (length(trim(database_id)) > 0), state TEXT NOT NULL DEFAULT 'filed' CHECK (state IN ('filed','paused','unfiled')), paused_by TEXT, copied_through TEXT, filed_at TEXT NOT NULL, unfiled_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (thread_id) REFERENCES cotton_msg_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_MSG_THREAD_FILINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_thread_filings_author ON cotton_msg_thread_filings (substr(_hlc, 20), _hlc)"#;// ── A reader's own marks on a filed chat (v125, architect 12 Oct 2026) ──/// `cotton_msg_thread_marks` — where ONE PERSON keeps a chat filed in a/// shared database: pinned, muted, archived, cleared. In the PERSONAL/// database only (the link rule refuses a row in a shared file), so it syncs/// to that person's own devices and nobody else's: a member's pin on a filed/// copy is theirs, and the shared database holds only the filing — the copy/// and its lines. One row per (shared database, chat): `database_id` is the/// shared database's id and `thread_id` the copy's (the filed chat's own) id,/// both in another file, so neither is a foreign key. The member is implicit:/// it is their own file. The id is derived from the pair/// (`derived_id::thread_marks_id`), so the phone and an assistant marking the/// same copy write one row. A chat in the personal Messages keeps its marks/// on its own `cotton_msg_threads` row, as before.pubconst MSG_THREAD_MARKS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_msg_thread_marks ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, database_id TEXT NOT NULL CHECK (length(trim(database_id)) > 0), thread_id TEXT NOT NULL CHECK (length(trim(thread_id)) > 0), pinned_at TEXT, muted_until TEXT, archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0,1)), cleared_before TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_MSG_THREAD_MARKS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_thread_marks_author ON cotton_msg_thread_marks (substr(_hlc, 20), _hlc)"#;// ── The internal kinds' own homes (137, tools as packages item 4) ─────────//// Until 137 these lived as `cotton_records` rows of an underscore kind; the// architect gave each a core table so no generic store survives (13 Oct 2026)./// `cotton_groups` — a group: a stack over one table's list, either the/// records a person put in it (`cotton_group_members`) or a filter (`filter`,/// a list `where`), never both. `table_id` is the table it gathers/// (`tool_order` for a group of tools on Home).pubconst GROUPS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_groups ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, table_id TEXT NOT NULL CHECK (length(trim(table_id)) > 0), name TEXT NOT NULL, filter TEXT, position REAL, picture TEXT, record_byline TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, hidden INTEGER NOT NULL DEFAULT 0, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_GROUPS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_groups_author ON cotton_groups (substr(_hlc, 20), _hlc)"#;/// `cotton_group_members` — one record a person put in a group, at its place./// One row per member, so two devices adding to one group both land (the/// group row's per-key `m:<record>` merge, before 137). The id is derived/// from the group and the record (`derived_id::group_member_id`).pubconst GROUP_MEMBERS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_group_members ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, group_id TEXT NOT NULL, record_id TEXT NOT NULL, place REAL NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (group_id) REFERENCES cotton_groups(id) )"#;pubconst AUTHOR_INDEX_COTTON_GROUP_MEMBERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_group_members_author ON cotton_group_members (substr(_hlc, 20), _hlc)"#;/// `cotton_tool_assets` — one picture a tool package carries, by the tool's/// id and the picture's file name, its bytes as the package gave them/// (base64). The id is derived from both (`derived_id::tool_asset_id`).pubconst TOOL_ASSETS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_tool_assets ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, tool_id TEXT NOT NULL CHECK (length(trim(tool_id)) > 0), name TEXT NOT NULL CHECK (length(trim(name)) > 0), bytes TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_TOOL_ASSETS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_tool_assets_author ON cotton_tool_assets (substr(_hlc, 20), _hlc)"#;/// `cotton_automation_runs` — one firing of an act or automation: what it/// was (`automation`, tool/name), the changes it made (JSON change ids, what/// an undo takes back), and how it went. Kept on phones: a person reads an/// automation's history there.pubconst AUTOMATION_RUNS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_automation_runs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, automation TEXT NOT NULL, changes TEXT NOT NULL DEFAULT '[]', root_first INTEGER, started_at TEXT NOT NULL, ended_at TEXT, outcome TEXT, summary TEXT, record_byline TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_AUTOMATION_RUNS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_automation_runs_author ON cotton_automation_runs (substr(_hlc, 20), _hlc)"#;// ── What a device keeps (v118, architect 12 Oct 2026) ────────────────────/// `cotton_device_keep` — one KEEP RULE of one device: what that device holds/// of the household's rows (and, with the byte fetcher, their bytes). A phone/// must not hold every byte the household holds; a Mac always holds/// everything, so a row here naming a Mac is never read (`crate::keep`).////// `device_id` is the device's key as `cotton_devices.device_id` says it./// `kind` is `table` (`target` a table's name; `rule` is `all`, `none` — never/// on this device, not even when opened — or `days:N`, the rows whose age/// column is within N days), `group` (`target` a group's id: every record of/// the group, always) or `record` (`target` `<table>:<row id>`: this one,/// always). No row is the default, `all`. The id is derived from the device,/// kind and target (`derived_id::device_keep_id`), so the same rule set on the/// phone and by an assistant is one row and its `rule` is one last write.// Validate the kind/rule pair in keep::check_rule, which sees the whole write.// Sync merges column fragments, so the database constrains only rule's syntax.pubconst DEVICE_KEEP_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_device_keep ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(trim(device_id)) > 0), kind TEXT NOT NULL CHECK (kind IN ('table','group','record')), target TEXT NOT NULL CHECK (length(trim(target)) > 0), rule TEXT NOT NULL CHECK (rule IN ('all','none','always') OR (rule GLOB 'days:[1-9]*' AND substr(rule, 6) NOT GLOB '*[^0-9]*')), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_DEVICE_KEEP: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_keep_author ON cotton_device_keep (substr(_hlc, 20), _hlc)"#;/// `_fts_fill` — a search index this file is still FILLING in the background/// (`crate::fts_fill`): the index holds exactly its source's rows at or above/// `floor`, and every search trigger acts only on those. `filled` of `total`/// is the progress line. No row: the index is whole. Device-local, never/// synced (version 122).pubconst FTS_FILL_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _fts_fill ( fts TEXT PRIMARY KEY, floor INTEGER NOT NULL, filled INTEGER NOT NULL DEFAULT 0, total INTEGER NOT NULL DEFAULT 0, started_at TEXT NOT NULL, updated_at TEXT NOT NULL )"#;/// `_fts_purge` — a search index an erase left words in, due a merge in the background (`crate::fts_purge`): an/// erase deletes plainly and the index's words leave once its purge has run. No row: nothing is left. Device-local,/// never synced (version 154, DELETE FAST).pubconst FTS_PURGE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _fts_purge ( fts TEXT PRIMARY KEY, since TEXT NOT NULL )"#;/// `_mail_cuts` — every mail cut this copy holds, one row per Delete, Mark read or Archive of a whole sender/// (`kind` bin, read or archive), kept from the kit's own cut tables by triggers wherever the kit made them/// (`cotton_email_bin_cut`, `cotton_email_read_cut`, `cotton_email_cut`). The mail predicate/// (`cotton_rules::mail::predicate::cuts`) reads only this, so a copy whose kit holds no cut table answers every/// mail uncut instead of failing. `erasing` is when THIS device began erasing what a 30-day-old Delete covers: from/// then its Undo is refused. Device-local, never synced (version 157, MAIL PREDICATE phase 2).pubconst MAIL_CUTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _mail_cuts ( kind TEXT NOT NULL, id TEXT NOT NULL, "key" TEXT NOT NULL, "before" TEXT NOT NULL, "at" TEXT NOT NULL, "except" TEXT, made_at TEXT NOT NULL, state TEXT, PRIMARY KEY (kind, id) )"#;/// The cut probe's seek: a mail's address or domain, by kind.pubconst MAIL_CUTS_KEY_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS _mail_cuts_key ON _mail_cuts (kind, "key")"#;/// `_mail_landed` (schema 157, PHASE 2 PHONE 2 item 5): when each mail landed on the server, BESIDE the mail row and/// never on it. Filling `cotton_emails.landed_at` on a held copy rewrote every mail's whole record, body and overflow/// pages included (measured on 300,000 synthetic mails: see the lane report); a narrow row here costs about a/// hundred bytes a mail. `key` is the sender normalised (`cotton_mail_key`) and `domain` its `@` and after, so a/// sender's or a domain's landed mail and the newest landing are index seeks. Device-local, never synced: kept from/// `cotton_emails.landed_at` by the triggers below when a pulled row brings it, and by the phone's landing fill.pubconst MAIL_LANDED_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _mail_landed ( id TEXT PRIMARY KEY, landed_at TEXT NOT NULL, "key" TEXT NOT NULL, domain TEXT NOT NULL ) WITHOUT ROWID"#;pubconst MAIL_LANDED_KEY_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS _mail_landed_key ON _mail_landed ("key", landed_at)"#;pubconst MAIL_LANDED_DOMAIN_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS _mail_landed_domain ON _mail_landed (domain, landed_at)"#;pubconst MAIL_LANDED_AT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS _mail_landed_at ON _mail_landed (landed_at)"#;pubconst MAIL_LANDED_MADE: &str = r#"CREATE TRIGGER IF NOT EXISTS _mail_landed_made AFTER INSERT ON cotton_emails WHEN NEW.landed_at IS NOT NULL BEGIN INSERT INTO _mail_landed (id, landed_at, "key", domain) VALUES (NEW.id, NEW.landed_at, cotton_mail_key(NEW.from_email), substr(cotton_mail_key(NEW.from_email), instr(cotton_mail_key(NEW.from_email), '@'))) ON CONFLICT (id) DO UPDATE SET landed_at = excluded.landed_at, "key" = excluded."key", domain = excluded.domain; END"#;pubconst MAIL_LANDED_CHANGED: &str = r#"CREATE TRIGGER IF NOT EXISTS _mail_landed_changed AFTER UPDATE OF landed_at, from_email ON cotton_emails WHEN NEW.landed_at IS NOT NULL BEGIN INSERT INTO _mail_landed (id, landed_at, "key", domain) VALUES (NEW.id, NEW.landed_at, cotton_mail_key(NEW.from_email), substr(cotton_mail_key(NEW.from_email), instr(cotton_mail_key(NEW.from_email), '@'))) ON CONFLICT (id) DO UPDATE SET landed_at = excluded.landed_at, "key" = excluded."key", domain = excluded.domain; END"#;pubconst MAIL_LANDED_GONE: &str = r#"CREATE TRIGGER IF NOT EXISTS _mail_landed_gone AFTER DELETE ON cotton_emails BEGIN DELETE FROM _mail_landed WHERE id = OLD.id; END"#;/// `_mail_own` (schema 157, PHASE 2 PHONE 2): his own addresses, normalised, kept by the phone from his accounts./// No cut covers mail from them. Device-local.pubconst MAIL_OWN_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _mail_own ("key" TEXT PRIMARY KEY) WITHOUT ROWID"#;/// `_on_demand` — the rows THIS device holds only because somebody opened/// them: a row outside the device's keep rules, answered by the serving Mac/// when its record was opened (`crate::keep::record_opened`). `opened_at` is/// the last opening; a row left unopened for thirty days is dropped from this/// device again. Device-local, never synced, born empty (version 118).pubconst ON_DEMAND_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _on_demand ( tbl TEXT NOT NULL, row_id TEXT NOT NULL, fetched_at TEXT NOT NULL, opened_at TEXT NOT NULL, PRIMARY KEY (tbl, row_id) )"#;/// `_keep_fetch` — WHAT THIS DEVICE'S COPY OF A TABLE IS COMPLETE FOR, one/// line per table a keep rule may narrow (`crate::keep::NARROWABLE`)./// `covered` is the widest rule (`all`, `none`, `days:N`) every row of which/// this copy has been handed; when the device's rule comes to be WIDER, the/// rows between were never sent and cannot be named, so they are fetched by/// table (`crate::keep::open_table`) — `target` is the rule that fetch is/// for and `after` the key it has reached, so a fetch a launch interrupted/// goes on where it stopped. Device-local, never synced, born empty (version/// 124): a device with no line is taken as complete for the rule it has the/// first time it looks, which is what every copy made before this was.pubconst KEEP_FETCH_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _keep_fetch ( tbl TEXT PRIMARY KEY, covered TEXT NOT NULL, target TEXT, after TEXT )"#;// ── Outages (v120, architect 12 Oct 2026) ────────────────────────────────/// `cotton_outages` — the owner's outage record, written by the serving Mac/// itself (actor `job:outages`) in the personal database only: one row per/// CONTINUOUS condition (`condition` is its key — `reach:relay_down`,/// `line:down` — and `ended_at` NULL is a condition still on). `kind` is a/// word the server's own list answers, not a CHECK here, so a new kind is no/// schema move. `effect` (what it means for the owner) and `doing` (what is/// being done) are the two sentences every row carries — the hand-kept note/// "Outages — 11 Oct 2026" is their model — and the file refuses a row/// without either. `told_open_at` / `told_close_at` say when the owner was/// rung about it; a `planned` row is never rung, so both stay NULL. No unique/// index on an open condition: the row is synced, and two Macs that each/// served for a while must fold, not collide — the server's book keeps one/// open row per condition (`cotton_server::outages`).pubconst OUTAGES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_outages ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL CHECK (length(trim(kind)) > 0), condition TEXT NOT NULL CHECK (length(trim(condition)) > 0), machine TEXT, title TEXT NOT NULL CHECK (length(trim(title)) > 0), effect TEXT NOT NULL CHECK (length(trim(effect)) > 0), doing TEXT NOT NULL CHECK (length(trim(doing)) > 0), started_at TEXT NOT NULL, ended_at TEXT, told_open_at TEXT, told_close_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_OUTAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_outages_author ON cotton_outages (substr(_hlc, 20), _hlc)"#;// ── Several databases (P1) ───────────────────────────────────────────────//// The person's own database lists the project databases they hold, and says// when a device stops holding one. Both tables are created EMPTY and read by// nothing yet, like the built-now set above: the slices that write them start// on a shape every file already has./// `cotton_databases` — in the personal database, one row per project/// database the person holds: its id (the database's own file id, so a row/// names the file, not a record in it), the name the switcher shows while the/// file itself is absent from this device, and the person's order.pubconst DATABASES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_databases ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, name TEXT NOT NULL CHECK (length(trim(name)) > 0), sort_order REAL NOT NULL DEFAULT 0, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_database_departures` — a fact in the personal database: a device/// (or, with `device_id` NULL, every device) stops holding a project/// database. `left` is the device's own leave, `removed` the owner taking it/// off a device, `handed_over` the database going to another person. Nothing/// is deleted from a device without its own `left` fact.pubconst DATABASE_DEPARTURES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_database_departures ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, database_id TEXT NOT NULL CHECK (length(database_id) > 0), device_id TEXT CHECK (device_id IS NULL OR length(device_id) > 0), reason TEXT NOT NULL CHECK (reason IN ('left', 'removed', 'handed_over')), departed_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_DATABASES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_databases_author ON cotton_databases (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_DATABASE_DEPARTURES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_database_departures_author ON cotton_database_departures (substr(_hlc, 20), _hlc)"#;pubconst DATABASE_DEPARTURES_DATABASE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_database_departures_database ON cotton_database_departures (workspace_id, database_id)"#;// ── The person key (KS0) ─────────────────────────────────────────────────/// `cotton_person_keys` — in the PERSONAL database only, the person's own/// signing key: `id` is the public half's fingerprint, `public_key` the/// public half, and `sealed_private` the private half sealed under the/// vault master key at `vmk_version`, so only a device that opens the vault/// opens it. It syncs, so the phone reads its row and signs as the person;/// no MCP tool, generic record reader or export reads it.////// INSERT-ONLY: a change receipt naming a row is refused by the fold/// (`fold::INSERT_ONLY`) and by `mint`.pubconst PERSON_KEYS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_person_keys ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, public_key TEXT NOT NULL, name TEXT NOT NULL DEFAULT '', sealed_private TEXT NOT NULL, vmk_version INTEGER NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_PERSON_KEYS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_person_keys_author ON cotton_person_keys (substr(_hlc, 20), _hlc)"#;/// `cotton_devices` — one row per APPROVAL of a key that may open this/// database.////// **A KEY MAY HOLD SEVERAL ROWS: at most one live, and every revoked approval/// before it** (version 41). A row is one life of one key — approved, and/// perhaps revoked — and re-admitting a revoked key is a NEW row at a new id/// (`cotton_tools::devices::approval_row_id`), never the old row returning./// `revoked_at` mirrors a `cotton_revocations` fact and is never cleared, so/// one row carrying two lives would let the first life's revocation cut off/// the second on whichever Mac heard of it last — and a recreation at/// the same id travels as the row alone, its tombstone erased by the/// recreation, so a Mac still holding the revoked life refuses it/// (`fold::no_un_revocation`). Both happened to one Mac's approval on/// 27 Sep 2026. So there is no `UNIQUE (workspace_id, device_id)`, and every/// reader that asks "the row for this key" takes the LIVE one first/// (`cotton_tools::devices::FileDevices::row_for`).////// The primary key is the synthetic `id` every composite-keyed table in this/// file carries ([`VAULT_KEYS_TABLE`]'s precedent), because a `TableSpec` names/// exactly one primary-key column. `device_id` is base64url of the device's raw/// Ed25519 public key — the same string `x-cotton-device` carries.////// `relay_identity_key` is the PUBLIC half of a Mac's relay/server identity/// key, published by that Mac into its own row so another Mac can recognise it/// on the tunnel without a second directory. NULL on a phone, which has none.////// **There is no CHECK pairing `revoked_at` with `revoked_by_device`.** Both/// are a mirror written only by `crate::revocation::revoke()`, in the same mint/// as the fact, and `mint` refuses any other write naming one — so the pair is/// held by its one writer, and the fact, not the mirror, is what a reader of a/// device's standing trusts (`crate::revocation::device_standing`).////// The four budget numbers (version 24) are what a Mac decides by: what it has/// already promised to the jobs Cotton knows about (`mem_committed_gb`), what/// it may promise at all (`mem_budget_gb` — its total memory less a reserve),/// and the largest a coding session's whole process tree has been measured/// holding on THIS Mac (`session_peak_gb`, drawn from `session_peak_samples`/// readings; under three it is an anecdote and the cost table's default stands/// instead). All four are NULLABLE and UNDEFAULTED, because a zero would read/// as "nothing committed, no budget, no peak" on a Mac nobody has measured,/// which is the one reading that would let a machine take work it cannot hold.////// `serving_rank` (version 27) is the SERVING ORDER of the Macs that can hold/// the server: lower is preferred, and NULL is last. It is a PERSON's column —/// which machine they would rather the household's name reach — on a row the/// Mac itself rewrites every fifteen minutes, which per-field clocks make safe/// exactly as they do for `sessions_cap`. It is the SOURCE of the rank the Mac/// puts on every AUTH (`cotton_relay_protocol::frames::AuthPayload::rank`),/// which the relay's election reads. NULLABLE and UNDEFAULTED for the budget/// numbers' reason — a 0 written into every row already on disk would say/// every Mac is equally and maximally preferred, which is not what a household/// that has never been asked means.////// `last_seen_at` and `pull_cursor` are deliberately ABSENT: they are written/// on every request and on every pull, by ONE machine about itself, and a/// column that rewrites itself per request would put the whole household's/// traffic on the wire. They stay in each server's own `registry.db`.////// `chip`, `os_version` and `disk_total_gb` (version 39) are the machine's/// CONSTANTS — what it is, not how it is doing — recorded once per device and/// rewritten only when the fact itself changes (a macOS update, a bigger/// drive). They are the mirror image of the reading columns above them: NOT in/// [`crate::presence::PRESENCE_COLUMNS`], written in their own op rather than/// in the fifteen-minute sample's, so a device's outbox never carries a chip/// name fifteen-minutely and a replay never loses one to the subset rule./// NULLABLE and UNDEFAULTED — a Mac whose helper predates them has not said.////// `scope` (version 49) says what the device was admitted FOR: `full`, every/// owner route, or `runner`, a machine that only takes CI work. Created with/// the built-now set and read by nothing yet; a row with none is `full`.////// The `push_*` columns are where the serving Mac may ring this device: the/// Apple push token it registered (`PUT /v1/devices`), the app's bundle id/// and Apple environment the token belongs to, when it registered, and —/// when Apple said the token is gone — when and why it was retired. ON THE/// SYNCED ROW so every standby Mac holds them and can ring a phone the moment/// the serving address goes silent (architect, 11 Oct 2026). Written only by/// the serving Mac: a pushed change to any of them is refused/// (`cotton-server` `sync::serving_screen::DEVICE_PUSH_COLUMNS`), so no device/// can re-point another's pushes. NULL until the device has registered.////// `pushed_first_at` (version 123) is on a MAC's row: when that Mac's own/// sender first rang the owner's devices ("This Mac can now reach your/// phone"), the proof that it can push at all. Since version 126 it is the/// first push from that Mac a PHONE ACKNOWLEDGED (`cotton_push_acks`), stamped/// with the phone's received time — Apple taking a push proves only the Mac's/// half (architect, 12 Oct 2026). Stamped once by that Mac while it serves,/// and refused from a push like the `push_*` columns. NULL on a phone, and on/// a Mac no phone has heard yet.////// `push_authorization` (version 126) is on a PHONE's row: what iOS last told/// that phone about Cotton's notifications — `authorized`, `provisional`,/// `ephemeral`, `denied` or `not_determined` — reported with its push/// registration and whenever it changes. Written by the serving Mac's/// registration route and refused from a push like the `push_*` columns. A/// `denied` row is the sentence on the device's row: notifications are off/// for Cotton on this phone. NULL until a phone has reported.////// `schema_version` and `copy_as_of` (version 132) are on a MAC's row, written/// by that Mac ITSELF with its machine sample and synced like `app_version`:/// the schema its copy of this database is stamped with, and the moment that/// copy was last level with the Mac that serves (the serving Mac's own is the/// sample's time; a backup Mac's is its last exchange that left nothing/// owed). They are what "Serve from this Mac" is offered on: a Mac on an/// older schema is not offered, and a copy that is behind says by how long/// (architect's ruling, 12 Oct 2026). NULL on a phone, and on a Mac that has/// not sampled since this version.////// `ai_holds`, `ai_spend` and `ai_day_cap_usd` (version 134) are on the/// SERVING Mac's row. The first two are written by its server on its own row:/// one sentence per kind of Anthropic work it is holding ("Email junk sorting/// paused · Anthropic credits"), newline-joined, NULL when nothing is held;/// and today's spend as JSON `{day, totalUsd, capUsd, byWork}`, the day being/// that Mac's local one. The third is the owner's: the most that Mac's/// Anthropic work may spend in one of its days, in USD; NULL is the $5/// default. Written ADD COLUMN, after the last column, where SQLite puts one.pubconst DEVICES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_devices ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(device_id) > 0), name TEXT NOT NULL, platform TEXT, app_version TEXT, relay_identity_key TEXT, approved_at TEXT NOT NULL, approved_by_device TEXT NOT NULL, revoked_at TEXT, revoked_by_device TEXT, revoked_reason TEXT, recovery_key_shown_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, cpu_count INTEGER, mem_total_gb REAL, mem_free_pct INTEGER, load1 REAL, disk_free_gb REAL, sessions_running INTEGER, kept_space_bytes INTEGER DEFAULT 2000000000 CHECK (kept_space_bytes IS NULL OR kept_space_bytes >= 0), sessions_cap INTEGER NOT NULL DEFAULT 3 CHECK (sessions_cap >= 0), build_lock_held INTEGER CHECK (build_lock_held IS NULL OR build_lock_held IN (0, 1)), agents TEXT NOT NULL DEFAULT '{}' CHECK (json_type(agents) = 'object'), account_ids TEXT NOT NULL DEFAULT '{}' CHECK (json_type(account_ids) = 'object'), host_version TEXT, sampled_at TEXT, mem_committed_gb REAL, mem_budget_gb REAL, session_peak_gb REAL, session_peak_samples INTEGER, serving_rank INTEGER, repos TEXT CHECK (repos IS NULL OR json_type(repos) = 'object'), chip TEXT, os_version TEXT, disk_total_gb REAL, update_hold TEXT, scope TEXT NOT NULL DEFAULT 'full' CHECK (scope IN ('full','reader','runner')), person_key TEXT, push_token TEXT, push_bundle_id TEXT, push_environment TEXT CHECK (push_environment IS NULL OR push_environment IN ('sandbox','production')), push_registered_at TEXT, push_retired_at TEXT, push_retired_reason TEXT, pushed_first_at TEXT, push_authorization TEXT CHECK (push_authorization IS NULL OR push_authorization IN ('authorized','provisional','ephemeral','denied','not_determined')), schema_version INTEGER CHECK (schema_version IS NULL OR schema_version > 0), copy_as_of TEXT, ai_holds TEXT, ai_spend TEXT, ai_day_cap_usd REAL, reported_state TEXT, hardware_id TEXT, takes_placements INTEGER NOT NULL DEFAULT 0 CHECK (takes_placements IN (0,1)), keep_free_bytes INTEGER CHECK (keep_free_bytes IS NULL OR keep_free_bytes >= 0), keep_bytes TEXT NULL CHECK (keep_bytes IS NULL OR keep_bytes IN ('everything','rows_only')), runner_ordered_at TEXT NULL, runner_confirmed_at TEXT NULL, runner_problem TEXT NULL, camera_roll INTEGER NOT NULL DEFAULT 1 CHECK (camera_roll IN (0,1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;// ── A phone heard a push (v126, architect 12 Oct 2026) ──/// `cotton_push_acks` — a phone's receipt for one push: Apple answering the/// Mac 2xx proves the Mac's half only, so a push counts as having reached the/// owner when the phone that showed it writes one of these. In the PERSONAL/// database only (the link rule refuses a row in a shared file): it is about/// the person's own devices. `push_id` is the push's own id — the Mac's/// `_push_log` row, which the payload carries as `notificationId` and Apple/// is handed as the `apns-id`. `device_id` is the Cotton device that heard/// it; `received_at` when iOS delivered it; `how` whether it was shown with/// the app open (`shown`), found in the notification list (`delivered`) or/// tapped (`opened`). One row per (device, push): the id is derived/// (`derived_id::push_ack_id`), and the first receipt stands.pubconst PUSH_ACKS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_push_acks ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(trim(device_id)) > 0), push_id TEXT NOT NULL CHECK (length(trim(push_id)) > 0), received_at TEXT NOT NULL, how TEXT NOT NULL CHECK (how IN ('shown','delivered','opened')), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_PUSH_ACKS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_push_acks_author ON cotton_push_acks (substr(_hlc, 20), _hlc)"#;// ── A Mac's relay key, kept by the serving Mac (v136, architect 12 Oct 2026) ──/// `cotton_device_relay_keys` — the relay identity key a Mac presented after/// an approval that carried none (`cotton_devices.relay_identity_key` is/// write-once, so it is never filled in). Written by the judge of `epoch`/// alone, from a request signed by the device's own key; INSERT-ONLY — never/// changed, never deleted. One row per (device, epoch): the id is derived/// (`derived_id::relay_key_id`), so two serving epochs can each keep one and/// no device refuses by arrival order; a device's key is its row's column/// when set, else the LOWEST epoch's row here — a pure function of the set./// `set_at`/`set_by` are what the device page says: the key was set then, by/// that Mac. In the PERSONAL database only: the relay roster is the/// household's.pubconst DEVICE_RELAY_KEYS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_device_relay_keys ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(trim(device_id)) > 0), epoch INTEGER NOT NULL CHECK (epoch >= 0), relay_identity_key TEXT NOT NULL CHECK (length(relay_identity_key) = 43), set_at TEXT NOT NULL, set_by TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_DEVICE_RELAY_KEYS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_relay_keys_author ON cotton_device_relay_keys (substr(_hlc, 20), _hlc)"#;// ── Who may hold a record (onlyyou rise, architect 14 Oct 2026) ──/// `cotton_audiences` — WHO MAY HOLD ONE RECORD of a shared database. A/// record with no row here travels to every member, as every record always/// has. A row whose `audience` is `only_you` HOLDS the record (and every row/// it owns) on the database owner's devices alone: the serving Mac never puts/// it in another device's exchange answer, copy or opening, and refuses a/// write of it from another device (`crate::audience`). `everyone` is the/// owner's RELEASE: from then on the record travels like any other. One row/// per record — the id is derived from (`record_table`, `record_id`)/// (`derived_id::audience_id`) — and `record_table` is the physical table, as/// an op names it. `audience` carries no CHECK: a value is a code rule/// (`crate::audience::AUDIENCES`), so a new audience never widens a synced/// CHECK. It means something only in a SHARED database: nobody else ever/// enters a personal one, so a hold there holds back nothing.pubconst AUDIENCES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_audiences ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, record_table TEXT NOT NULL CHECK (length(trim(record_table)) > 0), record_id TEXT NOT NULL CHECK (length(trim(record_id)) > 0), audience TEXT NOT NULL CHECK (length(trim(audience)) > 0), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_AUDIENCES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_audiences_author ON cotton_audiences (substr(_hlc, 20), _hlc)"#;/// A device's kept keys, lowest epoch first — what every relay-key reader asks.pubconst DEVICE_RELAY_KEYS_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_relay_keys_device ON cotton_device_relay_keys (device_id, epoch, id)"#;/// What the chokepoint reads on every owner request: this workspace's devices,/// the live ones first.pubconst DEVICES_WORKSPACE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_devices_workspace ON cotton_devices (workspace_id, revoked_at)"#;/// The lookup by KEY, which is how a request arrives — one device id, and the/// row that says whether it is admitted.pubconst DEVICES_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_devices_device ON cotton_devices (device_id)"#;/// `cotton_oauth_clients` — the assistants that have registered with this/// person's server.////// It carries no `workspace_id`: a client registration is addressed to the/// SERVER, and the file it lands in is the one database that server holds./// `secret_hash` is a hash and never a secret; `metadata_json` is the client's/// own registration document, verbatim.////// `metadata_json`'s codec is `Json`, which means a patch carries the PARSED/// document and not the text — a writer handing it the string `registry.db`/// stores would encode the quotes too. The declaration is deliberate: a/// registration this file cannot parse is a registration it should refuse at/// the codec rather than keep as an opaque string under a name that promises/// otherwise.pubconst OAUTH_CLIENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_oauth_clients ( client_id TEXT PRIMARY KEY, kind TEXT NOT NULL, secret_hash TEXT, metadata_json TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT )"#;/// `cotton_oauth_grants` — the standing consent: this client may act on this/// database, at this scope, until the person revokes it.////// **STILL NO TOKEN, AND NEVER ONE** — not a secret, not a hash of one. What/// version 21 added is what a SECOND Mac needs to honour the consent: the/// `cotton_mcp_tokens` row it minted (`token_id`, so the Connected AIs row and/// the audit anchor can be found without this machine's registry), and the/// refresh chain's position (`refresh_generation`, `refresh_rotated_at`). The/// credential itself is signed rather than stored/// (`cotton_core::vault::tokens`), so it does not live anywhere at all.////// The two chain columns settle a merge by `Policy::MaxNonNull` rather than by/// the clock — `crate::fold::COLUMN_POLICIES` — so the highest generation/// anybody reached is what every device ends on and a Mac that had not heard/// cannot wind the chain back into a window where a replayed token is honoured.////// **Version 45 adds `refresh_digest`, and it is the one hash here.** It is/// `<generation, ten digits>:<SHA-256 hex of that generation's refresh/// token>`, and it is what lets a `ctr_` signed under a key version the/// household has since ROTATED past still be honoured, once, by a Mac that can/// no longer check its tag (`cotton_server::oauth::grant`). It is not a bearer:/// a digest cannot be presented, and the token under it carries sixteen random/// bytes that are in no row of this file (`cotton_core::vault::tokens`,/// scheme 2), so neither this row nor the old key rebuilds it. The generation/// leads the value so that `Policy::MaxNonNull` on the TEXT settles a merge by/// the generation — the digest can never come apart from the position it/// names — and `crate::fold`'s digest fence refuses a digest that did not/// arrive with the rotation that moved the chain to it. The value ENDS with the/// device id of the Mac that wrote it (`<generation>:<sha-256 hex>:<device>`):/// the chain moves on whichever Mac is serving, that Mac minted the token the/// digest names, and a revocation of it must reach the grant.////// **Version 45 also adds `minted_by`**: the device id of the Mac that minted/// the consent. The sync route accepts a new grant, and any write to a column/// that is not free for every Mac, only from that device/// (`cotton_server::sync::oauth_grant_rows`), and revoking a device revokes/// every grant it minted. NULL is "minted before the rung, or by a Mac with no/// device of its own"; such a grant takes no such write from anybody. Written/// once, with its row (`crate::fold::no_grant_rewrite`).pubconst OAUTH_GRANTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_oauth_grants ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, client_id TEXT NOT NULL, client_name TEXT NOT NULL, scope TEXT NOT NULL, created_at TEXT NOT NULL, revoked_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, token_id TEXT, refresh_generation INTEGER NOT NULL DEFAULT 0, refresh_rotated_at TEXT, refresh_digest TEXT CHECK (refresh_digest IS NULL OR length(refresh_digest) BETWEEN 77 AND 204), minted_by TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The consents page's read: this workspace's grants, the live ones apart from/// the revoked.pubconst OAUTH_GRANTS_WORKSPACE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_oauth_grants_workspace ON cotton_oauth_grants (workspace_id, revoked_at)"#;pubconst AUTHOR_INDEX_COTTON_DEVICES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_devices_author ON cotton_devices (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_OAUTH_CLIENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_oauth_clients_author ON cotton_oauth_clients (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_OAUTH_GRANTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_oauth_grants_author ON cotton_oauth_grants (substr(_hlc, 20), _hlc)"#;// ── version 41 — a device key holds one row per APPROVAL ────────────────────/// `_cursors` — how far this file has seen each AUTHOR's writes (version 8).////// One row per WRITER, never per peer: under table-as-log a device asks each/// author's own stream for what it has not seen, so the cursor that matters is/// the author's stamp and not a server sequence. The `IF NOT EXISTS` is the/// `SESSION_LAUNCHES_TABLE` idiom one rung up — a fresh file runs version 1,/// which is this list, and then version 8 over the top.pubconst CURSORS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS _cursors ( author_device_id TEXT PRIMARY KEY, hlc_seen TEXT NOT NULL, updated_at TEXT NOT NULL )"#;/// A delete has an author too, and its stamp lives in `_tombstones.hlc` rather/// than in an `_hlc` column — so this one index names `hlc` where the other/// ninety-three name `_hlc`.pubconst TOMBSTONES_AUTHOR_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_tombstones_author ON _tombstones (substr(hlc, 20), hlc)"#;/// The held deletes, for the release pass — [`WRITES_HELD_INDEX`]'s twin.pubconst TOMBSTONES_HELD_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_tombstones_held ON _tombstones (held) WHERE held = 1"#;// One expression index per replicated table, and the expression is the HLC's// own layout: `<13 ms>:<4 counter>:<device>`, so `substr(_hlc, 20)` IS the// author. `(author, _hlc)` in that order is what makes "this author's writes// after this stamp, in order" a SEARCH rather than a scan of the table.//// Each is declared ONCE and referenced twice — from `SCHEMA_DDL`, which a// fresh file runs, and from `PER_FIELD_CLOCKS_DDL`, which version 8 runs over// a file already on disk. Same bytes, two paths in.pubconst AUTHOR_INDEX_COTTON_AI_ACCESS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_ai_access_author ON cotton_ai_access (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_ALARMS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_alarms_author ON cotton_alarms (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_ASSISTANT_RUNS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_assistant_runs_author ON cotton_assistant_runs (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_BLOCKED_SENDERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_blocked_senders_author ON cotton_blocked_senders (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_CALL_LOG: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_call_log_author ON cotton_call_log (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_COLLECTIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_collections_author ON cotton_collections (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_COMMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_comments_author ON cotton_comments (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_DICTATIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_dictations_author ON cotton_dictations (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_DOCUMENT_PAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_document_pages_author ON cotton_document_pages (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_DOCUMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_documents_author ON cotton_documents (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EMAIL_SENDERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_email_senders_author ON cotton_email_senders (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EMAIL_PARTICIPANTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_email_participants_author ON cotton_email_participants (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EMAIL_THREADS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_email_threads_author ON cotton_email_threads (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EMAILS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_emails_author ON cotton_emails (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EVENT_ATTENDEES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_event_attendees_author ON cotton_event_attendees (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_EVENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_events_author ON cotton_events (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_FEEDBACK: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_feedback_author ON cotton_feedback (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_GOALS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_goals_author ON cotton_goals (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_GOOGLE_ACCOUNTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_google_accounts_author ON cotton_google_accounts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_INBOX_ITEMS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_inbox_items_author ON cotton_inbox_items (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_LINKS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_links_author ON cotton_links (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_LOCATIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_locations_author ON cotton_locations (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MCP_AUDIT: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_mcp_audit_author ON cotton_mcp_audit (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MCP_TOKENS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_mcp_tokens_author ON cotton_mcp_tokens (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_ALBUM_ITEMS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_album_items_author ON cotton_media_album_items (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_ALBUMS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_albums_author ON cotton_media_albums (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_DUPLICATES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_duplicates_author ON cotton_media_duplicates (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_FACES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_faces_author ON cotton_media_faces (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEDIA_SIGHTINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_sightings_author ON cotton_media_sightings (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEETING_UTTERANCES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_meeting_utterances_author ON cotton_meeting_utterances (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEETINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_meetings_author ON cotton_meetings (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEMORIES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_memories_author ON cotton_memories (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MEMORY_PROJECTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_memory_projects_author ON cotton_memory_projects (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MONEY_ACCOUNTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_money_accounts_author ON cotton_money_accounts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MONEY_EVIDENCE: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_money_evidence_author ON cotton_money_evidence (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MONEY_STATEMENT_LINES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_money_statement_lines_author ON cotton_money_statement_lines (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MONEY_STATEMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_money_statements_author ON cotton_money_statements (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MONEY_TRANSACTIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_money_transactions_author ON cotton_money_transactions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MOODS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_moods_author ON cotton_moods (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_CONTACT_HANDLES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_contact_handles_author ON cotton_msg_contact_handles (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_CONTACTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_contacts_author ON cotton_msg_contacts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_MESSAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_messages_author ON cotton_msg_messages (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_OWNER_SETTINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_owner_settings_author ON cotton_msg_owner_settings (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_REACTIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_reactions_author ON cotton_msg_reactions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_STORIES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_stories_author ON cotton_stories (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_RECEIPTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_receipts_author ON cotton_msg_receipts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_THREAD_PARTICIPANTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_thread_participants_author ON cotton_msg_thread_participants (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_MSG_THREADS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_threads_author ON cotton_msg_threads (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NEWS_EDITIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_news_editions_author ON cotton_news_editions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NEWS_SEEN: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_news_seen_author ON cotton_news_seen (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NEWS_SETTINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_news_settings_author ON cotton_news_settings (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NEWS_STORIES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_news_stories_author ON cotton_news_stories (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NEWS_TOPICS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_news_topics_author ON cotton_news_topics (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_NOTES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_notes_author ON cotton_notes (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_pages_author ON cotton_pages (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PEOPLE: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_people_author ON cotton_people (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PERSON_NOTES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_person_notes_author ON cotton_person_notes (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PERSON_SUGGESTIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_person_suggestions_author ON cotton_person_suggestions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PHOTOS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_photos_author ON cotton_photos (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PROJECT_LINKS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_project_links_author ON cotton_project_links (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_PROMPTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_prompts_author ON cotton_prompts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAY_CHARACTERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplay_characters_author ON cotton_screenplay_characters (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAY_DOCUMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplay_documents_author ON cotton_screenplay_documents (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAY_DRAFT_SCENES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplay_draft_scenes_author ON cotton_screenplay_draft_scenes (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAY_DRAFTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplay_drafts_author ON cotton_screenplay_drafts (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAY_SCENES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplay_scenes_author ON cotton_screenplay_scenes (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SCREENPLAYS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_screenplays_author ON cotton_screenplays (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SECRET_PLACEMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_secret_placements_author ON cotton_secret_placements (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SECRETS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_secrets_author ON cotton_secrets (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SESSION_MESSAGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_session_messages_author ON cotton_session_messages (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_SESSIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_sessions_author ON cotton_sessions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_TODO_RECURRENCES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_todo_recurrences_author ON cotton_todo_recurrences (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_TODOS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_todos_author ON cotton_todos (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_VAULT_KEYS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_vault_keys_author ON cotton_vault_keys (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_VAULT_STATE: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_vault_state_author ON cotton_vault_state (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_VIDEOS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_videos_author ON cotton_videos (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_VOICE_VOCABULARY: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_voice_vocabulary_author ON cotton_voice_vocabulary (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_WORKSPACES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_workspaces_author ON cotton_workspaces (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 10 — `cotton_home_arrangement`, the person's own order of Home.//// The `SESSION_LAUNCHES_TABLE` idiom, eight rungs up: both objects are in// `SCHEMA_DDL` below AND in `HOME_ARRANGEMENT_DDL`, in the same bytes, so a// fresh file gets them from version 1 and a file already on disk gets them// from its own rung. One declaration, two paths in, which is what the// `IF NOT EXISTS` on each is for.// ---------------------------------------------------------------------------/// `cotton_home_arrangement` — ONE row per workspace: the database's tools and/// its Home.////// Three JSON arrays of strings and nothing else. `project_slugs` is the active/// projects in the person's order; `tools` is the database's tool keys (its kit/// plus what Tools added), in the person's order, as they were when the row was/// last written; `view_ids` is Home — its cards, each a view id (`tool/<key>`,/// `ready/everything`, `<table>/<groupId>`), in the person's order. Nothing is/// put away (owner's ruling, 12 Oct 2026; schema 130). The rules for reading/// them against today's projects and tools live in ONE place,/// `cotton_core::rules::home_arrangement`.////// `'[]'` defaults on all three, so a row is never half-written, and a/// `json_type` CHECK on each, so a column cannot come to hold an object.////// The clock columns are written out here rather than declared on the step:/// the table is BORN at version 10, which is two rungs above the one that/// added them everywhere else, so it is not in `PER_FIELD_CLOCK_COLUMNS`.pubconst HOME_ARRANGEMENT_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_home_arrangement ( workspace_id TEXT PRIMARY KEY, project_slugs TEXT NOT NULL DEFAULT '[]', tools TEXT NOT NULL DEFAULT '[]', view_ids TEXT NOT NULL DEFAULT '[]', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (json_type(project_slugs) = 'array'), CHECK (json_type(tools) = 'array'), CHECK (json_type(view_ids) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The author index every replicated table carries since version 8 — this one/// arrives with the table rather than a rung later.pubconst AUTHOR_INDEX_COTTON_HOME_ARRANGEMENT: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_home_arrangement_author ON cotton_home_arrangement (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 11 — the operation log goes.// ---------------------------------------------------------------------------// ---------------------------------------------------------------------------// Version 12 — media tiers: who HOLDS which bytes, and what this device keeps.//// The `SESSION_LAUNCHES_TABLE` idiom again: every object below is in// `SCHEMA_DDL` AND in `MEDIA_TIERS_DDL`, in the same bytes, so a fresh file// gets them from version 1 and a file already on disk gets them from its own// rung, and the `IF NOT EXISTS` on each makes the second issue a no-op.//// **No column on `cotton_photos` or `cotton_videos`.** The blur tier and the// video still already have theirs: `cotton_photos.preview`,// `cotton_videos.preview` and `cotton_videos.poster_key` have been in the file// since before the Rust ladder, and the phone already RENDERS the preview// (`PhotosBlur.image(base64:)`). Nothing has ever written them. Phase 2 is the// producer for a column and a renderer that already ship, so the rung adds no// column for them — and this comment is here so the next reader does not add// one, find it unused, and conclude the tier is missing.// ---------------------------------------------------------------------------/// One synced choice per device and tool, with readings published by the/// device holding the bytes. A missing reading is unknown, never zero.pubconst STORAGE_RULES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_storage_rules ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL, tool TEXT NOT NULL CHECK (tool IN ('photo','video','document','meeting','thread','person','other','whatsapp','instagram')), keep_rule TEXT NOT NULL DEFAULT 'all' CHECK (keep_rule IN ('all','recent_90_days','only_opened')), held_bytes INTEGER, freeable_bytes INTEGER, held_count INTEGER, total_count INTEGER, measured_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, device_id, tool), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst STORAGE_RULES_AUTHOR_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_storage_rules_author ON cotton_storage_rules (substr(_hlc, 20), _hlc)"#;/// `cotton_media_holdings` — one row per (object, device, tier): this device/// has these bytes.////// The table answers ONE question: *who can give me these bytes.* It is what/// turns "at least two devices hold every original" from a hope into a query/// (`crate::media_holdings::objects_with_fewer_than`), and what lets a phone's/// eviction pass refuse to drop the last copy of anything.////// The natural key is `(workspace_id, object_key, device_id, tier)` and the/// primary key is the synthetic `id` every composite-keyed table in this file/// carries ([`DEVICES_TABLE`]'s precedent, because a `TableSpec` names exactly/// one primary-key column). The id is DERIVED from the natural key —/// `hold:<tier>:<device_id>:<object_key>` — so a second record of the same hold/// is a restatement of one row rather than a second row, on any device, with no/// lookup first.////// **`dropped_at` is a COLUMN, never a row delete.** An eviction is a fact the/// other devices need — "I had these bytes and I no longer do" — and a delete/// would travel as a tombstone that says nothing about which tier or which/// object it was about once it has been pruned.////// **Exactly one writer per row, and that is what makes plain LWW correct/// here.** A device only ever writes rows whose `device_id` is its own device/// key — every writer takes the id from its own identity, and/// `crate::media_holdings::record_holding` refuses an id that is no live/// `cotton_devices` row — so two devices never race for one row and there is/// no merge to lose./// **[`crate::fold::COLUMN_POLICIES`] therefore gains NO entry** — and not/// even `cotton_devices.revoked_at` has one: a revocation is a/// `cotton_revocations` fact, which no later write can out-vote. Said here so/// the next reader does not add one by analogy.////// **A revocation is not a write to somebody else's rows.** A revoked phone's/// holdings are stale and only that phone may write them, and it may never come/// back — so every READER joins `cotton_devices` and excludes a device carrying/// a `revoked_at`. That keeps the single-writer property and makes a revoke/// correct on every device the instant the device row folds./// `crate::media_holdings` owns that query so there is one spelling of it.pubconst MEDIA_HOLDINGS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_media_holdings ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, object_key TEXT NOT NULL, device_id TEXT NOT NULL, tier TEXT NOT NULL CHECK (tier IN ('thumb','display','original')), bytes INTEGER NOT NULL, verified_at TEXT, dropped_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, object_key, device_id, tier), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// "Who holds this object" — the read `holders_of` makes, and the one the/// eviction fence makes before it deletes a file. `dropped_at` is in the index/// so the live holders are found without touching the evicted rows.pubconst MEDIA_HOLDINGS_OBJECT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_holdings_object ON cotton_media_holdings (workspace_id, object_key, dropped_at)"#;/// "What does this device hold, at this tier" — the replicator's own gaps, and/// what a revoked device's rows are found by when somebody asks what it was/// carrying.pubconst MEDIA_HOLDINGS_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_holdings_device ON cotton_media_holdings (device_id, tier)"#;/// Version 128: "every live hold of this tier", answered from the index alone —/// the standby work list's read of what other devices hold/// (`media_holdings::objects_held_elsewhere`, once per tier). Through/// [`MEDIA_HOLDINGS_OBJECT_INDEX`] it walked every holding of the workspace,/// the dropped ones too, and opened each row: 2.5 M steps and a 6.1 s hold of/// the owner's file, 94k holdings of which 26k are live (12 Oct 2026).pubconst MEDIA_HOLDINGS_LIVE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_holdings_live ON cotton_media_holdings (workspace_id, tier, object_key, device_id, bytes, created_at, dropped_at) WHERE dropped_at IS NULL"#;/// The author index every replicated table has carried since version 8 — this/// one arrives with the table, so the rung that creates it is the only one that/// ever touches it.pubconst AUTHOR_INDEX_COTTON_MEDIA_HOLDINGS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_holdings_author ON cotton_media_holdings (substr(_hlc, 20), _hlc)"#;/// Bucket evidence belongs to the serving epoch, not to a device holding./// Born empty; the serving mirror records only objects it has listed or put.pubconst MEDIA_BACKUPS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_media_backups ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, object_key TEXT NOT NULL, serving_epoch INTEGER NOT NULL, verified_at TEXT NOT NULL, missing_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE(workspace_id, serving_epoch, object_key), FOREIGN KEY(workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE)"#;pubconst MEDIA_BACKUPS_AUTHOR_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_media_backups_author ON cotton_media_backups (substr(_hlc,20),_hlc)"#;// ---------------------------------------------------------------------------// Version 14 — the Code tool (Cotton note "The Code tool — why a Mac holds the sessions").//// A Mac hosts coding-agent sessions and the phone drives them, so the file has// to carry three things it did not: what a Mac IS like right now, which agent// login it is signed in as, and a queue of launches that may not have a Mac// yet. Every object below is in `SCHEMA_DDL` AND in `CODE_TOOL_DDL`, in the// same bytes — the `SESSION_LAUNCHES_TABLE` idiom: a fresh file runs version 1// (this whole list) and then this rung over the top of it, and a file already// on disk gets them here.// ---------------------------------------------------------------------------/// `cotton_agent_accounts` — one row per agent login any Mac in the household/// has seen, and the usage windows it last reported.////// It replaces `cotton_account_usage`, which was keyed by the account string/// and carried a reading and nothing else. The row here SURVIVES A LOGOUT: the/// devices page shows an account nobody is signed in as, with the age of its/// last reading, rather than forgetting a login the moment a Mac switches. That/// is why `seen_on_device_id` is a column and not the key.////// `provider` is the agent's vendor rather than the tool: one Anthropic login/// serves Claude Code on every Mac that has it, and a second tool from the same/// vendor would share the windows the row holds.////// **Cotton never touches the credential.** `email` is what the agent's own/// status line reports about the login it already has; there is no token, no/// cookie and no sign-in here ([one-claude-login-per-mac-switched-at-the-mac-never-risk-anthropi]).pubconst AGENT_ACCOUNTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_agent_accounts ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, provider TEXT NOT NULL, email TEXT NOT NULL, label TEXT, five_hour_pct REAL, five_hour_resets_at TEXT, weekly_pct REAL, weekly_resets_at TEXT, seen_at TEXT, seen_on_device_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, provider, email), CHECK (provider IN ('anthropic', 'openai')), CHECK (length(trim(email)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The accounts page's read: this workspace's logins, newest reading first.pubconst AGENT_ACCOUNTS_WORKSPACE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_agent_accounts_workspace ON cotton_agent_accounts (workspace_id, seen_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_AGENT_ACCOUNTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_agent_accounts_author ON cotton_agent_accounts (substr(_hlc, 20), _hlc)"#;/// `cotton_device_samples` — one reading of a Mac, every fifteen minutes.////// The device ROW carries the latest reading, the way `cotton_machines` did;/// this table is the thirty-day strip the devices page draws under it. Both/// numbers live in `cotton_core::rules::samples`, with the reason on them, and/// the `samples-retention` sweep deletes past the window. Sample history/// stays on the device that measured it (`table_specs::DEVICE_LOCAL_TABLES`).////// `sampled_at` is part of the natural key, so a helper that reports the same/// minute twice writes the same row twice rather than growing the strip.pubconst DEVICE_SAMPLES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_device_samples ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL, sampled_at TEXT NOT NULL, load1 REAL, mem_free_pct INTEGER, disk_free_gb REAL, sessions_running INTEGER, build_lock_held INTEGER, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, device_id, sampled_at), CHECK (length(trim(device_id)) > 0), CHECK (build_lock_held IS NULL OR build_lock_held IN (0, 1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The strip's read, and the sweep's: one Mac's readings, newest first.pubconst DEVICE_SAMPLES_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_samples_device ON cotton_device_samples (workspace_id, device_id, sampled_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_DEVICE_SAMPLES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_device_samples_author ON cotton_device_samples (substr(_hlc, 20), _hlc)"#;/// `cotton_account_usage_samples` — one reading of an agent account's windows,/// at the same fifteen-minute cadence and under the same thirty-day retention.////// Two percentages and nothing else: a window's reset time is a fact of the/// LATEST reading (it is on the account row), and a strip of reset times nobody/// draws would be a column written every quarter hour for no reader.pubconst ACCOUNT_USAGE_SAMPLES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_account_usage_samples ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, account_id TEXT NOT NULL, sampled_at TEXT NOT NULL, five_hour_pct REAL, weekly_pct REAL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, account_id, sampled_at), CHECK (length(trim(account_id)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The strip's read, and the sweep's: one account's readings, newest first.pubconst ACCOUNT_USAGE_SAMPLES_ACCOUNT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_account_usage_samples_account ON cotton_account_usage_samples (workspace_id, account_id, sampled_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_ACCOUNT_USAGE_SAMPLES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_account_usage_samples_author ON cotton_account_usage_samples (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 15 — a DECISION and a STOP travel as session messages// (Cotton note "The Code tool — why a Mac holds the sessions").//// Phase 3 left `session.decide` and `session.stop` real on the Mac holding the// session and refusing on the phone, because the answer has to reach a hook// blocked on another machine and no row carried it. This rung is that row: the// session message bus already replicates, already addresses a session, and// already has a lifecycle (`open → done`) a device's client can work. Two more// `kind`s on it, and the one column a permission answer needs, are the whole// change.//// **A CHECK is the one thing an ALTER cannot widen**, so the table is rebuilt —// the same shape `VAULT_DDL` rebuilds `cotton_secrets` in, for the same reason,// and with the same care about its external-content index: the triggers and// `fts_session_messages` are dropped BEFORE the table goes, re-created after,// and refilled with ONE `'rebuild'`. An entry's rowid IS its source row's, and// a copy renumbers them.//// **`request_ref` is a new column and not `reply_to`.** `reply_to` is a foreign// key into this table — the message being answered — and what a decision// answers is not a message at all: it is the agent's own pending permission id,// minted by the hook on the Mac and carried in `cotton_sessions.waiting_ref`.// Writing it into `reply_to` would be a foreign key pointing at a row that will// never exist, which SQLite would refuse and the fold would park.// ---------------------------------------------------------------------------/// `cotton_session_messages` — the bus, version 2 of it.////// Version 1 carried four kinds, all of them prose somebody typed. Version 15/// adds two that are a BUTTON rather than a sentence:////// * `decision` — what a person answered a permission prompt with (`allow`,/// `deny` or `allowSession`, in `body`), addressed to the session that is/// blocked, with `request_ref` naming the pending permission it answers;/// * `stop` — stop this session.////// Both are addressed `to_kind = 'session'` and both are worked by the CLIENT/// on the Mac that holds that session: it forwards to the helper and marks the/// message `done`. A decision the helper never took is not a decision, so the/// row moves only once the helper has confirmed.////// **A decision must name what it answers.** A `decision` with no/// `request_ref` could not be forwarded to anything — the helper releases a/// blocked hook BY ITS REQUEST ID — so the table refuses one rather than/// letting a card write a row nobody can act on.pubconst SESSION_MESSAGES_TABLE: &str = r#"CREATE TABLE cotton_session_messages ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, project_id TEXT, to_kind TEXT NOT NULL, to_session_id TEXT, from_kind TEXT NOT NULL, from_session_id TEXT, kind TEXT NOT NULL, body TEXT NOT NULL, reply_to TEXT, request_ref TEXT, thought_id TEXT, status TEXT NOT NULL DEFAULT 'open', claimed_by_session_id TEXT, claimed_at TEXT, done_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', media TEXT NOT NULL DEFAULT '[]' CHECK (json_type(media) = 'array'), _born TEXT, CHECK (to_kind IN ('owner', 'project', 'session')), CHECK (from_kind IN ('owner', 'session')), CHECK (kind IN ('instruction', 'question', 'answer', 'report', 'decision', 'stop')), CHECK (status IN ('open', 'claimed', 'done', 'withdrawn')), CHECK (length(trim(body)) > 0 AND length(body) <= 8000), CHECK (to_kind <> 'session' OR to_session_id IS NOT NULL), CHECK (to_kind <> 'project' OR project_id IS NOT NULL), CHECK (from_kind <> 'session' OR from_session_id IS NOT NULL), CHECK (kind NOT IN ('decision', 'stop') OR to_kind = 'session'), CHECK (kind <> 'decision' OR request_ref IS NOT NULL), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (to_session_id) REFERENCES cotton_sessions(id) )"#;/// What a session's own inbox reads — and, since version 15, what the device's/// client reads to find the decisions and stops addressed to the sessions it/// holds. One index, both questions: `(workspace_id, status, to_kind,/// to_session_id)` is a prefix match on `status = 'open' AND to_kind =/// 'session'` either way.pubconst SESSION_MESSAGES_ADDRESSED_INDEX: &str = r#"CREATE INDEX idx_cotton_session_messages_addressed ON cotton_session_messages (workspace_id, status, to_kind, to_session_id)"#;/// The project bus's read: what is open on a project.pubconst SESSION_MESSAGES_PROJECT_INDEX: &str = r#"CREATE INDEX idx_cotton_session_messages_project ON cotton_session_messages (workspace_id, project_id, status)"#;// ---------------------------------------------------------------------------// Version 16 — the REPO VIEWER (Cotton note "Code hosting — why a repository lives in Cotton").//// A project that names a repository gets that repository on the phone: its pull// requests with their checks, reviews and comments, its issues and its recent// commits. The INDEX is rows (a glance and a push notification both need it// offline) and the FILES are live, which is why there is no tree and no blob// table here.//// Five tables, none of them a primitive: nobody files a pull request, searches// for one across their life or links one to a project — the REPOSITORY is// linked by the project's own `repos` field and every row here hangs off a// repository. So `SUPPORTING_TABLES` carries all five with their reasons, and// there is no FTS, no version trigger and no bin.//// Every object below is in `SCHEMA_DDL` AND in `REPOS_DDL`, in the same bytes —// the `SESSION_LAUNCHES_TABLE` idiom: a fresh file runs version 1 (this whole// list) and then this rung over the top of it, and a file already on disk gets// them here.// ---------------------------------------------------------------------------/// `cotton_repos` — one row per repository any project names, and the worker's/// own state about it.////// `key` is `host/owner/name` with the host lowercased, which is what a/// project's `repos` field spells; the row id is what every screen and every/// route addresses, because a key carries slashes.////// The cursors and the sync state live HERE rather than in a server-side table:/// they are what lets the phone print "synced 2 min ago" and "no token"/// without a second read, and a workspace with no token is a STATE on this row/// rather than a worker somebody disabled.////// Since version 17 the row also says whether Cotton HOLDS the repository's/// bytes (Cotton note "Code hosting — why a repository lives in Cotton"). `held` and `origin` are separate/// facts on purpose: holding is about whose disk the bytes are on, and `origin`/// is about who accepts a push — a repository can be held by Cotton for weeks/// while Forgejo is still its origin, and a NULL `origin` reads as the host/// `kind`. `bundle_state` and `last_bundle_error` are the `repo-mirror`/// worker's own state, in words, for the same reason `sync_state` is: so the/// phone can print it offline. `kind` admits `cotton` and `sync_state` admits/// `held`, which is what version 17's rebuild is for.pubconst REPOS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repos ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, key TEXT NOT NULL, host TEXT NOT NULL, owner TEXT NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, default_branch TEXT, description TEXT, web_url TEXT NOT NULL, open_pulls INTEGER, open_issues INTEGER, sync_state TEXT NOT NULL DEFAULT 'pending', last_error TEXT, synced_at TEXT, pulls_cursor TEXT, issues_cursor TEXT, held INTEGER NOT NULL DEFAULT 0, origin TEXT, head_sha TEXT, held_at TEXT, bundle_state TEXT, last_bundle_error TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, key), CHECK (kind IN ('github', 'forgejo', 'cotton')), CHECK (sync_state IN ('pending', 'ok', 'no_token', 'error', 'unsupported', 'held')), CHECK (held IN (0, 1)), CHECK (origin IS NULL OR origin IN ('forgejo', 'github', 'cotton')), CHECK (bundle_state IS NULL OR bundle_state IN ('none', 'bundling', 'ok', 'error')), CHECK (length(trim(key)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_REPOS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repos_author ON cotton_repos (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_pulls` — every pull request the host has, kept.////// `checks` is the host's combined status for `head_sha`, one entry per/// context, and `checks_state` is the host's own verdict — NULL when the host/// has posted no status at all, which is a different answer from "pending" and/// the card says so. `mergeable` is NULL until the host has decided, because a/// guess there is a Merge button offered on a conflict. On a repository whose/// origin is Cotton the serving Mac IS the host and answers it off its own/// clone (`cotton-server`'s `repos::mergeable`), so NULL there means only that/// git could not be asked.////// `html_url` is nullable since version 17: a repository whose origin is Cotton/// has no web face, so there is no url to write and NULL is the honest answer/// rather than a link to a page nobody serves.pubconst REPO_PULLS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_pulls ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, number INTEGER NOT NULL, remote_id INTEGER, title TEXT NOT NULL, body TEXT, state TEXT NOT NULL, merged INTEGER NOT NULL DEFAULT 0, draft INTEGER NOT NULL DEFAULT 0, author TEXT, head_ref TEXT, head_sha TEXT, base_ref TEXT, mergeable INTEGER, additions INTEGER, deletions INTEGER, changed_files INTEGER, comments_count INTEGER, review_comments_count INTEGER, labels TEXT NOT NULL DEFAULT '[]', checks_state TEXT, checks TEXT NOT NULL DEFAULT '[]', html_url TEXT, remote_created_at TEXT, remote_updated_at TEXT, merged_at TEXT, closed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, merge_commit_sha TEXT, UNIQUE (workspace_id, repo_id, number), CHECK (state IN ('open', 'closed')), CHECK (merged IN (0, 1)), CHECK (draft IN (0, 1)), CHECK (mergeable IS NULL OR mergeable IN (0, 1)), CHECK (checks_state IS NULL OR checks_state IN ('pending', 'success', 'failure', 'error', 'warning')), CHECK (json_type(labels) = 'array'), CHECK (json_type(checks) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The pulls list's read: one repository's pulls in a state, newest remote/// update first.pubconst REPO_PULLS_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_pulls_repo ON cotton_repo_pulls (workspace_id, repo_id, state, remote_updated_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_REPO_PULLS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_pulls_author ON cotton_repo_pulls (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_issues` — every issue the host has, the pulls' shape without/// checks, branches or a merge.////// `html_url` is nullable since version 17, for the pulls' reason.pubconst REPO_ISSUES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_issues ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, number INTEGER NOT NULL, remote_id INTEGER, title TEXT NOT NULL, body TEXT, state TEXT NOT NULL, author TEXT, labels TEXT NOT NULL DEFAULT '[]', comments_count INTEGER, html_url TEXT, remote_created_at TEXT, remote_updated_at TEXT, closed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, number), CHECK (state IN ('open', 'closed')), CHECK (json_type(labels) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The issues list's read.pubconst REPO_ISSUES_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_issues_repo ON cotton_repo_issues (workspace_id, repo_id, state, remote_updated_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_REPO_ISSUES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_issues_author ON cotton_repo_issues (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_comments` — the timeline of a pull or an issue: plain comments,/// reviews with their verdict, and review comments with their place in the/// diff.////// `kind` is part of the natural key because a host numbers a comment, a review/// and a review comment in three different sequences, and two of them can carry/// the same `remote_id`.pubconst REPO_COMMENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_comments ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, target_kind TEXT NOT NULL, target_number INTEGER NOT NULL, kind TEXT NOT NULL, remote_id INTEGER NOT NULL, author TEXT, body TEXT, review_state TEXT, path TEXT, line INTEGER, html_url TEXT, remote_created_at TEXT, remote_updated_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, kind, remote_id), CHECK (target_kind IN ('pull', 'issue')), CHECK (kind IN ('comment', 'review', 'review_comment')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// One pull's or issue's timeline, in the order the host wrote it.pubconst REPO_COMMENTS_TARGET_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_comments_target ON cotton_repo_comments (workspace_id, repo_id, target_kind, target_number, remote_created_at)"#;pubconst AUTHOR_INDEX_COTTON_REPO_COMMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_comments_author ON cotton_repo_comments (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_commits` — the last two hundred commits on the default branch,/// per repository; the worker deletes past the window and the delete/// replicates like any other write.////// `html_url` is nullable since version 17, for the pulls' reason — and a held/// repository's commit opens Cotton's own commit page rather than leaving the/// app at all.pubconst REPO_COMMITS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_commits ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, sha TEXT NOT NULL, message TEXT NOT NULL, author_name TEXT, author_login TEXT, authored_at TEXT, parents TEXT NOT NULL DEFAULT '[]', html_url TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, sha), CHECK (json_type(parents) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The commits list's read: one repository's commits, newest first.pubconst REPO_COMMITS_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_commits_repo ON cotton_repo_commits (workspace_id, repo_id, authored_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_REPO_COMMITS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_commits_author ON cotton_repo_commits (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 17 — CODE HOSTING, phase 0 (Cotton note "Code hosting — why a repository lives in Cotton").//// A HELD repository is one whose bytes Cotton holds, whether a git host is// still its origin or Cotton is. That is six columns on `cotton_repos` a phone// prints offline ("held on 2 Macs, origin Forgejo"), two vocabularies widened,// and two tables: the bundles that ARE the replication of a repository's bytes,// and the releases mirrored off the host with their assets as media keys.//// **A CHECK is the one thing an ALTER cannot widen**, so `cotton_repos` is// REBUILT — the shape `VAULT_DDL` and `SESSION_DECISIONS_DDL` rebuild in. Two// things are different here and both are landmines://// 1. **`DROP TABLE` on a parent CASCADES.** SQLite performs an implicit// `DELETE FROM` before removing a table, and that delete fires every child's// `ON DELETE CASCADE`. `cotton_repos` has four children, so dropping it// would silently empty every pull request, issue, comment and commit on the// file. The ladder carries no foreign-keys-off mode (a `PRAGMA` inside an// open transaction is silently ignored, and every rung IS a transaction), so// the order below is the mechanism: the four children are copied out and// DROPPED FIRST, the parent is rebuilt with nothing pointing at it, and the// children are re-created and refilled afterwards.// 2. **The children need the same rebuild anyway.** `html_url` was NOT NULL on// pulls, issues and commits, and a repository whose origin is Cotton has no// web face at all — there is no url to write. So the carry-out they need to// survive the parent's rebuild is also the widening they need.//// Nothing is backfilled. `held` is `0` and `origin`, `head_sha`, `held_at`,// `bundle_state` and `last_bundle_error` are NULL on every row that already// existed, which is the honest reading of a repository nobody has held yet:// NULL `origin` reads as the host `kind`, and NULL `bundle_state` as "not held,// so nothing to say". A fresh file and an upgraded one end in identical stored// SQL, which `tests/schema_snapshot.rs` and `tests/migrate_v17_code_hosting.rs`// both say.//// No search index and no version trigger: neither new table is a record kind// (`SUPPORTING_TABLES` carries both with its reason), and the serving Mac's// `repo-mirror` worker is the only writer of either.// ---------------------------------------------------------------------------/// `cotton_repo_bundles` — the replication ledger of a repository's BYTES.////// Every replicated unit in Cotton is one immutable content-addressed object,/// and a bare clone is not one: it is a directory of loose files no holdings/// row, no mirror and no restore lane understands. A GIT BUNDLE is exactly that/// shape, so a repository replicates as a full bundle plus incremental ones,/// each an ordinary media object of kind `repo` (`{ws}/repos/{repo_id}/bundles//// {sha256}.bundle`), and it inherits the drain, the two-holder pull,/// `media-replicate`, the leave refusal and the content-address check with no/// new machinery.////// One row per bundle, written by the serving Mac alone. A STANDBY Mac applies/// them in `created_at` order from the newest full one; which bundles it has/// applied is a fact about its own disk and lives in a file beside its clone/// (`applied.json`), never in a row here.////// `basis_sha` is NULL for a full bundle and set for an incremental one, and/// the CHECK holds the two equal in both directions: an incremental bundle with/// no basis is a pack nobody can unbundle, and a full bundle with one is a lie/// about what it contains.pubconst REPO_BUNDLES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_bundles ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, object_key TEXT NOT NULL, kind TEXT NOT NULL, basis_sha TEXT, head_sha TEXT NOT NULL, refs_json TEXT NOT NULL DEFAULT '{}', bytes INTEGER NOT NULL, sha256 TEXT NOT NULL, superseded_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, sha256), CHECK (kind IN ('full', 'incremental')), CHECK ((kind = 'full') = (basis_sha IS NULL)), CHECK (bytes >= 0), CHECK (length(sha256) = 64), CHECK (length(trim(object_key)) > 0), CHECK (json_type(refs_json) = 'object'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// What a standby reads: one repository's bundles, oldest first, because that/// is the order they are applied in.pubconst REPO_BUNDLES_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_bundles_repo ON cotton_repo_bundles (workspace_id, repo_id, created_at)"#;pubconst AUTHOR_INDEX_COTTON_REPO_BUNDLES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_bundles_author ON cotton_repo_bundles (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_clones` — what ONE Mac's own clone of a held repository is/// doing (version 77): one row per (repository, device).////// `cotton_repos.bundle_state` is the SERVING Mac's mirror, and until 77 a/// standby's `repo-restore` wrote its fork into the same synced pair — so the/// two Macs overwrote each other every few minutes and the repository page/// flickered between "bundled" and the fork sentence. A fork is a fact about/// one Mac's clone and the mirror's state is a fact about another's: one/// synced column cannot hold both, so each Mac's clone has its own row here.////// **Exactly one writer per row, `cotton_media_holdings`' rule and for its/// reason**: a Mac writes only the row whose `device_id` is its own device/// key, so two Macs never race for one row, plain last-write-wins is correct/// and `fold::COLUMN_POLICIES` gains no entry. The id is DERIVED from the/// natural key (`derived_id::repo_clone_id`), so a second write of the same/// clone is a restatement of one row. The mirror never writes here; it writes/// `cotton_repos.bundle_state`, which is the serving Mac's own state.////// `state` is `forked` while this Mac's default branch has forked from the/// newest bundle (`sentence` names both commits), and `ok` once a bundle/// joins the two lines or every live bundle is applied here. No row is/// "nothing to say". Readers join `cotton_devices` and leave out a revoked/// device (`crate::repo_clones`), which only that device could clear.pubconst REPO_CLONES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_clones ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, device_id TEXT NOT NULL, state TEXT NOT NULL, sentence TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, device_id), CHECK (state IN ('ok', 'forked')), CHECK (length(trim(device_id)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The repository page's read: one repository's clones.pubconst REPO_CLONES_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_clones_repo ON cotton_repo_clones (workspace_id, repo_id, state)"#;pubconst AUTHOR_INDEX_COTTON_REPO_CLONES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_clones_author ON cotton_repo_clones (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_releases` — a repository's releases, with their assets as media/// keys.////// Mirrored from the host today and authored in Cotton in phase 2; the shape is/// the same either way, because what a release IS does not depend on who is/// holding the repository. `html_url` is nullable for the same reason it became/// nullable on the pulls: a repository whose origin is Cotton has no web face.////// `assets_json` is `[{name, key, bytes, contentType}]` and every `key` is a/// media key under `{ws}/repos/{repo_id}/releases/` — the bytes are an ordinary/// media object, so a release's 2 GB of nightly backups replicate, evict and/// restore like every other object, and a screen asks for one on a tap/// (`media.ensure`) rather than holding it.////// `tag` is the natural key rather than `remote_id`, because the tag is what a/// person names a release by and what survives a repository moving host.pubconst REPO_RELEASES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_releases ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, tag TEXT NOT NULL, name TEXT, body TEXT, draft INTEGER NOT NULL DEFAULT 0, prerelease INTEGER NOT NULL DEFAULT 0, target_sha TEXT, author TEXT, published_at TEXT, assets_json TEXT NOT NULL DEFAULT '[]', html_url TEXT, remote_id INTEGER, synced_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, tag), CHECK (draft IN (0, 1)), CHECK (prerelease IN (0, 1)), CHECK (length(trim(tag)) > 0), CHECK (json_type(assets_json) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The releases list's read: one repository's releases, newest published first.pubconst REPO_RELEASES_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_releases_repo ON cotton_repo_releases (workspace_id, repo_id, published_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_REPO_RELEASES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_releases_author ON cotton_repo_releases (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 18 — a mood is a MOMENT (`crates/cotton-core/src/primitives.rs`).//// The three objects below are in `SCHEMA_DDL` AND in `MOOD_MOMENTS_DDL`, in the// same bytes, the way the vault's and the repo viewer's are: a fresh file runs// version 1 and then every rung over the top, and a file already on disk gets// each object from its own rung. One declaration, two paths in.// ---------------------------------------------------------------------------/// `cotton_moods` — a MOMENT, version 2 of the table.////// The version-17 shape was `score INTEGER NOT NULL CHECK (score BETWEEN 1 AND/// 5)`, `word TEXT` (≤ 32), `line TEXT` (≤ 280) and `journal_date`. A mood was/// a number from one to five and an optional word for it. It is what the person/// SAID now, and the emotions named in what they said:////// * `score` and `word` are GONE. `score` cannot be dropped by an `ALTER` —/// SQLite will not remove a column carrying a CHECK — so version 18/// rebuilds the table, which is also what makes the other three changes/// free./// * `emotions` is a JSON array of vocabulary slugs/// (`cotton_core::rules::emotions`), `[]` for a moment nobody has named a/// feeling in yet. NOT NULL with a default, so no writer can leave it/// absent and no reader has to decide what absent means./// * `emotions_by` is the byline, `summary_by`'s rule exactly: a write/// carrying `assistant` refuses over a row that says `user`. It is what/// keeps the `mood-emotions` worker off a feeling the person named./// * `journal_date` is `local_day`. The column is the same derived stamp —/// the day the WRITER resolved in the owner's zone, which is what the/// nudge's "already recorded today" skip and the timeline's day headers/// read — but the word `journal` was the tangle this change exists to cut:/// a mood is not a property of a journal page and never was./// * `line` rises 280 → 1000. A spoken moment runs longer than a tweet.////// `fts_moods` still indexes `line` alone, so its three triggers are unchanged;/// the rung drops and re-creates them because a trigger goes with the table it/// is on.pubconst MOODS_TABLE: &str = r#"CREATE TABLE cotton_moods ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, at TEXT NOT NULL, line TEXT, emotions TEXT NOT NULL DEFAULT '[]', emotions_by TEXT NOT NULL DEFAULT 'assistant', local_day TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (line IS NULL OR (length(trim(line)) > 0 AND length(line) <= 1000)), CHECK (json_type(emotions) = 'array'), CHECK (emotions_by IN ('user', 'assistant')), CHECK (local_day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The day index — the nudge asks "does this day already hold a moment", and/// the timeline's headers group on the same column.pubconst MOODS_LOCAL_DAY_INDEX: &str =r#"CREATE INDEX idx_cotton_moods_local_day ON cotton_moods (workspace_id, local_day)"#;/// The instant index — the timeline is newest-first by `at`, never by day.pubconst MOODS_AT_INDEX: &str =r#"CREATE INDEX idx_cotton_moods_at ON cotton_moods (workspace_id, at DESC)"#;// ── version 19 — the records the owner writes ───────────────────────────────//// Phase 2 of Cotton note "Code hosting — why a repository lives in Cotton". `repository`, `pull`, `issue`,// `repo_comment` and `release` stop being supporting tables and become RECORD// KINDS, which is not a rename: a primitive's `Yes` on a facility is a CHECK// on some table in this file, and three of them have to be widened before the// registry may claim them.//// - `cotton_project_links.record_kind` admits `repository`, because a project// naming a repository IS the membership edge phase 2 makes the source of// truth (the project's `repos` field stays a mirror for one release).// - `cotton_links.from_kind` and `.to_kind` admit `repository`, `pull` and// `issue`, so a todo can point at the pull it is about.// - A CHECK is the one thing an ALTER cannot widen, so both are REBUILDS, in// `VAULT_DDL`'s shape and for its reason. Neither table has children, so// version 17's children-first order is not needed here — and that is worth// saying rather than leaving to be re-derived: `cotton_repos` needed it// because a `DROP TABLE` fires every child's `ON DELETE CASCADE`, and it has// EIGHT of them after this rung (pulls, issues, comments, commits, bundles,// releases, rules, labels) — which is what the next rung to rebuild it owes.//// Two new tables, both children of `cotton_repos`, so both are ordinary// creates: `cotton_repo_rules` (branch protection) and `cotton_repo_labels`.//// And search: `pull` and `issue` take `SearchLane::Fts`, so the rung creates// their two external-content indexes and the three triggers each, then fills// each one with a single `'rebuild'` — one pass per index, inside the cost// gate, never a per-row `INSERT … SELECT`./// `cotton_repo_rules` — branch protection, per repository per branch.////// The rule a merge is judged against: which check contexts must be green,/// how many approvals, whether a pull whose base has moved is out of date, and/// whether a direct push is allowed at all. Written by the `repos` worker when/// the origin is a host that has them, and by the owner's own/// `POST /v1/repos/{id}/rules` when the origin is Cotton.////// `required_contexts_json` is a JSON ARRAY of context names. An empty array/// and a NULL would be two spellings of "no context is required", so the/// column is NOT NULL with `'[]'` as its default and a CHECK that it is an/// array.pubconst REPO_RULES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_rules ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, branch TEXT NOT NULL, required_contexts_json TEXT NOT NULL DEFAULT '[]', required_approvals INTEGER NOT NULL DEFAULT 0, block_outdated INTEGER NOT NULL DEFAULT 0, allow_push INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, branch), CHECK (length(trim(branch)) > 0), CHECK (json_type(required_contexts_json) = 'array'), CHECK (required_approvals >= 0), CHECK (block_outdated IN (0, 1)), CHECK (allow_push IN (0, 1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The rules read: every rule of one repository, by branch.pubconst REPO_RULES_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_rules_repo ON cotton_repo_rules (workspace_id, repo_id, branch)"#;pubconst AUTHOR_INDEX_COTTON_REPO_RULES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_rules_author ON cotton_repo_rules (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_labels` — the labels a repository offers, so a screen can draw/// a pull's chips in the host's own colours without asking the Mac.////// `name` is the natural key rather than `remote_id`: a label is named by what/// it says, and the name is what a pull's `labels` array carries.pubconst REPO_LABELS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_labels ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, name TEXT NOT NULL, color TEXT, description TEXT, remote_id INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, name), CHECK (length(trim(name)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The labels read: one repository's labels, by name.pubconst REPO_LABELS_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_labels_repo ON cotton_repo_labels (workspace_id, repo_id, name)"#;pubconst AUTHOR_INDEX_COTTON_REPO_LABELS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_labels_author ON cotton_repo_labels (substr(_hlc, 20), _hlc)"#;/// `fts_repo_pulls` — the external-content index over `cotton_repo_pulls`/// (version 19).////// `title` and `body` and nothing else. A pull's `checks` and `labels` are/// JSON a person never searches for by word, and `head_ref` is already found/// by the branch screens.pubconst FTS_REPO_PULLS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_repo_pulls USING fts5( title, body, content = 'cotton_repo_pulls', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_repo_pulls` on insert.pubconst FTS_REPO_PULLS_AI: &str = r#"CREATE TRIGGER fts_repo_pulls_ai AFTER INSERT ON cotton_repo_pulls WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_pulls'), 0) BEGIN INSERT INTO fts_repo_pulls (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_repo_pulls` on delete.pubconst FTS_REPO_PULLS_AD: &str = r#"CREATE TRIGGER fts_repo_pulls_ad AFTER DELETE ON cotton_repo_pulls WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_pulls'), 0) BEGIN INSERT INTO fts_repo_pulls (fts_repo_pulls, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); END"#;/// `fts_repo_pulls` on update.pubconst FTS_REPO_PULLS_AU: &str = r#"CREATE TRIGGER fts_repo_pulls_au AFTER UPDATE OF title, body ON cotton_repo_pulls FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_pulls'), 0) AND (new.title IS NOT old.title OR new.body IS NOT old.body) BEGIN INSERT INTO fts_repo_pulls (fts_repo_pulls, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); INSERT INTO fts_repo_pulls (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_repo_issues` — the external-content index over `cotton_repo_issues`/// (version 19). The pulls' columns, for the pulls' reason.pubconst FTS_REPO_ISSUES_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_repo_issues USING fts5( title, body, content = 'cotton_repo_issues', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_repo_issues` on insert.pubconst FTS_REPO_ISSUES_AI: &str = r#"CREATE TRIGGER fts_repo_issues_ai AFTER INSERT ON cotton_repo_issues WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_issues'), 0) BEGIN INSERT INTO fts_repo_issues (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;/// `fts_repo_issues` on delete.pubconst FTS_REPO_ISSUES_AD: &str = r#"CREATE TRIGGER fts_repo_issues_ad AFTER DELETE ON cotton_repo_issues WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_issues'), 0) BEGIN INSERT INTO fts_repo_issues (fts_repo_issues, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); END"#;/// `fts_repo_issues` on update.pubconst FTS_REPO_ISSUES_AU: &str = r#"CREATE TRIGGER fts_repo_issues_au AFTER UPDATE OF title, body ON cotton_repo_issues FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_repo_issues'), 0) AND (new.title IS NOT old.title OR new.body IS NOT old.body) BEGIN INSERT INTO fts_repo_issues (fts_repo_issues, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); INSERT INTO fts_repo_issues (rowid, title, body) VALUES (new.rowid, new.title, new.body); END"#;// ── Version 20 — CI ──────────────────────────────────────────────────────────//// Phase 3 of Cotton note "Code hosting — why a repository lives in Cotton": Cotton hosts the jobs a stock// runner asks for. Four tables, no rebuild, no retirement, no added column and// no backfill — a file with no rows here reads as "nothing has run yet", which// is the honest answer until the first push after the rung.//// The SPLIT between the four is the decision worth stating, because it is a// split down the middle of one feature://// - `cotton_repo_runs` and `cotton_repo_jobs` are SYNCED like any other row.// The phone's runs list, the run page and the checks block on a pull all// read them, and a phone that is not the serving Mac has to be able to draw// a failed check offline.// - `cotton_repo_runners` and `cotton_repo_vars` are SERVER-ONLY// (`table_specs::SERVER_ONLY_TABLES` carries the written reason for each).// A runner is a process on one machine and a var is an input to a process;// neither has a screen on a phone, and a runner's row is meaningless away// from the server that admitted it.//// **A log is never a row.** `UpdateLog` appends to a FILE on the serving Mac// (`~/CottonDB/runs/<run>/<job>.log`) and the finished file is filed as one// media object of kind `repo`; what the job row keeps is the line count, the// ack the runner is trimmed by, and the media key. Ten thousand lines of// `cargo test` output is not something every device should hold as rows.//// And NO search index: a run is found by its repository and its number, never// by a word in it. That is why this rung adds no FTS table, no trigger and no// conformance vector./// `cotton_repo_runners` — one row per runner this server has admitted.////// SERVER-ONLY. The `uuid` is the identity the runner sends back in/// `x-runner-uuid` on every call; the TOKEN it sends beside it is never here —/// its hash lives in `registry.db`'s `code_credentials`, scope `runner`, and/// `credential_id` is the link. Nothing in a person's own file can be replayed/// as a credential.////// `repo_id` NULL is a runner that takes work from EVERY repository in the/// workspace, which is what both of the owner's runners are. A non-null one is/// a runner admitted for a single repository — the narrower promise, and the/// one a shared machine would be registered under.////// `device_id` is set when the runner is a Mac's own bundled helper, so a/// Settings screen can say "this Mac" rather than reciting a uuid, and so the/// machines list can join a declared Mac to the runner that actually polled.////// **THE RULE, EXACTLY**: the server writes the device that minted the/// registration token, and only when that device's `cotton_devices.name` is the/// runner's own `name` (trimmed, exact) — which is the self-registering path, a/// Mac passing `machine_name()` as both. It is NULL for the Linux box, whose/// token was minted on some other machine and whose name matches no device/// here.pubconst REPO_RUNNERS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_runners ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT, uuid TEXT NOT NULL, name TEXT NOT NULL, labels_json TEXT NOT NULL DEFAULT '[]', device_id TEXT, credential_id TEXT NOT NULL, version TEXT, last_seen_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, uuid), CHECK (length(trim(uuid)) > 0), CHECK (length(trim(name)) > 0), CHECK (length(trim(credential_id)) > 0), CHECK (json_type(labels_json) = 'array'), CHECK (repo_id IS NULL OR length(repo_id) > 0), CHECK (device_id IS NULL OR length(device_id) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The runners read: every runner of one workspace, most recently seen first.pubconst REPO_RUNNERS_WORKSPACE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_runners_workspace ON cotton_repo_runners (workspace_id, last_seen_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_REPO_RUNNERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_runners_author ON cotton_repo_runners (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_runs` — one workflow run.////// `index_in_repo` is the number a person says out loud ("run 3619") and it is/// UNIQUE per repository, which is what makes `/repos/{id}/runs/{n}` a URL/// rather than a uuid to copy. It is assigned by the `ci` worker as/// `max + 1` inside the transaction that writes the run.////// `workflow` is the FILE's name (`pr-checks.yml`) because that is what a/// person greps for and what `pnpm forge run dispatch` names; `workflow_name`/// is the `name:` inside it, for a screen.////// `status` and `conclusion` are the two-column shape both git hosts use and/// both runners expect: while a run is `queued` or `in_progress` its/// conclusion is NULL, and a `completed` run has one. A single column would/// have to spell "finished, but we do not know how", which is not a state this/// server can be in.////// `triggered_by` is WHO, never what — the event is its own column. `worker`/// is a ref that moved or a pull that opened, `owner` is a dispatch or a rerun/// from the app or `pnpm forge`, `schedule` is a cron tick.////// `pull_id` is set for a `pull_request` run and names the row the checks/// entry is written onto. It is TEXT and NOT a foreign key, for two reasons/// that point the same way. A run HAPPENED, and it stays true after the pull/// row it was about has been re-read away — the same argument `runner_uuid`/// makes one table down. And a foreign key here would break a rung that has/// already shipped: version 1 builds every table, so version 17's rebuild of/// `cotton_repos` cascades into this one, and SQLite resolves a cascading/// row's OWN foreign keys as it deletes it — pointing at `cotton_repo_pulls`/// while version 17 has it dropped and not yet re-created answers/// `no such table: main.cotton_repo_pulls` and the ladder stops at rung 17.pubconst REPO_RUNS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_runs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, index_in_repo INTEGER NOT NULL, workflow TEXT NOT NULL, workflow_name TEXT, event TEXT NOT NULL, ref TEXT NOT NULL, sha TEXT NOT NULL, pull_id TEXT, status TEXT NOT NULL DEFAULT 'queued', conclusion TEXT, triggered_by TEXT NOT NULL DEFAULT 'worker', started_at TEXT, finished_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, index_in_repo), CHECK (index_in_repo > 0), CHECK (length(trim(workflow)) > 0), CHECK (event IN ('push', 'pull_request', 'merge_group', 'schedule', 'workflow_dispatch')), CHECK (length(trim(ref)) > 0), CHECK (length(sha) BETWEEN 7 AND 64), CHECK (status IN ('queued', 'in_progress', 'completed')), CHECK (conclusion IS NULL OR conclusion IN ('success', 'failure', 'cancelled', 'skipped', 'timed_out')), CHECK (status <> 'completed' OR conclusion IS NOT NULL), CHECK (status = 'completed' OR conclusion IS NULL), CHECK (triggered_by IN ('worker', 'owner', 'schedule')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (repo_id) REFERENCES cotton_repos(id) )"#;/// The runs read: one repository's runs, newest number first.pubconst REPO_RUNS_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_runs_repo ON cotton_repo_runs (workspace_id, repo_id, index_in_repo DESC)"#;/// The checks read: every run of one head commit, which is how a pull's/// checks block is assembled without scanning the repository's runs.pubconst REPO_RUNS_SHA_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_runs_sha ON cotton_repo_runs (workspace_id, repo_id, sha)"#;pubconst AUTHOR_INDEX_COTTON_REPO_RUNS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_runs_author ON cotton_repo_runs (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_jobs` — one job of one run, and the only row a runner writes.////// `index_in_run` is the job's place in the plan (`needs` order, one-based), so/// a screen draws them the way the file reads.////// `runs_on` is ONE label, not a list: the dialect admits one and the fetch/// compares it against what the runner declared. A list would be a matrix, and/// there is no matrix.////// The three log columns are the whole of "a log is a file":/// - `log_lines` is how many lines are durably on disk;/// - `log_ack` is the index the runner is told to trim to — never ahead of/// `log_lines`, because a runner that is acked past what was stored treats/// its own submitted logs as lost and gives up;/// - `log_key` is the media object the finished file was filed as, NULL until/// the job ends.////// `cancel_requested` is the cancellation CHANNEL. The protocol has no cancel/// RPC and no push, so a cancel — from `concurrency`, from a timeout or from/// the owner's own button — is a flag here that the job's next `UpdateTask`/// answer carries back to the runner.////// `runner_uuid` is TEXT and not a foreign key: a job that ran on a runner the/// owner has since deleted still says which one it ran on, and a row that/// forgot would be a row that cannot answer "where did this fail".////// `task_id` is the number THE RUNNER knows this job by. The protocol's/// `Task.id` is an `int64` and `UpdateLog` / `UpdateStepSummary` key by it, so/// a uuid cannot be the handle; it is assigned per WORKSPACE as `max + 1`. What/// this column enforces is `UNIQUE (workspace_id, task_id)` among LIVE rows —/// the never-reused promise the proto's own comment asks for is the service's/// (`ci/handout.rs`), and it is only as strong as the rows: jobs cascade away/// with their run, and `max + 1` over what is left can hand a number out again./// That is a gap a run nobody deleted cannot reach, and it is written here/// rather than implied by a stronger sentence than the schema keeps./// `max(task_id)` is also the `tasks_version` a `FetchTask` answers — a number/// that only ever rises when a job is born is exactly the signal the runner/// compares to decide whether to ask again.////// `requeues` is what makes "a runner silent for five minutes re-queues the/// job ONCE" expressible. A machine that dies mid-job would otherwise have its/// work handed out again for ever, and a job that fails the same way on every/// runner would go round the workspace; the count is the only place that/// promise can be kept, because nothing else on the row remembers.////// `token_digest` (version 44) is the SHA-256 of the `run` token handed out/// with the job (`cotton_core::vault::code_tokens::digest`). A `run` token has/// no `cotton_code_credentials` row — the job IS its grant — so this is where/// the digest that admits it after a workspace key rotation lives. Rewritten/// when a re-queued job is handed out again, because that mints a new token.pubconst REPO_JOBS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_jobs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, run_id TEXT NOT NULL, index_in_run INTEGER NOT NULL, task_id INTEGER NOT NULL, name TEXT NOT NULL, runs_on TEXT NOT NULL, needs_json TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL DEFAULT 'queued', conclusion TEXT, runner_uuid TEXT, timeout_minutes INTEGER, outputs_json TEXT NOT NULL DEFAULT '{}', steps_json TEXT NOT NULL DEFAULT '[]', summary TEXT, log_lines INTEGER NOT NULL DEFAULT 0, log_ack INTEGER NOT NULL DEFAULT 0, log_key TEXT, cancel_requested INTEGER NOT NULL DEFAULT 0, requeues INTEGER NOT NULL DEFAULT 0, started_at TEXT, finished_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, token_digest TEXT, UNIQUE (workspace_id, run_id, index_in_run), UNIQUE (workspace_id, task_id), CHECK (index_in_run > 0), CHECK (task_id > 0), CHECK (length(trim(name)) > 0), CHECK (length(trim(runs_on)) > 0), CHECK (json_type(needs_json) = 'array'), CHECK (json_type(outputs_json) = 'object'), CHECK (json_type(steps_json) = 'array'), CHECK (status IN ('queued', 'in_progress', 'completed')), CHECK (conclusion IS NULL OR conclusion IN ('success', 'failure', 'cancelled', 'skipped', 'timed_out')), CHECK (status <> 'completed' OR conclusion IS NOT NULL), CHECK (status = 'completed' OR conclusion IS NULL), CHECK (timeout_minutes IS NULL OR timeout_minutes > 0), CHECK (log_lines >= 0), CHECK (log_ack >= 0), CHECK (log_ack <= log_lines), CHECK (cancel_requested IN (0, 1)), CHECK (requeues >= 0), CHECK (summary IS NULL OR length(summary) <= 65536), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (run_id) REFERENCES cotton_repo_runs(id) )"#;/// The jobs read: one run's jobs, in plan order.pubconst REPO_JOBS_RUN_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_jobs_run ON cotton_repo_jobs (workspace_id, run_id, index_in_run)"#;/// `cotton_repo_jobs (run_id)` — the index a run's DELETE needs (version 94).////// `run_id` is a foreign key to `cotton_repo_runs`, and SQLite checks a/// parent's delete by looking for children through an index that LEADS with/// the key's column. [`REPO_JOBS_RUN_INDEX`] leads with `workspace_id`, so/// without this one every deleted run read every job of the file: the prune/// erases runs by the thousand, and that was the one cost of its act that/// still grew with the file (12.8k steps a run at 4,300 jobs; the guard/// `deleting_a_run_reads_its_own_jobs_and_never_the_table` has the numbers).pubconst REPO_JOBS_RUN_ID_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_jobs_run_id ON cotton_repo_jobs (run_id)"#;/// THE OUTBOX: the messages still waiting to go out, by channel and age/// (version 95).////// Every sender asks "which of this channel's texts are queued or sending" —/// the WhatsApp pass every two seconds, the Instagram one beside it — and no/// index led with either column, so each pass read every message of the file/// to find, nearly always, none: 683,907 steps a pass on the owner's personal/// database, under the file's hold (the serving Mac, 11 Oct 2026, the hold named at/// `cotton-ffi/src/shell/client.rs:3510`). PARTIAL, over the two unsent states/// alone: it holds a handful of rows on a file of any size, costs an ordinary/// message's write nothing, and a sender's question — which must say/// `send_state IN ('queued', 'sending')` in those words to be given it — is/// answered from it in the order it is asked for.pubconst MSG_OUTBOX_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_msg_messages_outbox ON cotton_msg_messages (channel, created_at, id) WHERE send_state IN ('queued', 'sending')"#;/// The FETCH read, and the one that has to be cheap: the queued jobs of a/// workspace, oldest first, which is what a runner asks for every two seconds.pubconst REPO_JOBS_QUEUE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_jobs_queue ON cotton_repo_jobs (workspace_id, status, created_at)"#;pubconst AUTHOR_INDEX_COTTON_REPO_JOBS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_jobs_author ON cotton_repo_jobs (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_vars` — a repository's CI variables, the plain half of the/// pair whose secret half is the vault.////// SERVER-ONLY, and the reason is not secrecy: a var is an INPUT to a process/// on a machine, set once beside the workflow that reads it, and no screen on/// a phone shows one. What makes the distinction load-bearing is the other/// half — a SECRET is a `cotton_secrets` row under service `ci.<repo_id>`,/// sealed, and nothing here is. A value in this table is stored in the clear/// and a person putting a token in one has put a token in the clear, which is/// why the vault is the answer for anything that matters and this table is for/// `RUST_BACKTRACE`.////// `name` is GLOB-checked rather than merely non-empty: a variable reaches the/// job as an environment variable, and a name with a space or a quote in it is/// a name no shell can read.pubconst REPO_VARS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_vars ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, name TEXT NOT NULL, value TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, repo_id, name), CHECK (length(trim(name)) > 0), CHECK (name NOT GLOB '*[^A-Za-z0-9_]*'), CHECK (length(value) <= 65536), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The vars read: one repository's variables, by name.pubconst REPO_VARS_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_vars_repo ON cotton_repo_vars (workspace_id, repo_id, name)"#;pubconst AUTHOR_INDEX_COTTON_REPO_VARS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_vars_author ON cotton_repo_vars (substr(_hlc, 20), _hlc)"#;// ── version 22 — which Macs run jobs, declared from the phone ────────────────//// Cotton note "Code hosting — why a repository lives in Cotton" § Runners. Version 20 shipped the toggle// as three keys in `<dataDir>/env` — `COTTON_RUNNER_ENABLED`,// `COTTON_RUNNER_LABELS`, `COTTON_RUNNER_CAPACITY` — with a written reason:// which Mac runs jobs is a fact about THAT MACHINE, and a// `cotton_workspaces` column would have made every Mac of the household start// taking work the moment one was asked to.//// The reason was right and the conclusion was wrong. A per-WORKSPACE row would// have done that; a per-DEVICE row cannot, because a Mac reads the row whose// `device_id` is its own and no other. What the env keys actually cost was the// owner having to sit at each machine in turn, and nothing at all running// until he did. So the setting becomes what the peer and media roles already// are: **a synced declaration the machine applies to itself.**/// `cotton_machine_runners` — one row per Mac: does it run jobs, which labels,/// how many at once.////// **SYNCED, and that is the whole point.** The phone writes the row and the/// Mac obeys it; a server-only table would put the declaration back on the/// machine it is about.////// `device_id` is `cotton_devices.device_id` — the KEY, not the row id, because/// that is what a Mac knows about itself before it has read anything. There is/// deliberately **no foreign key**: `cotton_secret_placements` is the/// precedent, and for the same reason — a declaration about a machine outlives/// the approval row, and a revoked device whose declaration vanished would read/// as a Mac nobody ever asked to run anything.////// `enabled` defaults to **1**. A Mac nobody has said anything about runs the/// PR checks, because that is the answer the owner wanted when he said nothing/// rather than a household of idle machines; `labels_json` defaults to the/// checks label alone and never to the signing one, which a Mac is given/// only when its keychain can sign or a person asks.////// The label VOCABULARY is not a CHECK and cannot be: SQLite admits no/// subquery in one, so `json_each` is out of reach. What the CHECKs hold is the/// SHAPE — an array, between one and THREE entries, each a non-empty string —/// and the three names are refused by name on the route/// (`cotton_core::rules::machine_runners::refuse_declaration`), where the/// refusal can be a sentence instead of a constraint failure.pubconst MACHINE_RUNNERS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_machine_runners ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(trim(device_id)) > 0), enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)), labels_json TEXT NOT NULL DEFAULT '["cotton-checks-mac:host"]', capacity INTEGER NOT NULL DEFAULT 1 CHECK (capacity BETWEEN 1 AND 4), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, ai_levels TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(ai_levels) AND json(ai_levels) IN ('[]', '[1]', '[2]', '[3]', '[1,2]', '[1,3]', '[2,1]', '[2,3]', '[3,1]', '[3,2]', '[1,2,3]', '[1,3,2]', '[2,1,3]', '[2,3,1]', '[3,1,2]', '[3,2,1]')), UNIQUE (workspace_id, device_id), CHECK (json_type(labels_json) = 'array'), CHECK (json_array_length(labels_json) BETWEEN 1 AND 3), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// What a Mac reads on every pass: its OWN row, by the key it knows itself by.pubconst MACHINE_RUNNERS_DEVICE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_machine_runners_device ON cotton_machine_runners (workspace_id, device_id)"#;pubconst AUTHOR_INDEX_COTTON_MACHINE_RUNNERS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_machine_runners_author ON cotton_machine_runners (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 23 — ONE OBJECT (Cotton note "The Code tool — why a Mac holds the sessions").//// The launch and the session were two rows for one thing: the owner asked in// `cotton_session_launches`, a Mac started it, and `cotton_sessions` appeared// beside it joined by an id the launcher had minted. Two rows meant two// lifecycles, two reads, two cards and a queue that could disagree with itself.// This rung folds the launch INTO the session: `cotton_sessions` is the one// object, from `queued` to `ended`, and `cotton_session_launches` is RETIRED.//// What the fold needs that an ALTER cannot give://// * `state` has to admit `queued`, `failed` and `withdrawn`, and a CHECK is// the one thing an ALTER cannot widen;// * `external_id`, `machine` and `started_at` have to become NULLABLE,// because a queued session has no agent behind it yet and NOT NULL is not// a thing an ALTER can take back;// * `launch_id` goes, because there is nothing left to point at.//// So `cotton_sessions` is REBUILT, and it is the second table the ladder has// rebuilt that has CHILDREN — `cotton_prompts` and `cotton_session_messages`,// both `ON DELETE CASCADE`. SQLite's `DROP TABLE` performs an implicit// `DELETE FROM`, which fires every one of those cascades, and a `PRAGMA// foreign_keys` inside an open transaction is silently ignored (every rung IS// one). So the ORDER below is the mechanism, exactly as `CODE_HOSTING_DDL`'s// is: children out and dropped first, parent rebuilt with nothing pointing at// it, children back. Both children carry an EXTERNAL-CONTENT search index, so// their triggers and FTS tables go first and come back last, refilled with one// `'rebuild'` apiece — an entry's rowid IS its source row's, and a copy// renumbers them.//// The three dispatch-mode settings go with the modes themselves:// `cotton_memory_projects.dispatch_mode`, `cotton_workspaces.dispatch_paused`// and `cotton_devices.dispatch_paused`. They are `ALTER TABLE … DROP COLUMN`s// rather than rebuilds — nothing indexes them and no other CHECK names them —// and version 1 no longer declares any of the three, so a FRESH file gets each// one from version 14's `AddedColumn` and loses it here, ending in the same// bytes an upgraded file does. `sessions_cap` and `session_permission_default`// STAY: a cap is how many sessions a Mac may hold and a default is what the// form opens on, and neither was ever a mode.// ---------------------------------------------------------------------------/// `cotton_sessions` — the ONE object, version 2 of it (version 23).////// A row is born `queued` when the owner asks for a session, with `device_id`/// set if they picked a Mac and NULL if they left it to Cotton; the `dispatch`/// worker fills a NULL one in or writes `hold_reason` saying why it could not;/// the chosen Mac's client claims it (`starting`), spawns the agent/// (`running`), and the agent's own hooks carry it through `idle`, `waiting`/// and `ended`. `failed` is a session that could not be started or died/// starting, with the sentence in `error`; `withdrawn` is one the owner took/// back before a Mac picked it up.////// **`state` stays NULLABLE**, for the reason version 14 gives: a session/// `log_session` registers from an agent's own hook — and every session logged/// before the Code tool existed — has no state anybody observed, and NULL is/// the honest answer where `'starting'` would be a guess.////// **`external_id`, `machine` and `started_at` are nullable now.** A queued/// session has no agent session id, has not been placed on a machine, and has/// not started; NOT NULL there would have meant inventing all three at the/// moment somebody pressed Start. `UNIQUE (tool, external_id)` still holds,/// and SQLite admits any number of NULLs in one — which is exactly right, since/// what it protects against is two rows claiming ONE agent session.////// **`requested_device_id` is what the OWNER asked for and `device_id` is/// where it went.** NULL asked means "any Mac"; `chosen_by` says which of the/// two decided. Keeping them apart is what lets the card say *"you picked mac-b"*/// after the dispatcher has moved nothing, and what stops a dispatcher's pick/// from reading afterwards as the owner's.////// **`hold_reason` is a SENTENCE and it is capped at 200 characters**, because/// a queue that goes quiet is the failure this design is most afraid of: a/// queued row that nothing placed says why, in words, on the card/// (`cotton_core::rules::dispatch`). It is cleared the moment the row is/// placed.////// `todo_database` (version 53) names the database `todo_id` lives in when it/// is not this one; NULL is this one. The two are a soft pair/// (`table_specs::SOFT_REF_DATABASES`), so `todo_id` carries no foreign key: a/// todo in another database is never a row of this file.pubconst SESSIONS_TABLE: &str = r#"CREATE TABLE cotton_sessions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, project_id TEXT, tool TEXT NOT NULL, external_id TEXT, machine TEXT, repo_url TEXT, branch TEXT, cwd TEXT, started_at TEXT, last_active_at TEXT NOT NULL, ended_at TEXT, summary TEXT, title TEXT, shipped TEXT NOT NULL DEFAULT '[]', turn_count INTEGER NOT NULL DEFAULT 0, prompt_count INTEGER NOT NULL DEFAULT 0, transcript_ref TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', account TEXT, listened_at TEXT, model TEXT, _born TEXT, device_id TEXT, state TEXT CHECK (state IS NULL OR state IN ('queued', 'starting', 'running', 'idle', 'waiting', 'ended', 'failed', 'withdrawn')), state_at TEXT, waiting_kind TEXT CHECK (waiting_kind IS NULL OR waiting_kind IN ('permission', 'question', 'input')), waiting_ref TEXT, last_line TEXT CHECK (last_line IS NULL OR length(last_line) <= 280), exit_code INTEGER, permission_mode TEXT CHECK (permission_mode IS NULL OR permission_mode IN ('bypass', 'ask')), host_owned INTEGER NOT NULL DEFAULT 0 CHECK (host_owned IN (0, 1)), todo_id TEXT, requested_device_id TEXT, chosen_by TEXT CHECK (chosen_by IS NULL OR chosen_by IN ('owner', 'dispatcher')), prompt TEXT NOT NULL DEFAULT '', hold_reason TEXT CHECK (hold_reason IS NULL OR length(hold_reason) <= 200), claimed_at TEXT, report_message_id TEXT, error TEXT, kind TEXT NOT NULL DEFAULT 'thread' CHECK (kind IN ('conversation', 'thread')), parent_session_id TEXT, todo_database TEXT CHECK (todo_database IS NULL OR length(todo_database) > 0), trashed_at TEXT, UNIQUE (tool, external_id), CHECK (tool IN ('claude-code', 'codex', 'kimi', 'gemini', 'opencode', 'other')), CHECK (external_id IS NULL OR length(trim(external_id)) > 0), CHECK (machine IS NULL OR length(trim(machine)) > 0), CHECK ((summary IS NULL) OR (length(summary) <= 2000)), CHECK ((title IS NULL) OR (length(title) <= 140)), CHECK (json_type(shipped) = 'array'), CHECK (turn_count >= 0), CHECK (prompt_count >= 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The sessions log's read: this workspace's sessions, the freshest first.pubconst SESSIONS_RECENT_INDEX: &str = r#"CREATE INDEX idx_cotton_sessions_recent ON cotton_sessions (workspace_id, last_active_at DESC)"#;/// A project's own sessions.pubconst SESSIONS_PROJECT_INDEX: &str = r#"CREATE INDEX idx_cotton_sessions_project ON cotton_sessions (project_id, last_active_at DESC) WHERE project_id IS NOT NULL"#;/// What `list_sessions {machine}` reads.pubconst SESSIONS_MACHINE_INDEX: &str = r#"CREATE INDEX idx_cotton_sessions_machine ON cotton_sessions (workspace_id, machine, last_active_at DESC)"#;/// THE QUEUE (version 23): what the `dispatch` worker reads to find the rows/// no Mac holds, and what each Mac's own client reads to find the rows it/// holds. One index, both questions — `(workspace_id, state, device_id)` is a/// prefix match on `state = 'queued'` either way.pubconst SESSIONS_QUEUE_INDEX: &str = r#"CREATE INDEX idx_cotton_sessions_queue ON cotton_sessions (workspace_id, state, device_id)"#;/// AT MOST ONE CONVERSATION PER PROJECT (version 31).////// Partial and SINGLE-COLUMN, because a CHECK spanning `kind` and `project_id`/// is what a synced table may not carry (`tests/no_cross_column_checks.rs`): a/// row arrives as a FRAGMENT, one op per column stamp, so "a conversation has/// a project" is enforced where the row is BORN/// (`cotton_tools::session_birth::ensure_conversation`) and never on the file.////// What the index is really for is the FILE's last word, not the lookup: the/// conversation's id is DERIVED from `(workspace, project)`, so two devices/// opening one project's conversation at once arrive at the SAME row and the/// fold merges them rather than one being rejected. The index is what makes a/// second row with a minted uuid impossible even so.pubconst SESSIONS_CONVERSATION_INDEX: &str = r#"CREATE UNIQUE INDEX IF NOT EXISTS idx_cotton_sessions_conversation ON cotton_sessions (project_id) WHERE kind = 'conversation'"#;/// A conversation's THREADS, freshest first (version 31) — what/// `list_sessions { parent }` reads.pubconst SESSIONS_PARENT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_sessions_parent ON cotton_sessions (parent_session_id, last_active_at DESC) WHERE parent_session_id IS NOT NULL"#;/// `cotton_prompts` — a session's turns, and a CHILD of `cotton_sessions`.////// Declared as a constant since version 23, for the reason/// [`SESSION_MESSAGES_TABLE`] is: the rung that rebuilds the parent has to take/// this table off the file first and put it back in the SAME BYTES version 1/// issues, and two hand-written copies of one CREATE are two things to keep/// equal.pubconst PROMPTS_TABLE: &str = r#"CREATE TABLE cotton_prompts ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, session_id TEXT NOT NULL, project_id TEXT, seq INTEGER NOT NULL, ts TEXT NOT NULL, text TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'assistant')), _born TEXT, UNIQUE (session_id, seq), CHECK (seq >= 0), CHECK ((length(trim(text)) > 0) AND (length(text) <= 8000)), FOREIGN KEY (session_id) REFERENCES cotton_sessions(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// Every prompt of one workspace — what the FTS join reads back.pubconst PROMPTS_WORKSPACE_INDEX: &str = r#"CREATE INDEX idx_cotton_prompts_workspace ON cotton_prompts (workspace_id)"#;/// One session's turns. Every reader of a session's turns names the workspace/// and the session; a file holds one workspace, so the index above is every/// turn in it, and without this one a session's turns were read by walking/// them all (8.3 s under `log_session` on a file of 262,000, 11 Oct 2026).pubconst PROMPTS_SESSION_INDEX: &str = r#"CREATE INDEX idx_cotton_prompts_session ON cotton_prompts (workspace_id, session_id, seq)"#;/// The OPEN queue, and why version 26 matters to it: the partial index is on/// `resolved_at IS NULL`, so a verdict that stamps the column takes its row out/// of the queue and one that does not leaves it in for ever.pubconst FEEDBACK_OPEN_INDEX: &str = r#"CREATE INDEX idx_cotton_feedback_open ON cotton_feedback (workspace_id, created_at DESC) WHERE resolved_at IS NULL"#;pubconst FEEDBACK_PARENT_INDEX: &str = r#"CREATE INDEX idx_cotton_feedback_parent ON cotton_feedback (parent_id) WHERE parent_id IS NOT NULL"#;pubconst FEEDBACK_CAPTURE_INDEX: &str = r#"CREATE INDEX idx_cotton_feedback_capture ON cotton_feedback (workspace_id, app, created_at) WHERE app IS NOT NULL"#;pubconst FEEDBACK_PERSON_INDEX: &str = r#"CREATE INDEX idx_cotton_feedback_person ON cotton_feedback (person_id, created_at) WHERE person_id IS NOT NULL"#;pubconst FEEDBACK_SAME_AS_INDEX: &str = r#"CREATE INDEX idx_cotton_feedback_same_as ON cotton_feedback (same_as) WHERE same_as IS NOT NULL"#;/// `cotton_feedback` at version 33 — a report about the APP, and nothing else.////// Three columns are gone with the record kinds that gave them meaning:/// `walkthrough_id`, `screen_id` and `run_screen_id` each named a row in a/// table version 33 drops ([`RETIRE_WALKTHROUGHS_DDL`]). Dropping their parent/// tables and leaving the columns would leave three foreign keys pointing at/// names the file no longer has, and SQLite answers the next INSERT into this/// table with "no such table" — so the rebuild is not tidying, it is what makes/// the retirement legal.////// The three CHECKs that spanned those columns go with them, and the census in/// `tests/no_cross_column_checks.rs` shrinks by four: the `<= 1` target count/// is now a count of ONE column, which is not a constraint at all./// `app` is the only target a report has left, and the pair/// `CHECK ((image_sha256 IS NULL) OR (app IS NOT NULL))` already says a/// screenshot belongs to one.pubconst FEEDBACK_TABLE: &str = r#"CREATE TABLE "cotton_feedback" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, image_sha256 TEXT, image_ext TEXT, x REAL, y REAL, body TEXT NOT NULL, author_kind TEXT NOT NULL, author_user_id TEXT, author_label TEXT, person_id TEXT, same_as TEXT, share_id TEXT, app TEXT, context TEXT, status TEXT NOT NULL DEFAULT 'open', resolved_at TEXT, resolved_by_kind TEXT, resolved_by_label TEXT, resolution_note TEXT, parent_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK ((image_sha256 IS NULL) OR (app IS NOT NULL)), CHECK ((image_sha256 IS NULL) = (image_ext IS NULL)), CHECK ((x IS NULL) = (y IS NULL)), CHECK ((x IS NULL) OR (app IS NULL) OR (image_sha256 IS NOT NULL)), CHECK (length(trim(body)) > 0), CHECK (author_kind IN ('user', 'agent', 'guest')), CHECK ((author_kind = 'user') = (author_user_id IS NOT NULL)), CHECK ((author_kind = 'user') OR (author_label IS NOT NULL)), CHECK (same_as IS NULL OR same_as <> id), CHECK ((same_as IS NULL) OR (parent_id IS NULL)), CHECK (context IS NULL OR json_type(context) = 'object'), CHECK (status IN ('open', 'agreed', 'declined', 'shipped', 'resolved', 'dismissed')), CHECK (resolved_by_kind IN ('user', 'agent')), FOREIGN KEY (parent_id) REFERENCES cotton_feedback(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_memories` at version 34 — **one sentence, with no separate temporal/// state.**////// Three columns are gone: `dated`, `next_review_at` and `review_interval_days`./// They were the resurfacing machinery — a flag saying "this is only true for/// now", plus the widening ladder that asked the owner about it again. The owner/// retired the mechanism: an entry that is only true for a while SAYS SO IN ITS/// OWN SENTENCE ("valid until 24 Oct", "until X ships"), and an assistant that/// reads an expired one archives it. One place to look — the sentence — rather/// than a sentence plus a flag that can disagree with it.////// The `review_interval_days` CHECK goes with the column, and/// `idx_cotton_memories_due`, the partial index over `dated` and/// `next_review_at`, has nothing left to index.pubconst MEMORIES_TABLE: &str = r#"CREATE TABLE "cotton_memories" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, slug TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'active', machine TEXT, visibility TEXT NOT NULL DEFAULT 'private', origin_kind TEXT NOT NULL, origin_label TEXT, reviewed_at TEXT, source_external_id TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, source TEXT, superseded_by TEXT CHECK (superseded_by IS NULL OR status = 'archived'), _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK ((status = 'archived') = (archived_at IS NOT NULL)), CHECK (length(body) <= 4000), CHECK ((machine IS NULL) OR (length(trim(machine)) > 0)), CHECK (origin_kind IN ('user', 'agent')), CHECK ((origin_kind = 'agent') = (origin_label IS NOT NULL)), CHECK (length(slug) BETWEEN 1 AND 64 AND slug GLOB '[a-z0-9]*' AND NOT slug GLOB '*[^a-z0-9-]*'), CHECK (status IN ('active', 'archived')), CHECK ((length(trim(title)) > 0) AND (length(title) <= 280)), CHECK (visibility IN ('private', 'shared', 'public')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// One slug per workspace: the slug IS how everything cites an entry.pubconst MEMORIES_SLUG_INDEX: &str = r#"CREATE UNIQUE INDEX idx_cotton_memories_slug ON cotton_memories (workspace_id, slug)"#;/// An importer's idempotency key.pubconst MEMORIES_SOURCE_EXTERNAL_INDEX: &str = r#"CREATE UNIQUE INDEX idx_cotton_memories_source_external ON cotton_memories (workspace_id, source_external_id) WHERE source_external_id IS NOT NULL"#;/// What replaced an archived entry.pubconst MEMORIES_SUPERSEDED_BY_INDEX: &str = r#"CREATE INDEX idx_cotton_memories_superseded_by ON cotton_memories (superseded_by) WHERE superseded_by IS NOT NULL"#;/// The unreviewed band — live entries nobody has kept yet.pubconst MEMORIES_UNREVIEWED_INDEX: &str = r#"CREATE INDEX idx_cotton_memories_unreviewed ON cotton_memories (workspace_id, updated_at DESC) WHERE (status = 'active') AND (reviewed_at IS NULL)"#;// ---------------------------------------------------------------------------// Version 29 — THE CODE CREDENTIAL, IN THE PERSON'S OWN FILE// (Cotton note "Code hosting — why a repository lives in Cotton" § Hand-over).//// A `ctg_` used to be 32 random bytes whose SHA-256 sat in the MINTING Mac's// `registry.db`. Which Mac answers the household's relay name is RUNTIME and// moves on any restart, so on 22 Sep 2026 one hand-over took the whole code// surface down three times: every git remote and every `pnpm forge` call// answered `401 bad_credential`, every runner read "this runner is not// registered with this server", and git's credential store ERASED what it held// on that first refusal. Nothing was wrong with the credentials; they were rows// on a Mac that had stopped answering the name.//// The credential is now SIGNED off the workspace key every paired device// derives (`cotton_core::vault::code_tokens`), so no Mac stores one and every// Mac verifies one. What the file holds is the GRANT — this table, whose// `revoked_at` is the revocation every Mac reads.//// **NO HASH COLUMN AND NO SECRET COLUMN**, which is the whole point and is what// lets the row sync: `tests/no_bearer_in_the_file.rs` is the guard, and this// table needs no exemption from it.//// **THERE IS NO ROW FOR A `run` CREDENTIAL**, and that is a decision rather// than an omission. A job's token is minted per job, so a row each would put one// synced row per CI job into the person's own file for ever — thousands a month// on this repository alone, on a phone that has no screen for any of them. A// `run` token names its JOB instead, and its liveness IS the job's: the job// reaching `completed` is the revocation, exactly and without a second stamp// somebody has to remember to write.//// One plain create and its two indexes. Nothing rebuilt, nothing retired, no// `AddedColumn`, NO BACKFILL — a `ctg_` minted under the registry is not// carried, because each one dies once (exactly as a hand-over killed them all// on 22 Sep) and re-mints through the paths that already exist for that. And no// search index: a credential is listed on one panel, never searched./// One row per LIVE code credential the household has minted — `device`,/// `script` and `runner`. The token itself is signed and stored nowhere.////// `revoked_at` is the one column that decides anything: the mirror of a/// `cotton_revocations` fact, written only by `crate::revocation::revoke()` and/// never cleared — the `cotton_oauth_grants` rule, for the same reason: a/// revocation must not be undone by a Mac that had not heard about it.////// `last_used_at` is the one write here that is not a decision. It is stamped/// at most once a minute, because a `git fetch` is three requests and a/// `pnpm forge` command is a dozen.////// **THERE IS NO `repo_id` COLUMN**, and that follows from the row set: the one/// scope that names a repository is `run`, and a `run` has no row here. The/// claims still carry one, because the TOKEN has to say which repository it is/// for; nothing in the file does.////// `token_digest` (version 44) is the SHA-256 of the token minted for this row/// (`cotton_core::vault::code_tokens::digest`) — never the token, and nothing/// anybody can present. It is what admits a LIVE credential after the/// workspace key it was signed under has been rotated away. NULL on a row/// minted before version 44, and such a row's token stays refused after a/// rotation. Written once, at mint; the fold refuses a patch that changes it/// (`fold::no_grant_rewrite`).////// `minted_by` (version 44) is the device id of the Mac that MINTED the token/// — the serving Mac, which saw the secret when it handed it out. NULL on a/// row minted before version 44, or by a server with no device identity. It is/// what lets the sync route accept a grant only from the device it names or/// the Mac that minted it, and what lets a revocation reach every grant a/// revoked device could have planted or kept a copy of/// (`cotton_server::sync::credential_rows`, `code::credentials::revoke_all_for_device`)./// Written once, with its row, like the digest and the device.pubconst CODE_CREDENTIALS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_code_credentials ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL CHECK (length(trim(device_id)) > 0), name TEXT NOT NULL CHECK (length(trim(name)) > 0), scope TEXT NOT NULL CHECK (scope IN ('device', 'script', 'runner')), created_at TEXT NOT NULL, expires_at TEXT, revoked_at TEXT, last_used_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, token_digest TEXT, minted_by TEXT, read_only INTEGER NOT NULL DEFAULT 0, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// What the chokepoint reads on every request: one row, by the id the token/// names — and what the panel lists, newest first.pubconst CODE_CREDENTIALS_WORKSPACE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_code_credentials_workspace ON cotton_code_credentials (workspace_id, created_at DESC)"#;pubconst AUTHOR_INDEX_COTTON_CODE_CREDENTIALS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_code_credentials_author ON cotton_code_credentials (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 31 — THE PROJECT CONVERSATION// (Cotton note "The project conversation — one standing thread per project").//// A project's conversation is a `cotton_sessions` row, not a new object: the// state machine, the Mac placement, the helper's pty, the hooks and the reply// path all already belong to a session, and a second table holding the same// lifecycle is two lifecycles to keep equal. What the row needed was two// columns — what KIND of session it is, and which conversation opened it —// and one child table for the task list a thread mirrors onto itself.// ---------------------------------------------------------------------------/// `cotton_session_tasks` — a session's own task list, mirrored (version 31).////// One row per task the agent is tracking, in the agent's own order, so a card/// can say "4/6" and a tap can show the list. It is a MIRROR: the agent's task/// list is the truth while the session runs, and `log_session { tasks }`/// replaces this list whole rather than patching it, because a list is one/// value and a half-applied edit would draw a task twice.////// **The id is DERIVED from `(session, seq)`** — the table's own UNIQUE — for/// `cotton_prompts`' reason exactly: two servers can both hear one mirror/// (the hook through one, a retry through another), and a uuid apiece is two/// rows the index refuses to hold.////// `text` is capped at 500 by the file, which is far past any task a person/// would recognise as one; `state` is the three words a task list has. NO/// cross-column CHECK, so nothing here says "a `done` task has a `done_at`":/// a synced row arrives as a fragment (`tests/no_cross_column_checks.rs`).pubconst SESSION_TASKS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_session_tasks ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, session_id TEXT NOT NULL, seq INTEGER NOT NULL, text TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (session_id, seq), CHECK (seq >= 0), CHECK (length(text) <= 500), CHECK (state IN ('open', 'active', 'done')), FOREIGN KEY (session_id) REFERENCES cotton_sessions(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// One session's list, in its own order — the only way this table is read.pubconst SESSION_TASKS_SESSION_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_session_tasks_session ON cotton_session_tasks (session_id, seq)"#;pubconst AUTHOR_INDEX_COTTON_SESSION_TASKS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_session_tasks_author ON cotton_session_tasks (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// Version 32 — A NOTE CARRIES PICTURES (Cotton note "Notes — Markdown, and the pictures a note shows").//// A note's body is Markdown and a picture in it is a REFERENCE, never bytes:// the photo, video or document is already a record of its own with its own// media key, its own holdings and its own bin, and a note that copied one// would be a second owner of the same bytes. So the picture on a note is a// third row naming both sides — this table.//// **NOT `cotton_links`.** That table is the record-to-record GRAPH: a// symmetric, unordered edge with no place to put a position or a caption, and// its `from_kind`/`to_kind` vocabularies are CHECKs baked into the table, so// admitting a new pairing is a rebuild of a table that has children. An// attachment is not an edge between two records of equal standing — it is an// ORDERED CHILD of one note, the way `cotton_media_album_items` is an ordered// child of one album, and that is the table this one is shaped after.// ---------------------------------------------------------------------------/// `cotton_note_attachments` — a note's pictures, in the note's own order/// (version 32).////// One row per attached record. `record_kind` is `photo`, `video` or/// `document`, and `record_id` is that record's own id verbatim — a photo id/// already carries its `photo:` prefix, a document id is a uuid.////// **THERE IS NO FOREIGN KEY ON `record_id`**, and there cannot be: it names/// one of THREE tables, and SQLite has no polymorphic reference. What follows/// from that is the rule the readers are held to — **a removed picture leaves/// its row**. `remove_photo` deletes the photo and its faces and sightings and/// nothing else (an album item already dangles by design), so a reader LEFT/// JOINs and answers `missing: true`, the phone draws a removed tile and the/// shared page skips it. A cascade here would silently rewrite a note's body/// the moment somebody tidied their library.////// **NO CROSS-COLUMN CHECK**, and the tempting one is named so nobody adds it/// later: `substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'`/// is exactly what `cotton_media_album_items` carries, and it is one of the/// eighty-one already on the file rather than a pattern to copy. A synced row/// arrives as a FRAGMENT — one op per column stamp — so a fold that lands/// `record_kind` before `record_id` would trip a CHECK spanning the two and/// park an op for ever (`tests/no_cross_column_checks.rs`). The invariant goes/// where the write happens.////// **NO `UNIQUE (note_id, position)`.** A reorder arrives as fragments too,/// and two rows swapping places would collide in the instant between the first/// arriving and the second. `position` is advisory and readers order by/// `position, created_at, id`, which is total whatever the file holds.////// `caption` is an OVERRIDE: NULL means "use the record's own caption or/// title", which is what the picture already says about itself everywhere else/// in the file. There is no `archived_at` — a note's pictures are visible/// exactly when the note is, and taking one off is a replicated row DELETE.pubconst NOTE_ATTACHMENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_note_attachments ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, note_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, position INTEGER NOT NULL, caption TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (note_id, record_kind, record_id), CHECK (record_kind IN ('photo', 'video', 'document')), CHECK (length(record_id) > 0), CHECK (position >= 0), CHECK (caption IS NULL OR length(caption) <= 500), FOREIGN KEY (note_id) REFERENCES cotton_notes(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// One note's pictures in its own order — the only way this table is read.pubconst NOTE_ATTACHMENTS_NOTE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_note_attachments_note ON cotton_note_attachments (note_id, position)"#;pubconst AUTHOR_INDEX_COTTON_NOTE_ATTACHMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_note_attachments_author ON cotton_note_attachments (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// VERSION 35 — A DEVELOPER JOB: ONE SHELL COMMAND, QUEUED FOR ONE NAMED MAC.//// A Mac accepts no inbound connection for work. So "run this on that Mac" is// not a request anybody can send: it is a ROW that Mac's own client reads,// claims and runs, exactly as a coding session is// (`cotton-client/src/session_host/dev_jobs.rs`). That is why this is a table// and not a route.//// SYNCED, NOT SERVER-ONLY. The whole point is that the row reaches a Mac that// is not the one holding the server, so it is handed over like any other and// `SERVER_ONLY_TABLES` does not name it.//// THE OUTPUT IS A FILE. `log_path` names an append-only file on the Mac that// ran the job — the whole of stdout and stderr, never trimmed — and the row// carries `log_bytes`, `log_lines` and `output_tail`, the last 64 KiB. That is// `cotton_repo_jobs`' own shape (a log file, plus `log_lines` and a bounded// `summary`): ten thousand lines of `cargo test` is not something every device// should hold as rows, and the tail is what a caller actually reads.// ---------------------------------------------------------------------------/// `cotton_dev_jobs` — one shell command a developer tool queued for one Mac/// (version 35).////// `device_id` is the Mac's DEVICE KEY (`cotton_devices.device_id`), not that/// table's row id, because the key is what every client already knows itself by/// — `cotton_sessions.device_id` is the same column for the same reason, and/// the claim reads `WHERE device_id = ?` against the key the client holds.////// **NO FOREIGN KEY ON `device_id`.** A synced row arrives as a fragment and a/// job can reach a Mac before that Mac's own device row has folded there; a/// reference would reject the job rather than hold it. Naming a machine nobody/// admitted is refused where the write happens (`dev_run_on_mac`), which is/// where an invariant over two tables belongs.////// **NO CROSS-COLUMN CHECK**, and the tempting ones are named so nobody adds/// them later: `CHECK (state <> 'done' OR exit_code IS NOT NULL)` and `CHECK/// (state = 'queued' OR claimed_at IS NOT NULL)` are exactly what a fold would/// trip, because one op per column stamp means `state` can land before/// `exit_code` does and the op would park in `_parked` for ever/// (`tests/no_cross_column_checks.rs`). The state machine lives in the pass/// that writes it.////// `state` is `queued` → `running` → `done` | `failed`, plus `expired` for a/// job no Mac claimed inside ten minutes (the server's `dev-jobs` sweep)./// `failed` carries `failure`, one sentence: a timeout, a shell that would not/// start, or an app that restarted mid-job.pubconst DEV_JOBS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_dev_jobs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device_id TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT, timeout_seconds INTEGER NOT NULL DEFAULT 300, state TEXT NOT NULL DEFAULT 'queued', exit_code INTEGER, failure TEXT, log_path TEXT, log_bytes INTEGER NOT NULL DEFAULT 0, log_lines INTEGER NOT NULL DEFAULT 0, output_tail TEXT, created_at TEXT NOT NULL, claimed_at TEXT, finished_at TEXT, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(device_id) > 0), CHECK (length(trim(command)) > 0), CHECK (length(command) <= 4096), CHECK (cwd IS NULL OR length(trim(cwd)) > 0), CHECK (timeout_seconds > 0), CHECK (timeout_seconds <= 3600), CHECK (state IN ('queued', 'running', 'done', 'failed', 'expired')), CHECK (log_bytes >= 0), CHECK (log_lines >= 0), CHECK (output_tail IS NULL OR length(output_tail) <= 65536), CHECK (failure IS NULL OR length(failure) <= 2048), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// THE CLAIM READ, and the one that has to be cheap: the jobs queued for THIS/// Mac, oldest first, which is what every pass of the session host asks for.pubconst DEV_JOBS_QUEUE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_dev_jobs_queue ON cotton_dev_jobs (workspace_id, device_id, state, created_at)"#;pubconst AUTHOR_INDEX_COTTON_DEV_JOBS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_dev_jobs_author ON cotton_dev_jobs (substr(_hlc, 20), _hlc)"#;/// `cotton_thought_attachments` — a thought's pictures, in the thought's own/// order (version 36).////// `cotton_note_attachments` one table over, with two differences that are the/// whole of what a thought is:////// **THE OWNER IS A THOUGHT** (`cotton_inbox_items` — the kind was renamed/// `thought` at version 29 and the table name is wire protocol). A bug report/// from the phone is one thought with a screenshot on it, so the picture hangs/// off the capture the person made, not off whatever the router later files it/// into. The row cascades with its thought exactly as a note's does.////// **NO `origin_handle`.** A thought is not shareable and the registry says so/// in writing (`cotton-core/src/primitives.rs`); the column exists on exactly/// the tables whose rows can arrive from somebody else, and a test holds that/// set exact. A thought's picture never travels beyond the person's own/// devices, so there is nobody else it could have come from.////// Everything else is the note table's decisions, for the note table's reasons:/// no foreign key on `record_id` (three tables, no polymorphic reference — a/// removed picture leaves its row and the reader answers `missing`), no/// cross-column CHECK (a synced row arrives as fragments), no/// `UNIQUE (thought_id, position)` (a reorder is fragments too), `caption`/// as an override that NULL leaves to the record's own words.pubconst THOUGHT_ATTACHMENTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_thought_attachments ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thought_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, position INTEGER NOT NULL, caption TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (thought_id, record_kind, record_id), CHECK (record_kind IN ('photo', 'video', 'document')), CHECK (length(record_id) > 0), CHECK (position >= 0), CHECK (caption IS NULL OR length(caption) <= 500), FOREIGN KEY (thought_id) REFERENCES cotton_inbox_items(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// One thought's pictures in its own order — the only way this table is read.pubconst THOUGHT_ATTACHMENTS_THOUGHT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_thought_attachments_thought ON cotton_thought_attachments (thought_id, position)"#;pubconst AUTHOR_INDEX_COTTON_THOUGHT_ATTACHMENTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_thought_attachments_author ON cotton_thought_attachments (substr(_hlc, 20), _hlc)"#;/// `cotton_repo_merge_queue` — the merge queue of a Cotton-hosted repository/// (version 38): ONE ROW PER PULL REQUEST THAT ASKED TO LAND.////// A pull request is never merged on its own green. Green on its own head says/// the branch is right against the main it was planned on, and nothing about/// the branch beside the others landing the same hour — on 28 Sep 2026 nineteen/// pull requests that had each passed alone were landed by hand as one train,/// and three of its rounds were clashes between them, twenty minutes a round./// So the merge client QUEUES a green pull (a row here, `queued`), and the `ci`/// worker forms a TRAIN from the queue: the queued heads squashed one after/// another onto main's tip, checked ONCE as that exact tree, and — green —/// main moved to that tip. What was checked is what lands.////// **A TRAIN IS ITS MEMBERS.** There is no train table: the rows that ride/// together carry the same `train_number` (per repository, the number in the/// ref `refs/merge-queue/<n>` the checks run on), the same/// `train_base_sha` (main when the train formed) and `train_tip_sha` (the end/// of the chain), and `train_run_id` once the run is planned. `landed_sha` is/// THIS pull's own squash commit in the chain — the sha its history is at once/// main moves.////// `state`: `queued` → `checking` (on a train) → `landed` | `ejected`; a red/// train with more than one member DISSOLVES — its rows go back to `queued`/// with `failures + 1`, and the next train they ride is half the size/// (`cotton_core::rules::merge_queue::train_cap`), so a clash is bisected/// without a second lane of Macs. `reason` is the sentence an ejected row/// carries: the run and job that went red, or the conflict.////// NO CROSS-COLUMN CHECK (version 35's rule, for version 35's reason: a synced/// row arrives one column stamp at a time). No reference to the pull row: a/// queue row outlives a pull that was deleted on the host, and says so. Server/// only (`table_specs::SERVER_ONLY_TABLES`): a phone reads the queue through/// the pull's own `checks`, where the train writes a "Merge queue" context.pubconst MERGE_QUEUE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_repo_merge_queue ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, repo_id TEXT NOT NULL, pull_id TEXT NOT NULL, pull_number INTEGER NOT NULL, base_ref TEXT NOT NULL, head_sha TEXT, state TEXT NOT NULL DEFAULT 'queued', failures INTEGER NOT NULL DEFAULT 0, reason TEXT, train_number INTEGER, train_base_sha TEXT, train_tip_sha TEXT, train_run_id TEXT, landed_sha TEXT, enqueued_at TEXT NOT NULL, finished_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, train_squash_sha TEXT, CHECK (length(repo_id) > 0), CHECK (length(pull_id) > 0), CHECK (pull_number > 0), CHECK (length(base_ref) > 0), CHECK (state IN ('queued', 'checking', 'landed', 'ejected')), CHECK (failures >= 0), CHECK (reason IS NULL OR length(reason) <= 2048), CHECK (train_number IS NULL OR train_number > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// THE SWEEP'S READ: a repository's queued and checking rows, oldest first —/// what every pass of the `ci` worker asks.pubconst MERGE_QUEUE_REPO_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_merge_queue_repo ON cotton_repo_merge_queue (workspace_id, repo_id, state, enqueued_at)"#;pubconst AUTHOR_INDEX_COTTON_REPO_MERGE_QUEUE: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_repo_merge_queue_author ON cotton_repo_merge_queue (substr(_hlc, 20), _hlc)"#;/// `cotton_comments` — one thread per record, and the CHECK on `record_kind`/// is held equal to the registry's `commentable` kinds by/// `cotton_core::primitives_tests::cotton_comments_check_equals_the_registrys_commentable_kinds`,/// which reads THIS text. A kind that joins the list widens the CHECK in this/// text and bumps `SCHEMA_VERSION`; `scripts/gen-kind.ts` makes both edits from/// the kind's declaration. There is no rung: the fresh line has one.////// `kind` (version 98) is what the comment asks of the owner: a `question`/// waits in "Asked of you" (`cotton_core::rules::asked_of_you::awaits_owner`),/// a `note` — an assistant's claim, status or remark — never does. Every/// comment written before it, and every one written without it, is a note/// (architect, 11 Oct 2026).pubconst COMMENTS_TABLE: &str = r#"CREATE TABLE "cotton_comments" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, parent_id TEXT, body TEXT NOT NULL, author_kind TEXT NOT NULL, author_user_id TEXT, author_label TEXT, anchor TEXT, resolved_at TEXT, resolved_by_kind TEXT, resolved_by_label TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, kind TEXT NOT NULL DEFAULT 'note', trashed_at TEXT, CHECK (kind IN ('question', 'note')), CHECK ((author_kind = 'agent') = (author_label IS NOT NULL)), CHECK (author_kind IN ('user', 'agent')), CHECK (length(trim(body)) > 0), CHECK (record_kind IN ('todo', 'event', 'note', 'journal', 'person', 'location', 'page', 'meeting', 'document', 'news_edition', 'memory', 'call', 'decision')), CHECK (resolved_by_kind IN ('user', 'agent')), CHECK ((resolved_at IS NULL) = (resolved_by_kind IS NULL)), CHECK ((author_kind = 'user') = (author_user_id IS NOT NULL)), FOREIGN KEY (parent_id) REFERENCES cotton_comments(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst COMMENTS_OPEN_INDEX: &str = r#"CREATE INDEX idx_cotton_comments_open ON cotton_comments (workspace_id, created_at DESC) WHERE resolved_at IS NULL"#;pubconst COMMENTS_PARENT_INDEX: &str = r#"CREATE INDEX idx_cotton_comments_parent ON cotton_comments (parent_id) WHERE parent_id IS NOT NULL"#;pubconst COMMENTS_RECORD_INDEX: &str = r#"CREATE INDEX idx_cotton_comments_record ON cotton_comments (record_kind, record_id, created_at)"#;/// `cotton_decisions` — v42. A decision is what an agent decided while building/// and why, tied to the pull request that carried it; it is kept apart from/// memory because memory is the owner's own words and is briefed in full, while/// a decision is technical, can be made false by a later pull request, and is/// found by search instead of briefed.pubconst DECISIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_decisions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT NOT NULL, why TEXT, pull TEXT, decided_by TEXT, trashed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(trim(title)) > 0), CHECK (length(title) <= 280), CHECK (pull IS NULL OR length(trim(pull)) > 0), CHECK (decided_by IS NULL OR length(trim(decided_by)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_DECISIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_decisions_author ON cotton_decisions (substr(_hlc, 20), _hlc)"#;/// `fts_decisions` — the external-content index over `cotton_decisions`.pubconst FTS_DECISIONS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_decisions USING fts5( title, why, content = 'cotton_decisions', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_decisions` on insert.pubconst FTS_DECISIONS_AI: &str = r#"CREATE TRIGGER fts_decisions_ai AFTER INSERT ON cotton_decisions WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_decisions'), 0) BEGIN INSERT INTO fts_decisions (rowid, title, why) VALUES (new.rowid, new.title, new.why); END"#;/// `fts_decisions` on delete.pubconst FTS_DECISIONS_AD: &str = r#"CREATE TRIGGER fts_decisions_ad AFTER DELETE ON cotton_decisions WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_decisions'), 0) BEGIN INSERT INTO fts_decisions (fts_decisions, rowid, title, why) VALUES ('delete', old.rowid, old.title, old.why); END"#;/// `fts_decisions` on update.pubconst FTS_DECISIONS_AU: &str = r#"CREATE TRIGGER fts_decisions_au AFTER UPDATE OF title, why ON cotton_decisions FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_decisions'), 0) AND (new.title IS NOT old.title OR new.why IS NOT old.why) BEGIN INSERT INTO fts_decisions (fts_decisions, rowid, title, why) VALUES ('delete', old.rowid, old.title, old.why); INSERT INTO fts_decisions (rowid, title, why) VALUES (new.rowid, new.title, new.why); END"#;// ---------------------------------------------------------------------------// VERSION 46 — TABLE AND TOOL DEFINITIONS: A TABLE'S SHAPE AND FACES AS DATA.//// A table definition says what one table holds and how it is drawn — its// columns and their types, which column is the title, the date, the project and// the manual order, the slip, the tile, the page, and the paragraph an// assistant reads about it. A tool definition names the tables one tool works// with. Each row stores ONE definition as the shared-format JSON// (`cotton_core::definitions`), keyed by the definition's own id, so the app// draws a table from a row rather than from a screen compiled into it.//// SYNCED like any record, so a definition written on one device reaches every// other one and settles by the same per-column who-wins rule as every other// table: there is no second conflict rule for definitions.//// THE BUILT-INS ARE SEEDED, NOT MIGRATED. The rung creates empty tables and// writes no row; every launch upserts the shipped definitions through the// normal write path, and writes nothing when the stored one already matches// (`cotton_tools::definitions::seed_builtin_definitions`).//// `builtin_hash` identifies seeded content; `builtin_stamp` orders the builds// that seeded it. Only the server seeds; an older build never overwrites newer// seeded rows. These are row metadata, outside the shared-format JSON.// The retired `builtin_revision` column remains inert in the add-only store.//// `instructions_edited` is a separate column rather than a field of the JSON// because it is a fact about the ROW's history, not about the table: the seed// keeps a person's own instructions and replaces everything else, and it has// to tell those apart without guessing from the text.// ---------------------------------------------------------------------------/// `cotton_table_definitions` — one table's definition, as shared-format JSON/// (version 46). `id` IS the definition's id (`todo`, `lesson`): lowercase,/// never changing, and what every other definition's `link_to` names.pubconst TABLE_DEFINITIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_table_definitions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, definition TEXT NOT NULL, builtin INTEGER NOT NULL DEFAULT 0, instructions_edited INTEGER NOT NULL DEFAULT 0, builtin_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, builtin_hash TEXT, builtin_stamp INTEGER, CHECK (length(id) > 0), CHECK (length(definition) > 0), CHECK (builtin IN (0, 1)), CHECK (instructions_edited IN (0, 1)), CHECK (builtin_revision IS NULL OR builtin_revision >= 1), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_tool_definitions` — one tool's definition, as shared-format JSON/// (version 46), in the same shape as the table definitions beside it.pubconst TOOL_DEFINITIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_tool_definitions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, definition TEXT NOT NULL, builtin INTEGER NOT NULL DEFAULT 0, instructions_edited INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(id) > 0), CHECK (length(definition) > 0), CHECK (builtin IN (0, 1)), CHECK (instructions_edited IN (0, 1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_toolkits` — one starter kit a database can be made from (version/// 97, owner 11 Oct 2026: "the toolkits also should be in data"). Kept in the/// personal database, which is on the phone, so a database can still be made/// offline from any kit.////// `tools` is the kit's ordered list, each entry EITHER a built-in tool key/// (`"todos"`) OR `{"package": {tool, tables, samples, with_samples}}` — a/// tool package carried inline, as `cotton_core::toolkits::KitTool` reads it;/// a package's pictures are photo records in this same database, named by its/// tool's `picture`. `picture` is the kit's own card picture, a/// `ToolPicture` as JSON (an object name or `{"photo": "photo:<sha256>"}`)./// `shipped` marks a row still as the build seeded it (`cotton_tools::toolkits`),/// which the launch seed keeps current; a person's change makes it 0 and theirs,/// and a deleted one is never seeded again.pubconst TOOLKITS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_toolkits ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, name TEXT NOT NULL, description TEXT, picture TEXT, tools TEXT NOT NULL DEFAULT '[]', shipped INTEGER NOT NULL DEFAULT 0, position INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (length(id) > 0), CHECK (length(name) > 0), CHECK (json_type(tools) = 'array'), CHECK (picture IS NULL OR json_valid(picture)), CHECK (shipped IN (0, 1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// The kit chooser's order.pubconst TOOLKITS_POSITION_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_toolkits_position ON cotton_toolkits (workspace_id, position)"#;pubconst AUTHOR_INDEX_COTTON_TOOLKITS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_toolkits_author ON cotton_toolkits (substr(_hlc, 20), _hlc)"#;/// `cotton_board_definitions` — one screen's board (version 92, design note/// 26203e21 §4): the parts Home, the Tools screen, the database page or a/// tool's landing screen draws, as the JSON `cotton_core::definitions::board`/// reads. `id` IS the board's id (`home`). A built-in default is seeded at/// `builtin = 1`; a row a person writes at the same id (`builtin = 0`)/// overrides it, and removing that row restores the default.pubconst BOARD_DEFINITIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_board_definitions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, definition TEXT NOT NULL, builtin INTEGER NOT NULL DEFAULT 0, builtin_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, builtin_hash TEXT, builtin_stamp INTEGER, CHECK (length(id) > 0), CHECK (length(definition) > 0), CHECK (builtin IN (0, 1)), CHECK (builtin_revision IS NULL OR builtin_revision >= 1), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;/// `cotton_theme_definitions` — one theme (version 92, design note 26203e21/// §6): a skin over a face family, as the JSON/// `cotton_core::definitions::theme` reads. The built-in `paper` is seeded at/// `builtin = 1`; the database draws a row of its own (`builtin = 0`) when it/// has one, and `paper` otherwise.pubconst THEME_DEFINITIONS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_theme_definitions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, definition TEXT NOT NULL, builtin INTEGER NOT NULL DEFAULT 0, builtin_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, builtin_hash TEXT, builtin_stamp INTEGER, CHECK (length(id) > 0), CHECK (length(definition) > 0), CHECK (builtin IN (0, 1)), CHECK (builtin_revision IS NULL OR builtin_revision >= 1), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_BOARD_DEFINITIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_board_definitions_author ON cotton_board_definitions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_THEME_DEFINITIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_theme_definitions_author ON cotton_theme_definitions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_TABLE_DEFINITIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_table_definitions_author ON cotton_table_definitions (substr(_hlc, 20), _hlc)"#;pubconst AUTHOR_INDEX_COTTON_TOOL_DEFINITIONS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_tool_definitions_author ON cotton_tool_definitions (substr(_hlc, 20), _hlc)"#;// ---------------------------------------------------------------------------// VERSION 47 — RECORDS AND CHANGES: A TABLE A PERSON DEFINED, STORED// GENERICALLY, AND THE CHANGE EVERY WRITE LEAVES BEHIND.//// `cotton_records` holds every record of every table a person defined (a// `cotton_table_definitions` row with no engine): one row per record, keyed by// its own uuid, tagged with the definition's id in `table_id`, its values as// one JSON object keyed by column key in `data`. A new user table is a new// definition row and nothing else — no rung, no DDL.//// TWO VALUES LIVE OUTSIDE `data`, in columns of their own: the record's project// (the definition's `project` column, in `project_id`) and its manual order// (the definition's `order` column, in `position`). The generic verbs present// them inside the record's values; storing them apart means a drag-reorder or// a move to another project is its own column write and never rewrites the// rest of the record, and the list index below can filter on the project.//// SYNCED under the one who-wins rule every table settles by. Who-wins is PER// COLUMN, so two devices editing DIFFERENT fields of one record inside one// sync window resolve as one `data` write — the later one's whole object.// Accepted for a single-owner database; the per-field alternative would be a// second storage shape.//// A delete is SOFT: `deleted_at` is set, and cleared again by an undo. The row// stays, so an undo restores the record at its own id.//// `cotton_changes` is HISTORY (slice 6, schema 85): one row per act per// record, written by `mint` in the act that made the change (or, until the// generic verbs hand theirs to `mint`, by those verbs in their own act), with// the act's verb and actor, the stamp of the record's write (`write_hlc`), the// record's kind and the moved fields before and after. A FACT: insert-only,// taken out only by an erase; an undo is a `cotton_undos` fact. Synced, so// every device holds the same history and an undo can be issued from any.// `record_id` is NULL for a change spanning several records (a reorder).//// No CHECK on `verb`: a newer build's verb must fold on an older one rather// than be refused; the verbs are `cotton_core::records::Verb`.// ---------------------------------------------------------------------------/// `cotton_records` — one record of a table a person defined (version 47).pubconst RECORDS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_records ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, table_id TEXT NOT NULL, data TEXT NOT NULL, project_id TEXT, position REAL, byline TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(id) > 0), CHECK (length(table_id) > 0), CHECK (json_type(data) = 'object'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_RECORDS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_records_author ON cotton_records (substr(_hlc, 20), _hlc)"#;pubconst RECORDS_TABLE_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_records_table ON cotton_records (table_id, project_id, updated_at)"#;/// `cotton_changes` — one act's history row for one record (version 85).pubconst CHANGES_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_changes ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, table_id TEXT NOT NULL, record_id TEXT, verb TEXT NOT NULL, byline TEXT NOT NULL, before TEXT, after TEXT, created_at TEXT NOT NULL, kind TEXT, actor TEXT, write_hlc TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(id) > 0), CHECK (length(table_id) > 0), CHECK (length(verb) > 0), CHECK (before IS NULL OR json_valid(before)), CHECK (after IS NULL OR json_valid(after)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst AUTHOR_INDEX_COTTON_CHANGES: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_changes_author ON cotton_changes (substr(_hlc, 20), _hlc)"#;/// A record's changes, oldest first — what an undo reads.pubconst CHANGES_RECORD_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_changes_record ON cotton_changes (table_id, record_id, created_at)"#;/// `cotton_posts` — v86. A post is a picture or clip the owner put on a social/// site, or one he saved there, kept after the site forgets it; it is not a/// story (a story expires in a day) and not a photo (a photo is his own file, a/// post is the site's item with its caption and link).pubconst POSTS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_posts ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, source TEXT NOT NULL, account TEXT NOT NULL, external_id TEXT NOT NULL, saved INTEGER NOT NULL DEFAULT 0, author_handle TEXT, author_name TEXT, person_id TEXT, caption TEXT, media TEXT NOT NULL DEFAULT '[]', posted_at TEXT, saved_at TEXT, permalink TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (saved IN (0, 1)), CHECK (trim(external_id) <> ''), CHECK (json_valid(media) AND json_type(media) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#;pubconst POSTS_INDEX_1: &str = r#"CREATE UNIQUE INDEX IF NOT EXISTS uq_cotton_posts_external ON cotton_posts (workspace_id, source, account, external_id)"#;pubconst POSTS_INDEX_2: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_posts_posted ON cotton_posts (workspace_id, saved, posted_at)"#;pubconst AUTHOR_INDEX_COTTON_POSTS: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_posts_author ON cotton_posts (substr(_hlc, 20), _hlc)"#;/// `fts_posts` — the external-content index over `cotton_posts`.pubconst FTS_POSTS_TABLE: &str = r#"CREATE VIRTUAL TABLE fts_posts USING fts5( caption, author_name, author_handle, content = 'cotton_posts', content_rowid = 'rowid', tokenize = 'unicode61 remove_diacritics 2' )"#;/// `fts_posts` on insert.pubconst FTS_POSTS_AI: &str = r#"CREATE TRIGGER fts_posts_ai AFTER INSERT ON cotton_posts WHEN new.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_posts'), 0) BEGIN INSERT INTO fts_posts (rowid, caption, author_name, author_handle) VALUES (new.rowid, new.caption, new.author_name, new.author_handle); END"#;/// `fts_posts` on delete.pubconst FTS_POSTS_AD: &str = r#"CREATE TRIGGER fts_posts_ad AFTER DELETE ON cotton_posts WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_posts'), 0) BEGIN INSERT INTO fts_posts (fts_posts, rowid, caption, author_name, author_handle) VALUES ('delete', old.rowid, old.caption, old.author_name, old.author_handle); END"#;/// `fts_posts` on update.pubconst FTS_POSTS_AU: &str = r#"CREATE TRIGGER fts_posts_au AFTER UPDATE OF caption, author_name, author_handle ON cotton_posts FOR EACH ROW WHEN old.rowid >= coalesce((SELECT floor FROM _fts_fill WHERE fts = 'fts_posts'), 0) AND (new.caption IS NOT old.caption OR new.author_name IS NOT old.author_name OR new.author_handle IS NOT old.author_handle) BEGIN INSERT INTO fts_posts (fts_posts, rowid, caption, author_name, author_handle) VALUES ('delete', old.rowid, old.caption, old.author_name, old.author_handle); INSERT INTO fts_posts (rowid, caption, author_name, author_handle) VALUES (new.rowid, new.caption, new.author_name, new.author_handle); END"#;// gen-kind: ddl-consts//// `scripts/gen-kind.ts` writes a new kind's table, indexes, search index and// history triggers as named constants ABOVE this line, adds the same constants// to `SCHEMA_DDL` below by phase, and raises `SCHEMA_VERSION` by one. It writes// no rung and no migration: the fresh line has one rung, and it issues this list./// Every statement a fresh file is built from, in issue order.////// SQLite's own implicit objects are absent and must stay absent: the/// `sqlite_autoindex_*` indexes have no DDL to re-issue, `sqlite_sequence` is/// created by the first AUTOINCREMENT table, and the FTS5 shadow tables are/// created by `CREATE VIRTUAL TABLE`./// Personal interaction history, receipt-bearing and kept on this device.pubconst USAGE_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_usage ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, device TEXT NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('view_opened', 'record_opened', 'act_fired', 'search')), tool TEXT NOT NULL, view TEXT NOT NULL, record TEXT, at TEXT NOT NULL, record_byline TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE)"#;pubconst USAGE_AUTHOR_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_usage_author ON cotton_usage (substr(_hlc, 20), _hlc)"#;pubconst USAGE_AT_INDEX: &str = r#"CREATE INDEX IF NOT EXISTS idx_cotton_usage_workspace_at ON cotton_usage (workspace_id, at)"#;/// Durable work belongs to the subject's database; bytes are resolved by the drainer.pubconst AI_JOBS: &str = r#"CREATE TABLE cotton_ai_jobs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL, level INTEGER NOT NULL CHECK (level IN (2,3)), subject_table TEXT NOT NULL, subject_id TEXT NOT NULL, input TEXT NOT NULL CHECK (json_valid(input)), state TEXT NOT NULL DEFAULT 'waiting' CHECK (state IN ('waiting','taken','done','failed','refused')), taken_by TEXT, taken_at TEXT, done_at TEXT, outcome TEXT CHECK (outcome IS NULL OR json_valid(outcome)), attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), reason TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT)"#;pubconst AI_CALLS: &str = r#"CREATE TABLE cotton_ai_calls ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, legacy_id INTEGER, created_at TEXT NOT NULL, function_name TEXT NOT NULL, provider TEXT NOT NULL, model TEXT, status TEXT NOT NULL, error_message TEXT, input_tokens INTEGER, output_tokens INTEGER, cache_read_input_tokens INTEGER, cache_creation_input_tokens INTEGER, duration_seconds REAL, latency_ms INTEGER NOT NULL, cost_usd REAL, key_source TEXT NOT NULL DEFAULT 'platform', is_preview INTEGER NOT NULL DEFAULT 0, metadata TEXT, updated_at TEXT NOT NULL, device_id TEXT, cost_amount REAL, currency TEXT NOT NULL DEFAULT 'USD', mode TEXT NOT NULL DEFAULT 'live', _hlc TEXT NOT NULL DEFAULT '', _born TEXT, local_day TEXT, at TEXT, job_id TEXT, drained_by TEXT)"#;pubconst AI_BUDGETS: &str = r#"CREATE TABLE cotton_ai_budgets ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, name TEXT NOT NULL DEFAULT 'AI budget', hourly_cap REAL NOT NULL DEFAULT 1 CHECK (hourly_cap >= 0), daily_cap REAL NOT NULL DEFAULT 5 CHECK (daily_cap >= 0), currency TEXT NOT NULL DEFAULT 'USD', usd_rate REAL NOT NULL DEFAULT 1 CHECK (usd_rate > 0), paused_until TEXT, pause_reason TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT)"#;pubconst AI_BATCHES: &str = r#"CREATE TABLE _ai_batches (request_key TEXT PRIMARY KEY, batch_id TEXT NOT NULL, next_poll TEXT NOT NULL, created_at TEXT NOT NULL, result TEXT, metered INTEGER NOT NULL DEFAULT 0, reservation_usd REAL NOT NULL DEFAULT 0, purpose TEXT, context TEXT, applied INTEGER NOT NULL DEFAULT 0, failure TEXT)"#;/// Empty durable arrival events and immutable owner approval proposals.pubconst ARRIVALS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_arrivals ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('mail','chat','call','photo','thought')), record_table TEXT NOT NULL, record_id TEXT NOT NULL, context TEXT NOT NULL CHECK(json_valid(context) AND json_type(context)='object'), seen_by TEXT, seen_at TEXT, burst TEXT, outcome TEXT CHECK(outcome IN ('acted','proposed','asked','left')), reason TEXT, retrieval TEXT CHECK(retrieval IS NULL OR (json_valid(retrieval) AND json_type(retrieval)='array')), changes TEXT CHECK(changes IS NULL OR (json_valid(changes) AND json_type(changes)='array')), ask TEXT, decided_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY(workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE)"#;pubconst FILING_PROPOSALS_TABLE: &str = r#"CREATE TABLE IF NOT EXISTS cotton_filing_proposals ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, owner TEXT NOT NULL, session TEXT NOT NULL, source TEXT NOT NULL, destination TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('move','capture')), candidates TEXT NOT NULL CHECK(json_valid(candidates) AND json_type(candidates)='array'), arrivals TEXT NOT NULL CHECK(json_valid(arrivals) AND json_type(arrivals)='array'), revisions TEXT NOT NULL CHECK(json_valid(revisions) AND json_type(revisions)='object'), payload TEXT NOT NULL CHECK(json_valid(payload) AND json_type(payload)='object'), reason TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open','approved','declined','stale')), decided_at TEXT, answer TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY(workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE)"#;pubstatic SCHEMA_DDL: &[&str] = &[ ARRIVALS_TABLE, FILING_PROPOSALS_TABLE,r#"CREATE UNIQUE INDEX IF NOT EXISTS idx_cotton_arrivals_record ON cotton_arrivals(workspace_id,record_table,record_id)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_arrivals_pending ON cotton_arrivals(workspace_id,decided_at,seen_by,created_at)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_arrivals_author ON cotton_arrivals(substr(_hlc,20),_hlc)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_filing_proposals_open ON cotton_filing_proposals(workspace_id,status,created_at)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_filing_proposals_author ON cotton_filing_proposals(substr(_hlc,20),_hlc)"#, AI_JOBS,r#"CREATE INDEX idx_cotton_ai_jobs_waiting ON cotton_ai_jobs(workspace_id,state,level,created_at,id)"#,r#"CREATE INDEX idx_cotton_ai_jobs_subject ON cotton_ai_jobs(workspace_id,subject_table,subject_id,state)"#,r#"CREATE INDEX idx_cotton_ai_jobs_author ON cotton_ai_jobs(substr(_hlc,20),_hlc)"#, AI_CALLS, AI_BUDGETS, AI_BATCHES,r#"CREATE INDEX IF NOT EXISTS idx_cotton_ai_calls_author ON cotton_ai_calls (substr(_hlc, 20), _hlc)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_ai_budgets_author ON cotton_ai_budgets (substr(_hlc, 20), _hlc)"#,r#"CREATE INDEX idx_cotton_ai_calls_created_at ON cotton_ai_calls (workspace_id, created_at)"#,r#"CREATE INDEX idx_cotton_ai_calls_workspace ON cotton_ai_calls (workspace_id)"#,r#"CREATE INDEX idx_cotton_ai_budgets_workspace ON cotton_ai_budgets (workspace_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_ai_budgets_workspace ON cotton_ai_budgets (workspace_id)"#, USAGE_TABLE, USAGE_AUTHOR_INDEX, USAGE_AT_INDEX,// Version 55: `heard_serving_epoch` — the newest serving epoch an answer// has named to this replica, whether or not that epoch's fact has arrived// yet. What a hand-over is owed against (`owes_hand_over`), and the floor// below which an answer is an old Mac's.r#"CREATE TABLE _meta ( only_one INTEGER PRIMARY KEY CHECK (only_one = 1), workspace_id TEXT NOT NULL, owner_id TEXT NOT NULL, schema_version INTEGER NOT NULL, last_server_seq INTEGER NOT NULL DEFAULT 0, device_id TEXT NOT NULL, last_hlc TEXT, author_id TEXT, rotation_check_due TEXT, handed_over_epoch INTEGER, heard_serving_epoch INTEGER )"#,r#"CREATE TABLE _outbox ( op_id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('create', 'change', 'retract')), author TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL, hlc TEXT NOT NULL, schema_version INTEGER NOT NULL, queued_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, bytes BLOB NOT NULL, sig BLOB, mint_cont INTEGER, mint_boot TEXT )"#,// Version 54: `held`, `mint_cont` and `mint_boot`, as on `_writes` — a// delete made before this device has judge time is held like any other// write, and the release pass dates it by when it was made (slice 1).r#"CREATE TABLE _tombstones ( tbl TEXT NOT NULL, row_id TEXT NOT NULL, hlc TEXT NOT NULL, op_id TEXT NOT NULL, author TEXT NOT NULL, actor TEXT NOT NULL, bytes BLOB NOT NULL, sig BLOB, held INTEGER NOT NULL DEFAULT 0, mint_cont INTEGER, mint_boot TEXT, PRIMARY KEY (tbl, row_id) )"#,r#"CREATE TABLE _media ( key TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, sha256 TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, local_path TEXT, state TEXT NOT NULL CHECK (state IN ('pending','synced','failed','delete_pending')), after TEXT, after_row_id TEXT, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, next_attempt_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, tier TEXT, pinned INTEGER NOT NULL DEFAULT 0, last_viewed_at TEXT, captured_here INTEGER NOT NULL DEFAULT 0, fetched_by_rule INTEGER NOT NULL DEFAULT 0 CHECK (fetched_by_rule IN (0,1)) , last_code TEXT, network TEXT NOT NULL DEFAULT 'any', asked_by TEXT, source TEXT)"#, CURSORS_TABLE, FIELD_SETS_TABLE, TRIM_TABLE, WRITES_TABLE, WRITES_OWNERS_TABLE, PARKED_TABLE, GONE_TABLE, MEDIA_KEY_NAMES_TABLE, MEDIA_UNLINKS_TABLE, COMPUTED_TABLE, ON_DEMAND_TABLE, KEEP_FETCH_TABLE, FTS_FILL_TABLE, FTS_PURGE_TABLE, MAIL_CUTS_TABLE, MAIL_CUTS_KEY_INDEX, MAIL_LANDED_TABLE, MAIL_LANDED_KEY_INDEX, MAIL_LANDED_DOMAIN_INDEX, MAIL_LANDED_AT_INDEX, MAIL_OWN_TABLE,r#"CREATE TABLE cotton_workspaces ( id TEXT PRIMARY KEY, name TEXT NOT NULL, owner_user_id TEXT NOT NULL, created_at TEXT NOT NULL, city_name TEXT, city_lat REAL, city_lon REAL, msg_import_self_names TEXT NOT NULL DEFAULT '{}', _hlc TEXT NOT NULL DEFAULT '', _born TEXT, relay_name TEXT, session_permission_default TEXT NOT NULL DEFAULT 'bypass' CHECK (session_permission_default IN ('bypass', 'ask')), kind TEXT CHECK (kind IS NULL OR kind IN ('personal', 'shared')), namespace TEXT CHECK (namespace IS NULL OR length(namespace) > 0), owner_person_id TEXT, relay_domain TEXT, relay_tunnel_host TEXT, front_door TEXT, front_door_address TEXT, relay_roster TEXT, CHECK (((city_name IS NOT NULL) + (city_lat IS NOT NULL) + (city_lon IS NOT NULL)) IN (0, 3)) )"#,r#"CREATE TABLE cotton_ai_access ( workspace_id TEXT PRIMARY KEY, owner_user_id TEXT NOT NULL, trial_started_at TEXT, subscription_active INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_alarms ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, label TEXT NOT NULL DEFAULT '', hour INTEGER NOT NULL, minute INTEGER NOT NULL, repeat_days TEXT NOT NULL DEFAULT '[]', enabled INTEGER NOT NULL DEFAULT 1, sound INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK ((hour >= 0) AND (hour <= 23)), CHECK ((minute >= 0) AND (minute <= 59)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_collections ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL, name TEXT NOT NULL, is_default INTEGER NOT NULL DEFAULT 0, sort_key TEXT, created_at TEXT NOT NULL, archived_at TEXT, color TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (kind = 'calendar'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_mcp_tokens ( id TEXT PRIMARY KEY, owner_user_id TEXT NOT NULL, workspace_id TEXT NOT NULL, name TEXT NOT NULL, token_hash TEXT NOT NULL, scopes TEXT NOT NULL, expires_at TEXT, revoked_at TEXT, created_at TEXT NOT NULL, last_used_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, minted_by_device TEXT CHECK (minted_by_device IS NULL OR length(minted_by_device) > 0), UNIQUE (token_hash), CHECK (length(trim(name)) > 0), CHECK (length(token_hash) = 64 AND NOT token_hash GLOB '*[^0-9a-f]*'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_document_pages ( id TEXT PRIMARY KEY, document_id TEXT NOT NULL, workspace_id TEXT NOT NULL, page INTEGER NOT NULL, text TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (document_id, page), CHECK (page >= 1), FOREIGN KEY (document_id) REFERENCES cotton_documents(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_events ( id TEXT PRIMARY KEY, collection_id TEXT, title TEXT NOT NULL, notes TEXT, starts_at TEXT NOT NULL, ends_at TEXT, all_day INTEGER NOT NULL DEFAULT 0, rrule TEXT, location TEXT, source_inbox_id TEXT, gcal_id TEXT, gcal_etag TEXT, sync_state TEXT, organizer_is_self INTEGER NOT NULL DEFAULT 1, my_response TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', series_id TEXT, original_starts_at TEXT, exdates TEXT CHECK (exdates IS NULL OR json_type(exdates) = 'array'), trashed_at TEXT, erase_requested_at TEXT, _born TEXT, ical_uid TEXT, account TEXT, on_google INTEGER NOT NULL DEFAULT 0, event_place TEXT, country TEXT, timezone TEXT, CHECK (on_google IN (0, 1)), CHECK (my_response IN ('needs_action', 'accepted', 'declined', 'tentative')), CHECK (sync_state IN ('synced', 'pending', 'conflict')) )"#,r#"CREATE TABLE cotton_event_attendees ( id TEXT PRIMARY KEY, event_id TEXT NOT NULL, email TEXT, phone TEXT, display_name TEXT, response TEXT NOT NULL DEFAULT 'needs_action', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (response IN ('needs_action', 'accepted', 'declined', 'tentative')), FOREIGN KEY (event_id) REFERENCES cotton_events(id) )"#,r#"CREATE TABLE cotton_goals ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT NOT NULL, why TEXT, target_date TEXT, status TEXT NOT NULL DEFAULT 'active', achieved_at TEXT, sort_order REAL NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK ((status = 'achieved') = (achieved_at IS NOT NULL)), CHECK (status IN ('active', 'paused', 'achieved', 'dropped')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_google_accounts ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, google_email TEXT NOT NULL, refresh_token_enc TEXT, sync_token TEXT, channel_id TEXT, channel_resource_id TEXT, channel_expires_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, google_email), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, HOME_ARRANGEMENT_TABLE,r#"CREATE TABLE cotton_locations ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, name TEXT NOT NULL, address TEXT, lat REAL, lng REAL, note TEXT, source_inbox_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, place TEXT, place_id TEXT, country TEXT, timezone TEXT, near TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_mcp_audit ( id TEXT PRIMARY KEY, token_id TEXT NOT NULL, workspace_id TEXT NOT NULL, tool TEXT NOT NULL, args_summary TEXT, ok INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_meetings ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT, status TEXT NOT NULL DEFAULT 'uploading', source TEXT NOT NULL, started_at TEXT NOT NULL, ended_at TEXT, duration_seconds INTEGER, language TEXT, event_id TEXT, speakers TEXT NOT NULL DEFAULT '[]', summary_md TEXT, decisions TEXT NOT NULL DEFAULT '[]', vendor TEXT, vendor_job_id TEXT, poll_attempts INTEGER NOT NULL DEFAULT 0, status_changed_at TEXT NOT NULL, audio_deleted_at TEXT, failed_stage TEXT, error_code TEXT, segments TEXT NOT NULL DEFAULT '[]', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, event_database TEXT CHECK (event_database IS NULL OR length(event_database) > 0), CHECK ((duration_seconds IS NULL) OR (duration_seconds >= 0)), CHECK ((status = 'failed') = (failed_stage IS NOT NULL)), CHECK (failed_stage IS NULL OR failed_stage IN ('submit', 'transcribe', 'summarize')), CHECK (poll_attempts >= 0), CHECK (source IN ('recorded', 'imported')), CHECK (status IN ('recording', 'uploading', 'queued', 'transcribing', 'summarizing', 'ready', 'failed')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_meeting_utterances ( id TEXT PRIMARY KEY, meeting_id TEXT NOT NULL, seq INTEGER NOT NULL, speaker_label TEXT NOT NULL, t0_ms INTEGER NOT NULL, t1_ms INTEGER NOT NULL, text TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (meeting_id, seq), CHECK (seq >= 0), CHECK (t1_ms >= t0_ms), CHECK (t0_ms >= 0), CHECK (t1_ms >= 0), FOREIGN KEY (meeting_id) REFERENCES cotton_meetings(id) )"#,r#"CREATE TABLE cotton_memory_projects ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, slug TEXT NOT NULL, name TEXT NOT NULL, repos TEXT NOT NULL DEFAULT '[]', brand TEXT CHECK (brand IS NULL OR json_type(brand) = 'object'), description TEXT, summary_updated_at TEXT, summary_by TEXT, status TEXT NOT NULL DEFAULT 'active', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, section_order TEXT CHECK (section_order IS NULL OR json_type(section_order) = 'array'), trashed_at TEXT, UNIQUE (workspace_id, slug), CHECK (length(trim(name)) > 0), CHECK (json_type(repos) = 'array'), CHECK (length(slug) BETWEEN 1 AND 64 AND slug GLOB '[a-z0-9]*' AND NOT slug GLOB '*[^a-z0-9-]*'), CHECK (status IN ('active', 'archived')), CHECK ((summary_by IS NULL) OR (length(trim(summary_by)) > 0)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_money_statements ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, document_id TEXT NOT NULL, account_id TEXT, kind TEXT NOT NULL, period_start TEXT, period_end TEXT, opening_balance_minor INTEGER, closing_balance_minor INTEGER, currency TEXT NOT NULL, read_status TEXT NOT NULL DEFAULT 'pending', read_error TEXT, read_by TEXT, read_at TEXT, line_count INTEGER NOT NULL DEFAULT 0, sum_in_minor INTEGER NOT NULL DEFAULT 0, sum_out_minor INTEGER NOT NULL DEFAULT 0, balance_check TEXT NOT NULL DEFAULT 'unknown', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (document_id), CHECK (balance_check IN ('ok', 'mismatch', 'unknown')), CHECK (kind IN ('bank', 'credit_card')), CHECK (line_count >= 0), CHECK ((period_start IS NULL) OR (period_end IS NULL) OR (period_end >= period_start)), CHECK (read_status IN ('pending', 'read', 'mismatch', 'failed')), FOREIGN KEY (document_id) REFERENCES cotton_documents(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_money_statement_lines ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, statement_id TEXT NOT NULL, page INTEGER NOT NULL, line_no INTEGER NOT NULL, posted_on TEXT NOT NULL, text TEXT NOT NULL, amount_minor INTEGER NOT NULL, direction TEXT NOT NULL, balance_after_minor INTEGER, reference TEXT, fingerprint TEXT NOT NULL, ignored_reason TEXT, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (statement_id, line_no), CHECK (amount_minor > 0), CHECK (direction IN ('in', 'out')), CHECK (length(trim(text)) > 0), CHECK (line_no >= 1), CHECK (page >= 1), FOREIGN KEY (statement_id) REFERENCES cotton_money_statements(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_money_evidence ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, transaction_id TEXT NOT NULL, kind TEXT NOT NULL, ref_id TEXT, excerpt TEXT NOT NULL, source_label TEXT, attached_by TEXT NOT NULL, attached_by_label TEXT, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (attached_by IN ('import', 'assistant', 'owner')), CHECK (kind IN ('statement_line', 'document', 'message', 'email', 'external')), CHECK ((kind = 'external') OR (ref_id IS NOT NULL)), FOREIGN KEY (transaction_id) REFERENCES cotton_money_transactions(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_msg_owner_settings ( workspace_id TEXT PRIMARY KEY, handle TEXT NOT NULL, display_name TEXT NOT NULL, avatar_url TEXT, availability_copy TEXT, allow_new_contacts INTEGER NOT NULL DEFAULT 1, app_download_url TEXT, read_receipts INTEGER NOT NULL DEFAULT 1, discoverable INTEGER NOT NULL DEFAULT 1, last_seen_visible INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', share_requests TEXT NOT NULL DEFAULT 'contacts_direct' CHECK (share_requests IN ('contacts_direct','ask_always')), _born TEXT, CHECK (handle NOT IN ('inbox', 'api', 'assets', 'admin', 'settings', 'download', 'privacy', 'terms', 'about', 'app', 'm')), CHECK (length(handle) BETWEEN 3 AND 30 AND NOT handle GLOB '*[^a-z0-9-]*'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_msg_reactions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thread_id TEXT NOT NULL, message_id TEXT NOT NULL, actor TEXT NOT NULL, emoji TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (message_id, actor), CHECK (trim(actor) <> ''), CHECK (trim(emoji) <> '' AND length(emoji) <= 8), FOREIGN KEY (message_id) REFERENCES cotton_msg_messages(id), FOREIGN KEY (thread_id) REFERENCES cotton_msg_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_stories ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, source TEXT NOT NULL CHECK (source IN ('whatsapp', 'instagram', 'facebook')), account TEXT NOT NULL, external_id TEXT NOT NULL, person_id TEXT, sender TEXT, sender_label TEXT, kind TEXT NOT NULL, caption TEXT, media_key TEXT, media_content_type TEXT, media_dropped_at TEXT, posted_at TEXT NOT NULL, expires_at TEXT NOT NULL, seen_at TEXT, kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)), created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, source, external_id), CHECK (trim(external_id) <> ''), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_news_editions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued', trigger_kind TEXT NOT NULL, edition_label TEXT, covered_from TEXT NOT NULL, covered_to TEXT, story_count INTEGER, read_minutes INTEGER, quiet TEXT NOT NULL DEFAULT '[]', notes TEXT NOT NULL DEFAULT '[]', model TEXT, opened_at TEXT, status_changed_at TEXT NOT NULL, failed_stage TEXT, error_code TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK ((status = 'failed') = (failed_stage IS NOT NULL)), CHECK (failed_stage IS NULL OR failed_stage IN ('harvest', 'write')), CHECK ((read_minutes IS NULL) OR (read_minutes >= 0)), CHECK (status IN ('queued', 'harvesting', 'writing', 'ready', 'failed')), CHECK ((story_count IS NULL) OR (story_count >= 0)), CHECK (trigger_kind IN ('scheduled', 'manual', 'stale_open')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_news_topics ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, name TEXT NOT NULL, brief TEXT NOT NULL DEFAULT '', exclusions TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL, source_url TEXT, active INTEGER NOT NULL DEFAULT 1, paused_reason TEXT, unopened_streak INTEGER NOT NULL DEFAULT 0, last_new_at TEXT, sort_order REAL NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (kind IN ('search', 'source')), CHECK (length(trim(name)) > 0), CHECK (paused_reason IS NULL OR paused_reason IN ('user', 'auto')), CHECK ((source_url IS NULL) OR (kind = 'source')), CHECK (unopened_streak >= 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_news_stories ( id TEXT PRIMARY KEY, edition_id TEXT NOT NULL, topic_id TEXT, rank INTEGER NOT NULL, headline TEXT NOT NULL, lede TEXT NOT NULL, bullets TEXT NOT NULL DEFAULT '[]', sources TEXT NOT NULL DEFAULT '[]', why_care TEXT, read_minutes INTEGER, opened_at TEXT, feedback TEXT, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (feedback IS NULL OR feedback IN ('less', 'more')), CHECK (rank >= 0), CHECK ((read_minutes IS NULL) OR (read_minutes >= 0)), FOREIGN KEY (edition_id) REFERENCES cotton_news_editions(id) )"#,r#"CREATE TABLE cotton_news_seen ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, topic_id TEXT NOT NULL, "key" TEXT NOT NULL, title_hash TEXT, url TEXT, source TEXT NOT NULL, first_seen_at TEXT NOT NULL, story_id TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, "key"), CHECK (source IN ('google_news', 'hn', 'brave', 'rss')), FOREIGN KEY (topic_id) REFERENCES cotton_news_topics(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_news_settings ( workspace_id TEXT PRIMARY KEY, edition_times TEXT NOT NULL DEFAULT '["07:00", "19:00"]', timezone TEXT NOT NULL, stale_after_minutes INTEGER NOT NULL DEFAULT 360, stale_refresh INTEGER NOT NULL DEFAULT 1, notify INTEGER NOT NULL DEFAULT 1, next_edition_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (json_type(edition_times) = 'array'), CHECK (stale_after_minutes > 0), CHECK (length(trim(timezone)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_notes ( id TEXT PRIMARY KEY, kind TEXT NOT NULL DEFAULT 'note', title TEXT, body TEXT NOT NULL DEFAULT '', journal_date TEXT, project_id TEXT, published_at TEXT, public_slug TEXT, source_inbox_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT, trashed_at TEXT, author_kind TEXT NOT NULL DEFAULT 'user', author_label TEXT, managed_by TEXT, external_id TEXT, source_hash TEXT, workspace_id TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)), CHECK (author_kind IN ('user', 'agent')), CHECK ((author_kind = 'agent') = (author_label IS NOT NULL)), CHECK (kind IN ('note', 'journal')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_pages ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, url TEXT NOT NULL, host TEXT NOT NULL, title TEXT, read_at TEXT, source_inbox_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT, text_state TEXT CHECK (text_state IS NULL OR text_state IN ('kept', 'unreachable', 'unreadable')), state TEXT NOT NULL DEFAULT 'unread' CHECK (state IN ('unread', 'reading', 'read')), _hlc TEXT NOT NULL DEFAULT '', _born TEXT, text TEXT, trashed_at TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_person_notes ( id TEXT PRIMARY KEY, person_id TEXT NOT NULL, body TEXT NOT NULL, noted_at TEXT NOT NULL, created_at TEXT NOT NULL, source_inbox_id TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, FOREIGN KEY (person_id) REFERENCES cotton_people(id) )"#,r#"CREATE TABLE cotton_todo_recurrences ( id TEXT PRIMARY KEY, title TEXT NOT NULL, notes TEXT, priority INTEGER NOT NULL DEFAULT 0, rrule TEXT NOT NULL, dtstart TEXT NOT NULL, paused INTEGER NOT NULL DEFAULT 0, materialized_until TEXT, source_inbox_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, workspace_id TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_todos ( id TEXT PRIMARY KEY, title TEXT NOT NULL, notes TEXT, label TEXT, status TEXT NOT NULL DEFAULT 'open', due_at TEXT, snoozed_until TEXT, priority INTEGER NOT NULL DEFAULT 0, completed_at TEXT, source_inbox_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, recurrence_id TEXT, occurrence_at TEXT, workspace_id TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, UNIQUE (recurrence_id, occurrence_at), CHECK (status IN ('open', 'done', 'dropped', 'missed')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_voice_vocabulary ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, term TEXT NOT NULL, source TEXT NOT NULL, use_count INTEGER NOT NULL DEFAULT 0, last_used_at TEXT, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (source IN ('manual', 'auto')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_dictations ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, text TEXT NOT NULL, raw_text TEXT, source TEXT NOT NULL, host_app TEXT, words INTEGER NOT NULL DEFAULT 0, duration_ms INTEGER, spoken_at TEXT NOT NULL, external_id TEXT, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (source IN ('take', 'typed', 'wispr')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, SESSIONS_TABLE, PROMPTS_TABLE,r#"CREATE TABLE cotton_screenplays ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT NOT NULL, logline TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (length(trim(title)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_screenplay_documents ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, screenplay_id TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, UNIQUE (screenplay_id, kind), CHECK (length(kind) BETWEEN 1 AND 40 AND NOT kind GLOB '*[^a-z0-9_-]*'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (screenplay_id) REFERENCES cotton_screenplays(id) )"#,// Version 99: act, sequence, status and location are the owner's words and// the engine never writes them; characters_in_scene is the scene's cast as// one line, re-derived from the Fountain body on every body write while// characters_set_by is not 'owner' (cotton-tools screenplay write.rs).r#"CREATE TABLE cotton_screenplay_scenes ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, screenplay_id TEXT NOT NULL, "position" REAL NOT NULL, heading TEXT, body TEXT NOT NULL, purpose TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, act TEXT, sequence TEXT, status TEXT, location TEXT, characters_in_scene TEXT, characters_set_by TEXT, trashed_at TEXT, CHECK (act IS NULL OR act IN ('1', '2', '3', '4', '5')), CHECK (status IS NULL OR status IN ('outline', 'drafted', 'locked')), CHECK (characters_set_by IS NULL OR characters_set_by IN ('engine', 'owner')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (screenplay_id) REFERENCES cotton_screenplays(id) )"#,r#"CREATE TABLE cotton_screenplay_characters ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, screenplay_id TEXT NOT NULL, name TEXT NOT NULL, aliases TEXT, bio TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, want TEXT, arc TEXT, age TEXT, casting_thoughts TEXT, picture_photo_id TEXT, UNIQUE (screenplay_id, name), CHECK (length(trim(name)) > 0), CHECK (aliases IS NULL OR json_type(aliases) = 'array'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (screenplay_id) REFERENCES cotton_screenplays(id) )"#,r#"CREATE TABLE cotton_screenplay_drafts ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, screenplay_id TEXT NOT NULL, name TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (length(trim(name)) > 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (screenplay_id) REFERENCES cotton_screenplays(id) )"#,r#"CREATE TABLE cotton_screenplay_draft_scenes ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, draft_id TEXT NOT NULL, scene_id TEXT NOT NULL, "position" REAL NOT NULL, heading TEXT, body TEXT NOT NULL, purpose TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (draft_id, scene_id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (draft_id) REFERENCES cotton_screenplay_drafts(id) )"#,r#"CREATE TABLE cotton_email_threads ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, external_key TEXT NOT NULL, subject TEXT, first_at TEXT, last_at TEXT, email_count INTEGER NOT NULL DEFAULT 0, summary TEXT, summary_updated_at TEXT, summary_by TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', trashed_at TEXT, _born TEXT, sender_address TEXT, sender_kind TEXT, record_kind TEXT, amount_minor INTEGER, currency TEXT, merchant TEXT, record_on TEXT, reference TEXT, record_reason TEXT, UNIQUE (workspace_id, external_key), CHECK ((record_kind IS NULL) OR (record_kind IN ('receipt', 'statement', 'ticket', 'booking', 'code', 'delivery', 'notice'))), CHECK ((currency IS NULL) OR (length(currency) = 3 AND currency = upper(currency))), CHECK ((record_on IS NULL) OR (record_on GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]')), CHECK ((sender_address IS NULL) OR (sender_address = lower(sender_address) AND length(sender_address) > 0)), CHECK ((sender_kind IS NULL) OR (sender_kind IN ('person', 'service', 'junk'))), CHECK (length(external_key) > 0), CHECK (email_count >= 0), CHECK ((summary IS NULL) OR (length(summary) <= 4000)), CHECK ((summary_by IS NULL) OR (length(trim(summary_by)) > 0)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_emails ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thread_id TEXT NOT NULL, external_id TEXT NOT NULL, subject TEXT, from_email TEXT NOT NULL, from_name TEXT, recipients TEXT NOT NULL DEFAULT '[]', sent_at TEXT NOT NULL, body TEXT, snippet TEXT, attachments TEXT NOT NULL DEFAULT '[]', created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', gmail_id TEXT, gmail_account TEXT, labels TEXT CHECK (labels IS NULL OR json_type(labels) = 'array'), unread INTEGER NOT NULL DEFAULT 0, starred INTEGER NOT NULL DEFAULT 0, in_inbox INTEGER NOT NULL DEFAULT 1, trashed_at TEXT, sync_state TEXT CHECK (sync_state IS NULL OR sync_state IN ('synced', 'pending')), _born TEXT, account TEXT, to_line TEXT, cc_line TEXT, direction TEXT, message_id TEXT, message_refs TEXT, list_unsubscribe TEXT, list_unsubscribe_post TEXT, list_id TEXT, precedence TEXT, auto_submitted TEXT, gmail_category TEXT, archived_at TEXT, landed_at TEXT, UNIQUE (workspace_id, external_id), CHECK (length(external_id) > 0), CHECK (length(from_email) > 0), CHECK (json_type(recipients) = 'array'), CHECK (json_type(attachments) = 'array'), FOREIGN KEY (thread_id) REFERENCES cotton_email_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_email_participants ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thread_id TEXT NOT NULL, email TEXT NOT NULL, display_name TEXT, role TEXT NOT NULL DEFAULT 'cc', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (thread_id, email), CHECK (length(email) > 0), CHECK (email = lower(email)), CHECK (role IN ('from', 'to', 'cc')), FOREIGN KEY (thread_id) REFERENCES cotton_email_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, MOODS_TABLE, SESSION_MESSAGES_TABLE,r#"CREATE TABLE cotton_media_faces ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, source TEXT NOT NULL, source_id TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, w REAL NOT NULL, h REAL NOT NULL, quality REAL, cluster_id TEXT, person_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', suggested_person_id TEXT, suggested_distance REAL CHECK (suggested_distance IS NULL OR (suggested_distance >= 0 AND suggested_distance <= 2)), suggestion_dismissed_at TEXT, _born TEXT, embedding TEXT CHECK (embedding IS NULL OR length(embedding) > 0), embedding_model TEXT CHECK (embedding_model IS NULL OR length(embedding_model) > 0), person_by TEXT CHECK (person_by IS NULL OR person_by = 'match'), CHECK (record_kind IN ('photo', 'video')), CHECK (substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'), CHECK (source IN ('apple', 'cotton')), CHECK (x >= 0 AND x <= 1 AND y >= 0 AND y <= 1), CHECK (w > 0 AND w <= 1 AND h > 0 AND h <= 1), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_media_duplicates ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, record_kind TEXT NOT NULL, keep_id TEXT NOT NULL, copy_id TEXT NOT NULL, distance INTEGER NOT NULL, method TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'open', decided_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (record_kind IN ('photo', 'video')), CHECK (keep_id <> copy_id), CHECK (substr(keep_id, 1, length(record_kind) + 1) = record_kind || ':'), CHECK (substr(copy_id, 1, length(record_kind) + 1) = record_kind || ':'), CHECK (distance >= 0 AND distance <= 64), CHECK (method IN ('phash', 'featureprint')), CHECK (state IN ('open', 'confirmed', 'dismissed')), CHECK ((state = 'open') = (decided_at IS NULL)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_person_suggestions ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, person_id TEXT, contact_id TEXT, candidate_id TEXT NOT NULL, reason TEXT NOT NULL, score REAL NOT NULL, state TEXT NOT NULL DEFAULT 'open', decided_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (person_id <> candidate_id), CHECK (reason IN ('name_exact', 'name_fuzzy', 'handle_name')), CHECK (score >= 0 AND score <= 1), CHECK (state IN ('open', 'merged', 'different')), CHECK ((state = 'open') = (decided_at IS NULL)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, SECRETS_TABLE, VAULT_KEYS_TABLE, VAULT_STATE_TABLE, SECRET_PLACEMENTS_TABLE, PLACEMENT_PROPOSALS_TABLE, DEVICES_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, MEDIA_HOLDINGS_TABLE, MEDIA_BACKUPS_TABLE, MEDIA_BACKUPS_AUTHOR_INDEX, STORAGE_RULES_TABLE, AGENT_ACCOUNTS_TABLE, DEVICE_SAMPLES_TABLE, ACCOUNT_USAGE_SAMPLES_TABLE, REPOS_TABLE, REPO_PULLS_TABLE, REPO_ISSUES_TABLE, REPO_COMMENTS_TABLE, REPO_COMMITS_TABLE, REPO_BUNDLES_TABLE, REPO_CLONES_TABLE, REPO_RELEASES_TABLE, REPO_RULES_TABLE, REPO_LABELS_TABLE, REPO_RUNNERS_TABLE, REPO_RUNS_TABLE, REPO_JOBS_TABLE, REPO_VARS_TABLE, MACHINE_RUNNERS_TABLE, CODE_CREDENTIALS_TABLE, SESSION_TASKS_TABLE, NOTE_ATTACHMENTS_TABLE, DEV_JOBS_TABLE, THOUGHT_ATTACHMENTS_TABLE, MERGE_QUEUE_TABLE, TABLE_DEFINITIONS_TABLE, TOOL_DEFINITIONS_TABLE, TOOLKITS_TABLE, BOARD_DEFINITIONS_TABLE, THEME_DEFINITIONS_TABLE, RECORDS_TABLE, CHANGES_TABLE,r#"CREATE TABLE cotton_assistant_runs ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, source_kind TEXT NOT NULL CHECK (source_kind IN ('thought','comment','session_message')), source_id TEXT NOT NULL, record_kind TEXT, record_id TEXT, session_id TEXT, class TEXT NOT NULL CHECK (class IN ('quick','deep')), state TEXT NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','running','done','failed')), task TEXT NOT NULL CHECK (length(task) BETWEEN 1 AND 500), receipt TEXT NOT NULL, turns INTEGER NOT NULL DEFAULT 0, input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0, cost_usd REAL, result_note_id TEXT, stopped_reason TEXT CHECK (stopped_reason IS NULL OR stopped_reason IN ('answered','turn_ceiling','time_ceiling','no_key','model_refused')), error TEXT, queued_at TEXT NOT NULL, started_at TEXT, finished_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK ((state = 'failed') = (error IS NOT NULL)), CHECK ((state IN ('done','failed')) = (finished_at IS NOT NULL)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_blocked_senders ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, address TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, address), CHECK (length(address) > 0), CHECK (address = lower(address)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_email_senders ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, address TEXT NOT NULL, kind TEXT NOT NULL, written_to INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, decided_by TEXT CHECK (decided_by IS NULL OR decided_by IN ('owner', 'assistant')), verdict TEXT CHECK (verdict IS NULL OR verdict IN ('person', 'service', 'junk')), reason TEXT, decided_at TEXT, UNIQUE (workspace_id, address), CHECK (length(address) > 0), CHECK (address = lower(address)), CHECK (kind IN ('person', 'service', 'junk')), CHECK (written_to IN (0, 1)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,// Schema 148 (Cotton Calling, 12 Nov 2026): no CHECK on `source`. A call// made in Cotton lands beside the imported history under `cotton`; where a// call came from is the object's definition to say, not the copy's.r#"CREATE TABLE cotton_call_log ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, source TEXT NOT NULL, external_id TEXT NOT NULL, provider TEXT NOT NULL, direction TEXT NOT NULL, outcome TEXT NOT NULL, started_at TEXT NOT NULL, duration_s INTEGER NOT NULL DEFAULT 0, handle TEXT, contact_id TEXT, person_id TEXT, device TEXT, meta TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, source, external_id), CHECK (direction IN ('in', 'out')), CHECK (outcome IN ('answered', 'missed', 'cancelled', 'failed')), CHECK (length(trim(external_id)) > 0), CHECK (length(trim(provider)) > 0), CHECK (duration_s >= 0), CHECK (json_type(meta) = 'object'), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_msg_threads" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, contact_id TEXT, kind TEXT NOT NULL DEFAULT 'dm', last_message_at TEXT, last_message_preview TEXT, archived INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, title TEXT, external_key TEXT, _hlc TEXT NOT NULL DEFAULT '', photo_key TEXT, description TEXT, created_by_phone TEXT, read_seq INTEGER NOT NULL DEFAULT 0, delivered_seq INTEGER NOT NULL DEFAULT 0, muted_until TEXT, pinned_at TEXT, unread_marked_at TEXT, draft TEXT, draft_reply_to_id TEXT, cleared_before TEXT, summary TEXT CHECK ((summary IS NULL) OR (length(summary) <= 4000)), summary_updated_at TEXT, summary_by TEXT CHECK ((summary_by IS NULL) OR (length(trim(summary_by)) > 0)), _born TEXT, trashed_at TEXT, CHECK (kind IN ('dm', 'group')), CHECK (((kind = 'dm') AND ((contact_id IS NOT NULL) OR (NULLIF(trim(COALESCE(title, '')), '') IS NOT NULL))) OR ((kind = 'group') AND (contact_id IS NULL) AND (NULLIF(trim(COALESCE(title, '')), '') IS NOT NULL))), FOREIGN KEY (contact_id) REFERENCES cotton_msg_contacts(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_msg_thread_participants" ( id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, workspace_id TEXT NOT NULL, contact_id TEXT, display_name TEXT, created_at TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', left_at TEXT, is_self INTEGER NOT NULL DEFAULT 0, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (role IN ('admin', 'member')), CHECK ((is_self = 1) OR (contact_id IS NOT NULL) OR (NULLIF(trim(COALESCE(display_name, '')), '') IS NOT NULL)), FOREIGN KEY (contact_id) REFERENCES cotton_msg_contacts(id), FOREIGN KEY (thread_id) REFERENCES cotton_msg_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_inbox_items" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, raw_text TEXT, audio_url TEXT, captured_at TEXT NOT NULL, route_status TEXT NOT NULL DEFAULT 'pending', routed_kind TEXT, routed_id TEXT, route_confidence TEXT, correction_of TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, transcript TEXT, route_reason TEXT, route_proposal TEXT, routed_records TEXT, route_plan TEXT, route_plan_user_edited INTEGER, -- v20: the chat sweep's two marks on a capture. swept_at TEXT, sweep_note TEXT, -- v75: where the thought was said (Spec 7): the tool's table when it -- was said inside one, and the record when it was said on a record's -- page. Both NULL for a thought said on the database's own page. -- capture.create refuses a record without its table; no constraint here, a -- synced row arrives column by column (tests/no_cross_column_checks.rs). said_table TEXT, said_record_id TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK ((raw_text IS NOT NULL) OR (audio_url IS NOT NULL)), CHECK (route_status IN ('pending', 'routed', 'corrected', 'dismissed')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_money_accounts" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL, subtype TEXT NOT NULL, name TEXT NOT NULL, counterparty_person_id TEXT, currency TEXT NOT NULL, institution TEXT, number_mask TEXT, is_default INTEGER NOT NULL DEFAULT 0, is_pooled INTEGER CHECK (is_pooled IS NULL OR is_pooled IN (0,1)), archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK (subtype IN ('bank', 'cash', 'credit_card', 'wallet', 'receivable', 'payable', 'loan', 'lent_out', 'fixed_asset')), FOREIGN KEY (counterparty_person_id) REFERENCES cotton_people(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_money_transactions" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, occurred_on TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', payee_text TEXT, account_id TEXT, counterparty_person_id TEXT, amount_minor INTEGER, amount_known INTEGER NOT NULL DEFAULT 1 CHECK (amount_known IN (0,1)), direction TEXT NOT NULL DEFAULT 'out' CHECK (direction IN ('in','out')), currency TEXT, for_period TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'actual' CHECK (status IN ('actual','expected')), certainty TEXT CHECK (certainty IS NULL OR certainty IN ('fixed','expected','estimate')), repeat TEXT NOT NULL DEFAULT 'none' CHECK (repeat IN ('none','monthly')), repeat_day INTEGER CHECK (repeat_day IS NULL OR repeat_day BETWEEN 1 AND 31), between_us INTEGER NOT NULL DEFAULT 0 CHECK (between_us IN (0,1)), moves_money INTEGER NOT NULL DEFAULT 1 CHECK (moves_money IN (0,1)), tag TEXT, transfer_of TEXT, source TEXT NOT NULL DEFAULT 'manual', external_hash TEXT, notes TEXT, settles_transaction_id TEXT, due_date TEXT, source_inbox_id TEXT, created_by TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, trashed_at TEXT, CHECK ((settles_transaction_id IS NULL) OR (settles_transaction_id <> id)), CHECK (source IN ('capture', 'manual', 'import', 'system', 'schedule', 'migration', 'statement', 'external')), FOREIGN KEY (account_id) REFERENCES cotton_money_accounts(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_documents" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT, original_name TEXT NOT NULL, mime TEXT NOT NULL, byte_size INTEGER NOT NULL, sha256 TEXT NOT NULL, storage_path TEXT NOT NULL, decrypted_path TEXT, password TEXT, page_count INTEGER, status TEXT NOT NULL DEFAULT 'processing', failed_stage TEXT, error_code TEXT, status_changed_at TEXT, doc_type TEXT NOT NULL DEFAULT 'other', document_date TEXT, period_start TEXT, period_end TEXT, issuer TEXT, summary TEXT, facts TEXT NOT NULL DEFAULT '{}', text_extracted INTEGER NOT NULL DEFAULT 0, source TEXT NOT NULL DEFAULT 'app', mcp_token_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), secret_id TEXT, _born TEXT, trashed_at TEXT, UNIQUE (workspace_id, sha256), CHECK (byte_size >= 0), CHECK (doc_type IN ('bank_statement', 'card_statement', 'invoice', 'receipt', 'tax', 'id', 'insurance', 'medical', 'legal', 'ticket', 'statement_other', 'letter', 'manual', 'other')), CHECK ((status = 'failed') = (failed_stage IS NOT NULL)), CHECK (failed_stage IS NULL OR failed_stage IN ('unlock', 'extract', 'summarize', 'land')), CHECK ((page_count IS NULL) OR (page_count >= 0)), CHECK ((period_start IS NULL) OR (period_end IS NULL) OR (period_end >= period_start)), CHECK (length(sha256) = 64 AND NOT sha256 GLOB '*[^0-9a-f]*'), CHECK (source IN ('app', 'agent', 'share')), CHECK (status IN ('processing', 'summarizing', 'ready', 'locked', 'failed')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, FEEDBACK_TABLE, LINKS_TABLE, MEMORIES_TABLE,r#"CREATE TABLE "cotton_msg_contacts" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, phone_e164 TEXT, display_name TEXT, person_id TEXT, auth_user_id TEXT, vip INTEGER NOT NULL DEFAULT 0, muted INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0, on_cotton_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, avatar_key TEXT, UNIQUE (workspace_id, phone_e164), CHECK (phone_e164 IS NULL OR (length(phone_e164) BETWEEN 8 AND 15 AND NOT phone_e164 GLOB '*[^0-9]*')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_msg_messages" ( id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, workspace_id TEXT NOT NULL, direction TEXT NOT NULL, channel TEXT NOT NULL, origin TEXT NOT NULL, body TEXT, media TEXT NOT NULL DEFAULT '[]', external_id TEXT, sent_at TEXT NOT NULL, created_at TEXT NOT NULL, read_at TEXT, reply_to_id TEXT, reply_to_external_id TEXT, reactions TEXT NOT NULL DEFAULT '[]', meta TEXT NOT NULL DEFAULT '{}', sender_contact_id TEXT, sender_participant_id TEXT, seq INTEGER, edited_at TEXT, deleted_at TEXT, forward_of_id TEXT, mentions TEXT NOT NULL DEFAULT '[]', starred_at TEXT, hidden_at TEXT, send_state TEXT, send_error TEXT, send_attempts INTEGER NOT NULL DEFAULT 0, trashed_at TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (channel IN ('cotton', 'whatsapp', 'imessage', 'sms', 'instagram')), CHECK (send_state IS NULL OR send_state IN ('queued', 'sending', 'sent', 'delivered', 'read', 'failed')), CHECK (direction IN ('in', 'out')), CHECK (json_type(media) = 'array'), CHECK (json_type(meta) = 'object'), CHECK (origin IN ('live', 'imported')), CHECK (json_type(reactions) = 'array'), CHECK (json_type(mentions) = 'array'), FOREIGN KEY (thread_id) REFERENCES cotton_msg_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#, COMMENTS_TABLE,r#"CREATE TABLE "cotton_photos" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, key TEXT NOT NULL, sha256 TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, width INTEGER, height INTEGER, taken_at TEXT NOT NULL, preview TEXT, caption TEXT, summary TEXT, summary_by TEXT, summary_at TEXT, review_note TEXT, review_by TEXT, review_at TEXT, taken_offset INTEGER, latitude REAL, longitude REAL, place_name TEXT, place_city TEXT, place_region TEXT, place_country TEXT, camera_make TEXT, camera_model TEXT, orientation INTEGER, favourite INTEGER NOT NULL DEFAULT 0, subtypes TEXT NOT NULL DEFAULT '[]', original_filename TEXT, aesthetic_score REAL, curation_score REAL, labels TEXT NOT NULL DEFAULT '[]', phash TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', ocr_text TEXT, is_utility INTEGER CHECK (is_utility IS NULL OR is_utility IN (0, 1)), origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, trashed_at TEXT, image_embedding TEXT CHECK (image_embedding IS NULL OR length(image_embedding) > 0), image_embedding_model TEXT CHECK (image_embedding_model IS NULL OR length(image_embedding_model) > 0), UNIQUE (workspace_id, sha256), CHECK (id = 'photo:' || sha256), CHECK (sha256 NOT GLOB '*[^0-9a-f]*' AND length(sha256) = 64), CHECK (size_bytes >= 0), CHECK (width IS NULL OR width > 0), CHECK (height IS NULL OR height > 0), CHECK (caption IS NULL OR length(caption) <= 500), CHECK (review_note IS NULL OR (length(trim(review_note)) > 0 AND length(review_note) <= 280)), CHECK ((summary IS NULL) = (summary_at IS NULL)), CHECK ((review_note IS NULL) = (review_at IS NULL)), CHECK ((latitude IS NULL) = (longitude IS NULL)), CHECK (latitude IS NULL OR (latitude >= -90 AND latitude <= 90)), CHECK (longitude IS NULL OR (longitude >= -180 AND longitude <= 180)), CHECK (orientation IS NULL OR (orientation >= 1 AND orientation <= 8)), CHECK (taken_offset IS NULL OR (taken_offset >= -86400 AND taken_offset <= 86400)), CHECK (favourite IN (0, 1)), CHECK (json_type(subtypes) = 'array'), CHECK (json_type(labels) = 'array'), CHECK (aesthetic_score IS NULL OR (aesthetic_score >= -1 AND aesthetic_score <= 1)), CHECK (curation_score IS NULL OR (curation_score >= -1 AND curation_score <= 1)), CHECK (phash IS NULL OR (length(phash) = 16 AND phash NOT GLOB '*[^0-9a-f]*')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_videos" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, key TEXT NOT NULL, sha256 TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, width INTEGER, height INTEGER, duration_ms INTEGER, taken_at TEXT NOT NULL, preview TEXT, poster_key TEXT, caption TEXT, summary TEXT, summary_by TEXT, summary_at TEXT, review_note TEXT, review_by TEXT, review_at TEXT, taken_offset INTEGER, latitude REAL, longitude REAL, place_name TEXT, place_city TEXT, place_region TEXT, place_country TEXT, camera_make TEXT, camera_model TEXT, orientation INTEGER, favourite INTEGER NOT NULL DEFAULT 0, subtypes TEXT NOT NULL DEFAULT '[]', original_filename TEXT, aesthetic_score REAL, curation_score REAL, labels TEXT NOT NULL DEFAULT '[]', phash TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, trashed_at TEXT, UNIQUE (workspace_id, sha256), CHECK (id = 'video:' || sha256), CHECK (sha256 NOT GLOB '*[^0-9a-f]*' AND length(sha256) = 64), CHECK (size_bytes >= 0), CHECK (width IS NULL OR width > 0), CHECK (height IS NULL OR height > 0), CHECK (caption IS NULL OR length(caption) <= 500), CHECK (review_note IS NULL OR (length(trim(review_note)) > 0 AND length(review_note) <= 280)), CHECK ((summary IS NULL) = (summary_at IS NULL)), CHECK ((review_note IS NULL) = (review_at IS NULL)), CHECK ((latitude IS NULL) = (longitude IS NULL)), CHECK (latitude IS NULL OR (latitude >= -90 AND latitude <= 90)), CHECK (longitude IS NULL OR (longitude >= -180 AND longitude <= 180)), CHECK (orientation IS NULL OR (orientation >= 1 AND orientation <= 8)), CHECK (taken_offset IS NULL OR (taken_offset >= -86400 AND taken_offset <= 86400)), CHECK (favourite IN (0, 1)), CHECK (json_type(subtypes) = 'array'), CHECK (json_type(labels) = 'array'), CHECK (aesthetic_score IS NULL OR (aesthetic_score >= -1 AND aesthetic_score <= 1)), CHECK (curation_score IS NULL OR (curation_score >= -1 AND curation_score <= 1)), CHECK (phash IS NULL OR (length(phash) = 16 AND phash NOT GLOB '*[^0-9a-f]*')), CHECK (duration_ms IS NULL OR duration_ms >= 0), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_media_sightings" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, source TEXT NOT NULL, source_id TEXT, thread_id TEXT, key TEXT NOT NULL, seen_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, CHECK (record_kind IN ('photo', 'video')), CHECK (substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'), CHECK (source IN ('message', 'share', 'library', 'apple_library', 'email')), CHECK ((source = 'message') = (thread_id IS NOT NULL)), CHECK (source NOT IN ('message', 'apple_library', 'email') OR source_id IS NOT NULL), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_media_albums ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, kind TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'open', decided_at TEXT, title TEXT NOT NULL, title_by TEXT NOT NULL DEFAULT 'derived', starts_at TEXT NOT NULL, ends_at TEXT NOT NULL, home_label TEXT, cover_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, trashed_at TEXT, CHECK (kind IN ('trip', 'event')), CHECK (state IN ('open', 'kept', 'dismissed')), CHECK ((state = 'open') = (decided_at IS NULL)), CHECK (title_by IN ('derived', 'user')), CHECK (starts_at <= ends_at), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE cotton_media_album_items ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, album_id TEXT NOT NULL, record_kind TEXT NOT NULL, record_id TEXT NOT NULL, added_by TEXT NOT NULL, sort_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', origin_handle TEXT CHECK (origin_handle IS NULL OR length(origin_handle) > 0), _born TEXT, CHECK (record_kind IN ('photo', 'video')), CHECK (substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'), CHECK (added_by IN ('derived', 'user')), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE, FOREIGN KEY (album_id) REFERENCES cotton_media_albums(id) )"#, PROJECT_LINKS_TABLE,r#"CREATE TABLE "cotton_people" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, full_name TEXT NOT NULL, org TEXT, role_title TEXT, city TEXT, summary TEXT, summary_updated_at TEXT, summary_by TEXT, contact_source TEXT NOT NULL DEFAULT 'manual', device_contact_id TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, birth_month INTEGER, birth_day INTEGER, birth_year INTEGER, timezone TEXT, avatar_url TEXT, avatar_key TEXT, device_contact_snapshot TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, city_filled_at TEXT, avatar_photo_id TEXT, trashed_at TEXT, language TEXT NOT NULL DEFAULT 'en' CHECK (length(language) BETWEEN 2 AND 3 AND language NOT GLOB '*[^a-z]*'), face_embedding TEXT CHECK (face_embedding IS NULL OR length(face_embedding) > 0), face_embedding_model TEXT CHECK (face_embedding_model IS NULL OR length(face_embedding_model) > 0), face_embedding_from TEXT CHECK (face_embedding_from IS NULL OR length(face_embedding_from) > 0), city_place TEXT, country TEXT, CHECK ((birth_day IS NULL) OR ((birth_day >= 1) AND (birth_day <= 31))), CHECK ((birth_month IS NULL) OR ((birth_month >= 1) AND (birth_month <= 12))), CHECK (((birth_month IS NOT NULL) + (birth_day IS NOT NULL)) IN (0, 2)), CHECK (contact_source IN ('import', 'manual', 'apple_library')), CHECK ((summary IS NULL) OR (length(summary) <= 4000)), CHECK ((summary_by IS NULL) OR (length(trim(summary_by)) > 0)), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_msg_receipts" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, thread_id TEXT NOT NULL, phone TEXT NOT NULL, delivered_seq INTEGER NOT NULL DEFAULT 0, read_seq INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (thread_id, phone), CHECK ((length(phone) BETWEEN 8 AND 15 AND NOT phone GLOB '*[^0-9]*') OR (length(phone) BETWEEN 2 AND 31 AND phone GLOB '[a-z0-9]*' AND NOT phone GLOB '*[^a-z0-9-]*' AND phone GLOB '*[^0-9]*')), FOREIGN KEY (thread_id) REFERENCES cotton_msg_threads(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,r#"CREATE TABLE "cotton_msg_contact_handles" ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, contact_id TEXT NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL, created_at TEXT NOT NULL, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, UNIQUE (workspace_id, kind, value), CHECK (kind IN ('phone', 'email', 'cotton', 'instagram', 'facebook', 'linkedin')), CHECK (kind <> 'phone' OR (length(value) BETWEEN 8 AND 15 AND NOT value GLOB '*[^0-9]*')), CHECK (kind <> 'email' OR (value = lower(value) AND value LIKE '%_@_%' AND value NOT GLOB '* *')), CHECK (kind <> 'cotton' OR (length(value) BETWEEN 2 AND 31 AND value GLOB '[a-z0-9]*' AND NOT value GLOB '*[^a-z0-9-]*' AND value GLOB '*[^0-9]*')), FOREIGN KEY (contact_id) REFERENCES cotton_msg_contacts(id), FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE )"#,// v42 — `decision`. DECISIONS_TABLE, AUTHORS_TABLE, REVOCATIONS_TABLE, SERVING_MACHINE_TABLE, VAULT_RETIRED_KEYS_TABLE, MEDIA_ERASURES_TABLE, UNDOS_TABLE, GRANT_ROTATIONS_TABLE, DATABASES_TABLE, DATABASE_DEPARTURES_TABLE, PERSON_KEYS_TABLE, ADMISSIONS_TABLE, MEMBER_PERSON_CLAIMS_TABLE, DEVICE_STATEMENTS_TABLE, INVITES_TABLE, JOINED_PLACES_TABLE, IMPORTS_TABLE, CONNECTIONS_TABLE,// v86 — `post`. POSTS_TABLE, PERSON_HANDLES_TABLE, PERSON_LANGUAGES_TABLE,// v114 — filing a chat in a shared database. MSG_THREAD_FILINGS_TABLE,// v118 — what a device keeps. DEVICE_KEEP_TABLE,// 137 — the internal kinds' own homes. GROUPS_TABLE, GROUP_MEMBERS_TABLE, TOOL_ASSETS_TABLE, AUTOMATION_RUNS_TABLE,// v125 — a reader's own marks on a filed chat. MSG_THREAD_MARKS_TABLE,// v126 — a phone heard a push. PUSH_ACKS_TABLE, DEVICE_RELAY_KEYS_TABLE,// onlyyou rise — who may hold a record. AUDIENCES_TABLE,// v120 — the owner's outage record. OUTAGES_TABLE,// gen-kind: schema-ddl-tables FTS_TODOS_TABLE, FTS_EVENTS_TABLE, FTS_NOTES_TABLE, FTS_LOCATIONS_TABLE, FTS_MEETINGS_TABLE, FTS_PAGES_TABLE, FTS_MEMORIES_TABLE, FTS_DOCUMENTS_TABLE, FTS_DOCUMENT_PAGES_TABLE, FTS_PROMPTS_TABLE, FTS_EMAILS_TABLE, FTS_MAIL_TABLE, FTS_MOODS_TABLE, FTS_THOUGHTS_TABLE, FTS_SESSION_MESSAGES_TABLE, FTS_VIDEOS_TABLE, FTS_MESSAGES_TABLE, FTS_CHAT_TABLE, FTS_PHOTOS_TABLE, FTS_PEOPLE_TABLE, FTS_SECRETS_TABLE, FTS_REPO_PULLS_TABLE, FTS_REPO_ISSUES_TABLE,// v42 — `decision`. FTS_DECISIONS_TABLE,// v86 — `post`. FTS_POSTS_TABLE,// gen-kind: schema-ddl-ftsr#"CREATE INDEX idx_media_state ON _media (state, next_attempt_at)"#,r#"CREATE INDEX idx_outbox_order ON _outbox (hlc, op_id)"#, PARKED_ROW_INDEX,r#"CREATE UNIQUE INDEX cotton_workspaces_owner_user_id_key ON cotton_workspaces (owner_user_id)"#,r#"CREATE INDEX idx_cotton_alarms_workspace ON cotton_alarms (workspace_id)"#,r#"CREATE INDEX idx_cotton_collections_workspace ON cotton_collections (workspace_id)"#,r#"CREATE INDEX idx_cotton_document_pages_workspace ON cotton_document_pages (workspace_id)"#,r#"CREATE INDEX idx_cotton_event_attendees_event ON cotton_event_attendees (event_id)"#,r#"CREATE INDEX idx_cotton_msg_messages_unread_cursor ON cotton_msg_messages (thread_id, seq, sent_at) WHERE direction = 'in' AND origin = 'live' AND hidden_at IS NULL AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_notes_home ON cotton_notes (workspace_id) WHERE kind = 'note' AND managed_by IS NULL AND archived_at IS NULL AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_todos_open ON cotton_todos (workspace_id) WHERE status = 'open' AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_events_invites ON cotton_events (my_response, starts_at) WHERE my_response = 'needs_action' AND organizer_is_self = 0 AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_balance ON cotton_money_transactions (workspace_id,account_id,currency,occurred_on,CASE WHEN direction='in' THEN amount_minor ELSE -amount_minor END,direction,amount_minor,status,amount_known,moves_money,trashed_at) WHERE status='actual' AND amount_known=1 AND moves_money=1 AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_glance ON cotton_money_transactions (workspace_id,trashed_at,between_us,status,direction,currency,amount_minor)"#,r#"CREATE INDEX idx_cotton_emails_binned ON cotton_emails (workspace_id,trashed_at) WHERE trashed_at IS NOT NULL"#,r#"CREATE INDEX idx_cotton_memories_glance ON cotton_memories (workspace_id,status,visibility,origin_kind,reviewed_at,created_at,id,title)"#,r#"CREATE INDEX idx_cotton_events_collection ON cotton_events (collection_id)"#,r#"CREATE INDEX idx_cotton_events_range ON cotton_events (starts_at)"#,r#"CREATE INDEX idx_cotton_goals_workspace_status ON cotton_goals (workspace_id, status, sort_order)"#,r#"CREATE INDEX idx_cotton_google_accounts_workspace ON cotton_google_accounts (workspace_id)"#,r#"CREATE INDEX idx_cotton_locations_workspace ON cotton_locations (workspace_id)"#,r#"CREATE INDEX idx_cotton_mcp_audit_token ON cotton_mcp_audit (token_id, created_at DESC)"#,r#"CREATE INDEX idx_cotton_mcp_audit_workspace ON cotton_mcp_audit (workspace_id, created_at DESC)"#,r#"CREATE INDEX idx_cotton_mcp_tokens_owner ON cotton_mcp_tokens (owner_user_id, created_at DESC)"#,r#"CREATE INDEX idx_cotton_meeting_utterances_meeting ON cotton_meeting_utterances (meeting_id, seq)"#,r#"CREATE INDEX idx_cotton_meetings_event ON cotton_meetings (event_id) WHERE event_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_meetings_pipeline ON cotton_meetings (status, status_changed_at) WHERE status IN ('transcribing', 'summarizing')"#,r#"CREATE INDEX idx_cotton_meetings_workspace_started ON cotton_meetings (workspace_id, started_at DESC)"#,r#"CREATE INDEX idx_cotton_news_editions_pipeline ON cotton_news_editions (status, status_changed_at) WHERE status IN ('queued', 'harvesting', 'writing')"#,r#"CREATE INDEX idx_cotton_news_editions_workspace_created ON cotton_news_editions (workspace_id, created_at DESC)"#,r#"CREATE INDEX idx_cotton_news_seen_topic ON cotton_news_seen (workspace_id, topic_id, first_seen_at DESC)"#,r#"CREATE INDEX idx_cotton_news_stories_edition_rank ON cotton_news_stories (edition_id, rank)"#,r#"CREATE INDEX idx_cotton_news_topics_workspace_active ON cotton_news_topics (workspace_id, active, sort_order)"#,r#"CREATE INDEX idx_cotton_notes_managed ON cotton_notes (managed_by) WHERE managed_by IS NOT NULL"#,r#"CREATE INDEX idx_cotton_notes_workspace ON cotton_notes (workspace_id)"#,r#"CREATE UNIQUE INDEX idx_cotton_notes_workspace_external ON cotton_notes (workspace_id, external_id) WHERE external_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_pages_workspace ON cotton_pages (workspace_id)"#,r#"CREATE INDEX idx_cotton_person_notes_person ON cotton_person_notes (person_id)"#,r#"CREATE INDEX idx_cotton_todo_recurrences_workspace ON cotton_todo_recurrences (workspace_id)"#,r#"CREATE INDEX idx_cotton_todos_recurrence ON cotton_todos (recurrence_id) WHERE recurrence_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_todos_workspace ON cotton_todos (workspace_id)"#,r#"CREATE INDEX idx_cotton_todos_workspace_due ON cotton_todos (workspace_id, due_at)"#,r#"CREATE INDEX idx_cotton_voice_vocabulary_workspace ON cotton_voice_vocabulary (workspace_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_events_gcal_id ON cotton_events (account, gcal_id) WHERE gcal_id IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_msg_owner_settings_handle ON cotton_msg_owner_settings (handle)"#,r#"CREATE UNIQUE INDEX uq_cotton_notes_public_slug ON cotton_notes (public_slug) WHERE public_slug IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_voice_vocabulary_workspace_term ON cotton_voice_vocabulary (workspace_id, lower(term))"#,r#"CREATE INDEX idx_cotton_dictations_workspace_spoken ON cotton_dictations (workspace_id, spoken_at DESC)"#,r#"CREATE UNIQUE INDEX uq_cotton_dictations_workspace_external ON cotton_dictations (workspace_id, external_id) WHERE external_id IS NOT NULL"#, SESSIONS_RECENT_INDEX, SESSIONS_PROJECT_INDEX, SESSIONS_MACHINE_INDEX, SESSIONS_QUEUE_INDEX, PROMPTS_WORKSPACE_INDEX, PROMPTS_SESSION_INDEX,r#"CREATE INDEX idx_cotton_msg_reactions_message ON cotton_msg_reactions (message_id)"#,r#"CREATE INDEX idx_cotton_msg_reactions_workspace ON cotton_msg_reactions (workspace_id)"#,r#"CREATE INDEX idx_cotton_stories_posted ON cotton_stories (workspace_id, posted_at)"#,r#"CREATE INDEX idx_cotton_stories_person ON cotton_stories (person_id)"#,r#"CREATE INDEX idx_cotton_screenplays_workspace ON cotton_screenplays (workspace_id, archived_at)"#,r#"CREATE INDEX idx_cotton_screenplay_scenes_order ON cotton_screenplay_scenes (screenplay_id, "position")"#,r#"CREATE INDEX idx_cotton_screenplay_characters_screenplay ON cotton_screenplay_characters (screenplay_id, name)"#,r#"CREATE INDEX idx_cotton_screenplay_drafts_screenplay ON cotton_screenplay_drafts (screenplay_id, created_at)"#,r#"CREATE INDEX idx_cotton_screenplay_draft_scenes_order ON cotton_screenplay_draft_scenes (draft_id, "position")"#,r#"CREATE INDEX idx_cotton_email_threads_workspace_recent ON cotton_email_threads (workspace_id, last_at DESC)"#,r#"CREATE INDEX idx_cotton_email_threads_sender_kind ON cotton_email_threads (workspace_id, sender_kind, last_at DESC)"#,r#"CREATE INDEX idx_cotton_email_threads_sender ON cotton_email_threads (workspace_id, sender_address) WHERE sender_address IS NOT NULL"#,r#"CREATE INDEX idx_cotton_email_threads_record_kind ON cotton_email_threads (workspace_id, record_kind, last_at DESC) WHERE record_kind IS NOT NULL"#,// Version 127: the threads that name a merchant, for the dictation// vocabulary's read of merchants (`cotton-ffi` phone/voice_words.rs). It// read every live thread, wide rows and all, every 30 s inside the serving// Mac's hold — 10.5 s on the owner's 81k threads, of which 7.6k name a// merchant (12 Oct 2026). It carries every column that read asks, in the// order it asks them, so the read is answered from this index alone.r#"CREATE INDEX idx_cotton_email_threads_merchant ON cotton_email_threads (workspace_id, id, merchant, trashed_at) WHERE merchant IS NOT NULL AND trashed_at IS NULL"#,r#"CREATE INDEX idx_cotton_emails_thread_sent ON cotton_emails (thread_id, sent_at DESC)"#,r#"CREATE INDEX idx_cotton_emails_workspace ON cotton_emails (workspace_id)"#,r#"CREATE INDEX idx_cotton_emails_account ON cotton_emails (workspace_id, account) WHERE account IS NOT NULL"#,r#"CREATE INDEX idx_cotton_email_participants_email ON cotton_email_participants (workspace_id, email)"#,r#"CREATE INDEX idx_cotton_email_participants_thread ON cotton_email_participants (thread_id)"#,r#"CREATE INDEX idx_cotton_money_evidence_ref ON cotton_money_evidence (kind, ref_id)"#,r#"CREATE INDEX idx_cotton_money_evidence_transaction ON cotton_money_evidence (transaction_id)"#,r#"CREATE INDEX idx_cotton_money_evidence_workspace ON cotton_money_evidence (workspace_id)"#,r#"CREATE INDEX idx_cotton_money_statement_lines_statement ON cotton_money_statement_lines (statement_id, line_no)"#,r#"CREATE INDEX idx_cotton_money_statement_lines_workspace ON cotton_money_statement_lines (workspace_id)"#,r#"CREATE INDEX idx_cotton_money_statements_account ON cotton_money_statements (account_id, period_start) WHERE account_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_statements_pending ON cotton_money_statements (created_at) WHERE read_status = 'pending'"#,r#"CREATE INDEX idx_cotton_money_statements_workspace ON cotton_money_statements (workspace_id, period_start DESC)"#,r#"CREATE UNIQUE INDEX uq_cotton_money_evidence_line ON cotton_money_evidence (ref_id) WHERE kind = 'statement_line'"#,r#"CREATE UNIQUE INDEX uq_cotton_money_evidence_ref ON cotton_money_evidence (transaction_id, kind, ref_id) WHERE ref_id IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_money_statement_lines_fingerprint ON cotton_money_statement_lines (statement_id, fingerprint)"#,r#"CREATE INDEX idx_cotton_money_statement_lines_fingerprint ON cotton_money_statement_lines (fingerprint)"#, MOODS_LOCAL_DAY_INDEX, MOODS_AT_INDEX, SESSION_MESSAGES_ADDRESSED_INDEX, SESSION_MESSAGES_PROJECT_INDEX, AGENT_ACCOUNTS_WORKSPACE_INDEX, DEVICE_SAMPLES_DEVICE_INDEX, ACCOUNT_USAGE_SAMPLES_ACCOUNT_INDEX, REPO_PULLS_REPO_INDEX, REPO_ISSUES_REPO_INDEX, REPO_COMMENTS_TARGET_INDEX, REPO_COMMITS_REPO_INDEX, REPO_BUNDLES_REPO_INDEX, REPO_CLONES_REPO_INDEX, REPO_RELEASES_REPO_INDEX, REPO_RULES_REPO_INDEX, REPO_LABELS_REPO_INDEX, REPO_RUNNERS_WORKSPACE_INDEX, REPO_RUNS_REPO_INDEX, REPO_RUNS_SHA_INDEX, REPO_JOBS_RUN_INDEX, REPO_JOBS_RUN_ID_INDEX, REPO_JOBS_QUEUE_INDEX, REPO_VARS_REPO_INDEX, MACHINE_RUNNERS_DEVICE_INDEX, CODE_CREDENTIALS_WORKSPACE_INDEX,r#"CREATE UNIQUE INDEX uq_cotton_media_faces_natural ON cotton_media_faces (workspace_id, record_kind, record_id, source, source_id)"#,r#"CREATE INDEX idx_cotton_media_faces_record ON cotton_media_faces (workspace_id, record_id)"#,r#"CREATE INDEX idx_cotton_media_faces_person ON cotton_media_faces (workspace_id, person_id) WHERE person_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_media_faces_cluster ON cotton_media_faces (workspace_id, cluster_id) WHERE cluster_id IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_media_duplicates_pair ON cotton_media_duplicates (workspace_id, keep_id, copy_id)"#,r#"CREATE INDEX idx_cotton_media_duplicates_open ON cotton_media_duplicates (workspace_id, keep_id) WHERE state = 'open'"#,r#"CREATE INDEX idx_cotton_media_duplicates_copy ON cotton_media_duplicates (workspace_id, copy_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_person_suggestions_pair ON cotton_person_suggestions (workspace_id, person_id, candidate_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_person_suggestions_contact ON cotton_person_suggestions (workspace_id, contact_id, candidate_id) WHERE contact_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_person_suggestions_open ON cotton_person_suggestions (workspace_id, person_id) WHERE state = 'open'"#,r#"CREATE INDEX idx_cotton_person_suggestions_candidate ON cotton_person_suggestions (workspace_id, candidate_id)"#, SECRETS_SERVICE_INDEX, SECRETS_SERVICE_NAME_INDEX, SECRETS_LIVE_INDEX, VAULT_KEYS_VERSION_INDEX, SECRET_PLACEMENTS_DEVICE_INDEX, SECRET_PLACEMENTS_SECRET_INDEX,r#"CREATE INDEX idx_cotton_assistant_runs_state ON cotton_assistant_runs (workspace_id, state, queued_at)"#,r#"CREATE INDEX idx_cotton_assistant_runs_source ON cotton_assistant_runs (source_kind, source_id)"#,r#"CREATE INDEX idx_cotton_assistant_runs_note ON cotton_assistant_runs (result_note_id)"#,r#"CREATE INDEX idx_cotton_blocked_senders_address ON cotton_blocked_senders (workspace_id, address)"#,r#"CREATE INDEX idx_cotton_call_log_started ON cotton_call_log (workspace_id, started_at DESC)"#,r#"CREATE INDEX idx_cotton_call_log_person ON cotton_call_log (person_id)"#,r#"CREATE INDEX idx_cotton_call_log_contact ON cotton_call_log (contact_id)"#,r#"CREATE INDEX idx_cotton_msg_threads_contact ON cotton_msg_threads (contact_id)"#,r#"CREATE INDEX idx_cotton_msg_threads_workspace_recent ON cotton_msg_threads (workspace_id, last_message_at DESC)"#,r#"CREATE UNIQUE INDEX uq_cotton_msg_threads_dm ON cotton_msg_threads (workspace_id, contact_id) WHERE kind = 'dm'"#,r#"CREATE UNIQUE INDEX uq_cotton_msg_threads_group_key ON cotton_msg_threads (workspace_id, external_key) WHERE external_key IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_thread_participants_contact ON cotton_msg_thread_participants (contact_id)"#,r#"CREATE INDEX idx_cotton_msg_thread_participants_workspace ON cotton_msg_thread_participants (workspace_id)"#,r#"CREATE INDEX idx_cotton_msg_thread_participants_thread_label ON cotton_msg_thread_participants (thread_id, display_name)"#,r#"CREATE INDEX idx_cotton_msg_thread_participants_thread_contact ON cotton_msg_thread_participants (thread_id, contact_id)"#,r#"CREATE INDEX idx_cotton_msg_threads_pinned ON cotton_msg_threads (workspace_id, pinned_at) WHERE pinned_at IS NOT NULL"#,r#"CREATE INDEX idx_cotton_inbox_items_workspace ON cotton_inbox_items (workspace_id, route_status)"#,r#"CREATE INDEX idx_cotton_inbox_items_said ON cotton_inbox_items (said_table, said_record_id) WHERE said_table IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_notes_journal_day ON cotton_notes (workspace_id, journal_date, COALESCE(project_id, '')) WHERE kind = 'journal'"#,r#"CREATE UNIQUE INDEX uq_cotton_money_accounts_identity ON cotton_money_accounts (workspace_id, institution, number_mask) WHERE (institution IS NOT NULL) AND (number_mask IS NOT NULL)"#,r#"CREATE INDEX idx_cotton_documents_pipeline ON cotton_documents (status, status_changed_at) WHERE status IN ('processing', 'summarizing')"#,r#"CREATE INDEX idx_cotton_documents_type ON cotton_documents (workspace_id, doc_type)"#,r#"CREATE INDEX idx_cotton_documents_workspace_date ON cotton_documents (workspace_id, document_date DESC, created_at DESC)"#,r#"CREATE INDEX idx_cotton_money_accounts_person ON cotton_money_accounts (counterparty_person_id) WHERE counterparty_person_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_accounts_workspace ON cotton_money_accounts (workspace_id)"#,r#"CREATE INDEX idx_cotton_money_transactions_due ON cotton_money_transactions (due_date) WHERE due_date IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_account ON cotton_money_transactions (account_id) WHERE account_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_expected ON cotton_money_transactions (workspace_id,occurred_on,id,due_date,currency,direction,amount_minor,trashed_at) WHERE status='expected'"#,r#"CREATE INDEX idx_cotton_money_transactions_person ON cotton_money_transactions (counterparty_person_id) WHERE counterparty_person_id IS NOT NULL"#,// Owed's cut and heads (schema 146): every row naming a person, read off// this index alone, never the table (`read_db::MONEY_OWED_INDEX`).r#"CREATE INDEX idx_cotton_money_transactions_owed ON cotton_money_transactions (workspace_id,status,trashed_at,counterparty_person_id,occurred_on DESC,updated_at DESC,id,direction,amount_minor,currency,description) WHERE counterparty_person_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_settles ON cotton_money_transactions (settles_transaction_id) WHERE settles_transaction_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_money_transactions_workspace ON cotton_money_transactions (workspace_id)"#,r#"CREATE INDEX idx_cotton_money_transactions_workspace_date ON cotton_money_transactions (workspace_id, occurred_on DESC)"#,r#"CREATE UNIQUE INDEX uq_cotton_money_accounts_default ON cotton_money_accounts (workspace_id) WHERE is_default = 1"#,r#"CREATE UNIQUE INDEX uq_cotton_money_transactions_external_hash ON cotton_money_transactions (workspace_id, external_hash) WHERE external_hash IS NOT NULL"#, FEEDBACK_OPEN_INDEX, FEEDBACK_PARENT_INDEX, FEEDBACK_CAPTURE_INDEX, FEEDBACK_PERSON_INDEX, FEEDBACK_SAME_AS_INDEX, LINKS_FROM_INDEX, LINKS_TO_INDEX, LINKS_WORKSPACE_INDEX, LINKS_ENDS_INDEX,r#"CREATE INDEX idx_cotton_events_series ON cotton_events (series_id) WHERE series_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_events_trashed ON cotton_events (trashed_at) WHERE trashed_at IS NOT NULL"#,// Version 74: an invite's iCalendar UID — the one name both calendar doors// (Google's API and CalDAV) give the same event, so a reader matches on it// before its own id; an occurrence is the series UID plus original_starts_at.r#"CREATE INDEX idx_cotton_events_ical_uid ON cotton_events (ical_uid, original_starts_at) WHERE ical_uid IS NOT NULL"#,r#"CREATE INDEX idx_cotton_emails_gmail_id ON cotton_emails (workspace_id, gmail_id)"#,r#"CREATE INDEX idx_cotton_emails_from ON cotton_emails (workspace_id, from_email)"#,r#"CREATE INDEX idx_cotton_emails_pending ON cotton_emails (workspace_id, sync_state) WHERE sync_state = 'pending'"#,// Version 112: the mail list's counts, asked of indexes rather than of the// emails' rows (10.7 s and 7.5 s holds on the owner's 68k emails, 11 Oct// 2026). A connection's "N emails" counts its account's live mail through// the folded account the query names; a thread's "has an email in this// folder (starred / unread)" is one probe by thread. Both carry every// column their query tests, so each is answered from the index alone.r#"CREATE INDEX idx_cotton_emails_account_live ON cotton_emails (workspace_id, lower(coalesce(account, gmail_account)), trashed_at)"#,// Schema 153 (SENDERS INDEX, 24 Nov 2026; agreed with app-inventory): each mail's sender, as Comms// groups them (`lower(trim(from_email))`, word for word), with what a sender's tally reads. Comms' Senders tab// (cotton-ffi chat_senders.rs `mail_tallies`, chat_mail.rs `sender_groups_in`), a sender's page and Delete// everything (`senders::mail_where`, `= ?` / `LIKE '%@domain'`) read it alone, never the rows: a mail row is mostly// its body, so a pass over every row read ~400 MB on an account of 100,000 and the tab was cut off at 20 s// (emulator-5618). `from_email` itself last: SQLite 3.51 answers the sender expression in a SELECT list from the// index only when the column it is made of is there too. About 130 bytes a mail.// Schema 157 (MAIL PREDICATE phase 2): with `id`, which a cut's cover reads (its `except`, and the mail's landing// in `_mail_landed`), so the predicate with cuts still reads the index alone; a moved copy makes it in the// background (`index_later`) and drops the 153 index once it holds it.r#"CREATE INDEX IF NOT EXISTS idx_cotton_emails_sender_id ON cotton_emails (workspace_id, lower(trim(from_email)), sent_at, from_name, trashed_at, from_email, id)"#,r#"CREATE INDEX idx_cotton_emails_thread_live ON cotton_emails (thread_id, trashed_at, in_inbox, starred, unread)"#,// Schema 155 (POST AT SIZE, 26 Nov 2026; the coordinator's go): three partial indexes, so Post's// first open after new mail or a start never reads every mail's body at his size (110,000 mails). Each holds only// the mail its WHERE names, word for word as Post asks (cotton-ffi chat_mail_post_cuts.rs `inbox`, `archived`;// chat_mail_post.rs `files`):// - the Inbox by sender, with what an Archive row's cover reads (sent_at, created_at, id) and the conversation:// Home's tallies, a sender's Inbox count, and the conversations an Archive row covers (670 ms to 50 ms);// - mail archived by its own flag, by conversation: the Archived list (a sparse one read all 80,000);// - mail with attachments, newest first: Files and search's files (a mailbox with few read every row).// The columns each WHERE names are in the index too: SQLite reads a partial index alone only when they are.// Additive: indexes alone, IF NOT EXISTS.r#"CREATE INDEX IF NOT EXISTS idx_cotton_emails_inbox ON cotton_emails (workspace_id, lower(trim(from_email)), sent_at, created_at, id, thread_id, from_email, trashed_at, archived_at, in_inbox) WHERE trashed_at IS NULL AND archived_at IS NULL AND coalesce(in_inbox, 1) <> 0"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_emails_archived ON cotton_emails (thread_id) WHERE trashed_at IS NULL AND (archived_at IS NOT NULL OR in_inbox = 0)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_emails_files ON cotton_emails (workspace_id, sent_at, id) WHERE trashed_at IS NULL AND attachments IS NOT NULL AND attachments <> '' AND attachments <> '[]'"#, MEMORIES_SLUG_INDEX, MEMORIES_SOURCE_EXTERNAL_INDEX, MEMORIES_SUPERSEDED_BY_INDEX, MEMORIES_UNREVIEWED_INDEX,r#"CREATE INDEX idx_cotton_msg_contacts_auth_user ON cotton_msg_contacts (auth_user_id) WHERE auth_user_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_contacts_workspace ON cotton_msg_contacts (workspace_id)"#,r#"CREATE INDEX idx_cotton_msg_messages_thread_sent ON cotton_msg_messages (thread_id, sent_at DESC)"#,// Schema 150 (chat-search, 21 Nov 2026): a message that disappears names// the moment it goes (`meta.cotton.expiresAt`), and the copy finds the// ones due without reading the rest; a chat's timer is its newest timer// line (`meta.cotton.timer`).r#"CREATE INDEX idx_cotton_msg_messages_expires ON cotton_msg_messages (json_extract(meta, '$.cotton.expiresAt')) WHERE json_extract(meta, '$.cotton.expiresAt') IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_timer ON cotton_msg_messages (thread_id, sent_at DESC) WHERE json_extract(meta, '$.cotton.timer') IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_unread ON cotton_msg_messages (workspace_id, thread_id) WHERE read_at IS NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_unresolved_reply ON cotton_msg_messages (thread_id, reply_to_external_id) WHERE (reply_to_external_id IS NOT NULL) AND (reply_to_id IS NULL)"#,r#"CREATE UNIQUE INDEX uq_cotton_msg_messages_external ON cotton_msg_messages (thread_id, channel, external_id) WHERE external_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_channel_external ON cotton_msg_messages (workspace_id, channel, external_id) WHERE external_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_sender_participant ON cotton_msg_messages (sender_participant_id)"#,r#"CREATE INDEX idx_cotton_msg_messages_thread_seq ON cotton_msg_messages (thread_id, seq)"#,// Version 102: which channels a thread holds, read by skipping from one// channel to the next rather than by walking the thread's messages// (`channels_by_thread` in cotton-tools; 1.68M steps for one page before).r#"CREATE INDEX idx_cotton_msg_messages_thread_channel ON cotton_msg_messages (thread_id, channel)"#,// Version 106: the live messages a linked source brought, by the account// it read them from (`meta.source.account`), so a connection's "N messages"// counts its account's rows, never the table (10.6 s on the owner's file).r#"CREATE INDEX idx_cotton_msg_messages_source_account ON cotton_msg_messages (workspace_id, channel, json_extract(meta, '$.source.account')) WHERE deleted_at IS NULL AND hidden_at IS NULL AND json_extract(meta, '$.source.account') IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_starred ON cotton_msg_messages (workspace_id, starred_at) WHERE starred_at IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_messages_thread_created ON cotton_msg_messages (thread_id, created_at)"#, MSG_OUTBOX_INDEX, COMMENTS_OPEN_INDEX, COMMENTS_PARENT_INDEX, COMMENTS_RECORD_INDEX,r#"CREATE INDEX idx_cotton_photos_taken ON cotton_photos (workspace_id, taken_at DESC)"#,r#"CREATE INDEX idx_cotton_videos_taken ON cotton_videos (workspace_id, taken_at DESC)"#,r#"CREATE INDEX idx_cotton_photos_review ON cotton_photos (workspace_id, review_at) WHERE review_note IS NOT NULL"#,r#"CREATE INDEX idx_cotton_videos_review ON cotton_videos (workspace_id, review_at) WHERE review_note IS NOT NULL"#,r#"CREATE INDEX idx_cotton_photos_undescribed ON cotton_photos (workspace_id, taken_at DESC) WHERE summary IS NULL"#,r#"CREATE INDEX idx_cotton_videos_undescribed ON cotton_videos (workspace_id, taken_at DESC) WHERE summary IS NULL"#,r#"CREATE INDEX idx_cotton_photos_place ON cotton_photos (workspace_id, place_city)"#,r#"CREATE INDEX idx_cotton_videos_place ON cotton_videos (workspace_id, place_city)"#,r#"CREATE INDEX idx_cotton_photos_favourite ON cotton_photos (workspace_id, taken_at DESC) WHERE favourite = 1"#,r#"CREATE INDEX idx_cotton_videos_favourite ON cotton_videos (workspace_id, taken_at DESC) WHERE favourite = 1"#,r#"CREATE INDEX idx_cotton_photos_phash ON cotton_photos (workspace_id, phash) WHERE phash IS NOT NULL"#,r#"CREATE INDEX idx_cotton_videos_phash ON cotton_videos (workspace_id, phash) WHERE phash IS NOT NULL"#,r#"CREATE INDEX idx_cotton_photos_utility ON cotton_photos (workspace_id, taken_at DESC) WHERE is_utility = 1"#,r#"CREATE INDEX idx_cotton_media_faces_suggested ON cotton_media_faces (workspace_id, suggested_person_id) WHERE suggested_person_id IS NOT NULL"#,r#"CREATE UNIQUE INDEX uq_cotton_media_sightings_natural ON cotton_media_sightings (workspace_id, record_kind, record_id, source, ifnull(source_id, ''))"#,r#"CREATE INDEX idx_cotton_media_sightings_record ON cotton_media_sightings (workspace_id, record_id)"#,r#"CREATE INDEX idx_cotton_media_sightings_thread ON cotton_media_sightings (workspace_id, thread_id) WHERE thread_id IS NOT NULL"#,r#"CREATE INDEX idx_cotton_media_sightings_source ON cotton_media_sightings (workspace_id, source, source_id)"#,r#"CREATE INDEX idx_cotton_media_albums_open ON cotton_media_albums (workspace_id, starts_at DESC) WHERE state = 'open'"#,r#"CREATE INDEX idx_cotton_media_albums_time ON cotton_media_albums (workspace_id, starts_at DESC)"#,r#"CREATE UNIQUE INDEX uq_cotton_media_album_items_member ON cotton_media_album_items (album_id, record_id)"#,r#"CREATE INDEX idx_cotton_media_album_items_record ON cotton_media_album_items (workspace_id, record_id)"#, PROJECT_LINKS_RECORD_INDEX, PROJECT_LINKS_WORKSPACE_INDEX, PROJECT_LINKS_ARRANGED_INDEX,r#"CREATE INDEX idx_cotton_people_workspace ON cotton_people (workspace_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_people_device_contact ON cotton_people (workspace_id, device_contact_id) WHERE device_contact_id IS NOT NULL"#,// Version 78: the pass that filled a person's city from their zone — Home's// Done for you lists the newest passes, and a stamped person is never filled again.r#"CREATE INDEX idx_cotton_people_city_filled ON cotton_people (workspace_id, city_filled_at) WHERE city_filled_at IS NOT NULL"#,r#"CREATE INDEX idx_cotton_memory_projects_origin ON cotton_memory_projects (origin_handle) WHERE origin_handle IS NOT NULL"#, PROJECT_LINKS_ORIGIN_INDEX,r#"CREATE INDEX idx_cotton_notes_origin ON cotton_notes (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_documents_origin ON cotton_documents (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_media_albums_origin ON cotton_media_albums (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_media_album_items_origin ON cotton_media_album_items (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_photos_origin ON cotton_photos (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_videos_origin ON cotton_videos (origin_handle) WHERE origin_handle IS NOT NULL"#,r#"CREATE INDEX idx_cotton_msg_receipts_thread ON cotton_msg_receipts (thread_id)"#,r#"CREATE INDEX idx_cotton_msg_receipts_workspace ON cotton_msg_receipts (workspace_id)"#,r#"CREATE INDEX idx_cotton_msg_contact_handles_contact ON cotton_msg_contact_handles (contact_id)"#,r#"CREATE INDEX idx_cotton_msg_contact_handles_workspace ON cotton_msg_contact_handles (workspace_id)"#, TOMBSTONES_AUTHOR_INDEX, TOMBSTONES_HELD_INDEX, AUTHOR_INDEX_COTTON_AI_ACCESS, AUTHOR_INDEX_COTTON_ALARMS, AUTHOR_INDEX_COTTON_ASSISTANT_RUNS, AUTHOR_INDEX_COTTON_BLOCKED_SENDERS, AUTHOR_INDEX_COTTON_CALL_LOG, AUTHOR_INDEX_COTTON_COLLECTIONS, AUTHOR_INDEX_COTTON_COMMENTS, AUTHOR_INDEX_COTTON_DICTATIONS, AUTHOR_INDEX_COTTON_DOCUMENT_PAGES, AUTHOR_INDEX_COTTON_DOCUMENTS, AUTHOR_INDEX_COTTON_EMAIL_PARTICIPANTS, AUTHOR_INDEX_COTTON_EMAIL_SENDERS, AUTHOR_INDEX_COTTON_EMAIL_THREADS, AUTHOR_INDEX_COTTON_EMAILS, AUTHOR_INDEX_COTTON_EVENT_ATTENDEES, AUTHOR_INDEX_COTTON_EVENTS, AUTHOR_INDEX_COTTON_FEEDBACK, AUTHOR_INDEX_COTTON_GOALS, AUTHOR_INDEX_COTTON_GOOGLE_ACCOUNTS, AUTHOR_INDEX_COTTON_HOME_ARRANGEMENT, AUTHOR_INDEX_COTTON_INBOX_ITEMS, AUTHOR_INDEX_COTTON_LINKS, AUTHOR_INDEX_COTTON_LOCATIONS, AUTHOR_INDEX_COTTON_MCP_AUDIT, AUTHOR_INDEX_COTTON_MCP_TOKENS, AUTHOR_INDEX_COTTON_MEDIA_ALBUM_ITEMS, AUTHOR_INDEX_COTTON_MEDIA_ALBUMS, AUTHOR_INDEX_COTTON_MEDIA_DUPLICATES, AUTHOR_INDEX_COTTON_MEDIA_FACES, AUTHOR_INDEX_COTTON_MEDIA_SIGHTINGS, AUTHOR_INDEX_COTTON_MEETING_UTTERANCES, AUTHOR_INDEX_COTTON_MEETINGS, AUTHOR_INDEX_COTTON_MEMORIES, AUTHOR_INDEX_COTTON_MEMORY_PROJECTS, AUTHOR_INDEX_COTTON_MONEY_ACCOUNTS, AUTHOR_INDEX_COTTON_MONEY_EVIDENCE, AUTHOR_INDEX_COTTON_MONEY_STATEMENT_LINES, AUTHOR_INDEX_COTTON_MONEY_STATEMENTS, AUTHOR_INDEX_COTTON_MONEY_TRANSACTIONS, AUTHOR_INDEX_COTTON_MOODS, AUTHOR_INDEX_COTTON_MSG_CONTACT_HANDLES, AUTHOR_INDEX_COTTON_MSG_CONTACTS, AUTHOR_INDEX_COTTON_MSG_MESSAGES, AUTHOR_INDEX_COTTON_MSG_OWNER_SETTINGS, AUTHOR_INDEX_COTTON_MSG_REACTIONS, AUTHOR_INDEX_COTTON_MSG_RECEIPTS, AUTHOR_INDEX_COTTON_STORIES, AUTHOR_INDEX_COTTON_MSG_THREAD_PARTICIPANTS, AUTHOR_INDEX_COTTON_MSG_THREADS, AUTHOR_INDEX_COTTON_NEWS_EDITIONS, AUTHOR_INDEX_COTTON_NEWS_SEEN, AUTHOR_INDEX_COTTON_NEWS_SETTINGS, AUTHOR_INDEX_COTTON_NEWS_STORIES, AUTHOR_INDEX_COTTON_NEWS_TOPICS, AUTHOR_INDEX_COTTON_NOTES, AUTHOR_INDEX_COTTON_PAGES, AUTHOR_INDEX_COTTON_PEOPLE, AUTHOR_INDEX_COTTON_PERSON_NOTES, AUTHOR_INDEX_COTTON_PERSON_SUGGESTIONS, AUTHOR_INDEX_COTTON_PHOTOS, AUTHOR_INDEX_COTTON_PROJECT_LINKS, AUTHOR_INDEX_COTTON_PROMPTS, AUTHOR_INDEX_COTTON_SCREENPLAY_CHARACTERS, AUTHOR_INDEX_COTTON_SCREENPLAY_DOCUMENTS, AUTHOR_INDEX_COTTON_SCREENPLAY_DRAFT_SCENES, AUTHOR_INDEX_COTTON_SCREENPLAY_DRAFTS, AUTHOR_INDEX_COTTON_SCREENPLAY_SCENES, AUTHOR_INDEX_COTTON_SCREENPLAYS, AUTHOR_INDEX_COTTON_SECRET_PLACEMENTS, AUTHOR_INDEX_COTTON_PLACEMENT_PROPOSALS, AUTHOR_INDEX_COTTON_SECRETS, AUTHOR_INDEX_COTTON_SESSION_MESSAGES, AUTHOR_INDEX_COTTON_SESSIONS, AUTHOR_INDEX_COTTON_TODO_RECURRENCES, AUTHOR_INDEX_COTTON_TODOS, AUTHOR_INDEX_COTTON_VAULT_KEYS, AUTHOR_INDEX_COTTON_VAULT_STATE, AUTHOR_INDEX_COTTON_VIDEOS, AUTHOR_INDEX_COTTON_VOICE_VOCABULARY, AUTHOR_INDEX_COTTON_WORKSPACES, AUTHOR_INDEX_COTTON_DEVICES, AUTHOR_INDEX_COTTON_OAUTH_CLIENTS, AUTHOR_INDEX_COTTON_OAUTH_GRANTS, DEVICES_WORKSPACE_INDEX, DEVICES_DEVICE_INDEX, OAUTH_GRANTS_WORKSPACE_INDEX, AUTHOR_INDEX_COTTON_AGENT_ACCOUNTS, AUTHOR_INDEX_COTTON_DEVICE_SAMPLES, AUTHOR_INDEX_COTTON_ACCOUNT_USAGE_SAMPLES, AUTHOR_INDEX_COTTON_REPOS, AUTHOR_INDEX_COTTON_REPO_PULLS, AUTHOR_INDEX_COTTON_REPO_ISSUES, AUTHOR_INDEX_COTTON_REPO_COMMENTS, AUTHOR_INDEX_COTTON_REPO_COMMITS, AUTHOR_INDEX_COTTON_REPO_BUNDLES, AUTHOR_INDEX_COTTON_REPO_CLONES, AUTHOR_INDEX_COTTON_REPO_RELEASES, AUTHOR_INDEX_COTTON_REPO_RULES, AUTHOR_INDEX_COTTON_REPO_LABELS, AUTHOR_INDEX_COTTON_REPO_RUNNERS, AUTHOR_INDEX_COTTON_REPO_RUNS, AUTHOR_INDEX_COTTON_REPO_JOBS, AUTHOR_INDEX_COTTON_REPO_VARS, AUTHOR_INDEX_COTTON_MACHINE_RUNNERS, AUTHOR_INDEX_COTTON_CODE_CREDENTIALS, AUTHOR_INDEX_COTTON_SESSION_TASKS, SESSION_TASKS_SESSION_INDEX, AUTHOR_INDEX_COTTON_NOTE_ATTACHMENTS, NOTE_ATTACHMENTS_NOTE_INDEX, AUTHOR_INDEX_COTTON_DEV_JOBS, DEV_JOBS_QUEUE_INDEX, AUTHOR_INDEX_COTTON_REPO_MERGE_QUEUE, MERGE_QUEUE_REPO_INDEX, AUTHOR_INDEX_COTTON_THOUGHT_ATTACHMENTS, THOUGHT_ATTACHMENTS_THOUGHT_INDEX, AUTHOR_INDEX_COTTON_TABLE_DEFINITIONS, AUTHOR_INDEX_COTTON_TOOL_DEFINITIONS, TOOLKITS_POSITION_INDEX, AUTHOR_INDEX_COTTON_TOOLKITS, AUTHOR_INDEX_COTTON_BOARD_DEFINITIONS, AUTHOR_INDEX_COTTON_THEME_DEFINITIONS, AUTHOR_INDEX_COTTON_RECORDS, RECORDS_TABLE_INDEX, AUTHOR_INDEX_COTTON_CHANGES, CHANGES_RECORD_INDEX, SESSIONS_CONVERSATION_INDEX, SESSIONS_PARENT_INDEX, AUTHOR_INDEX_COTTON_MEDIA_HOLDINGS, MEDIA_HOLDINGS_OBJECT_INDEX, STORAGE_RULES_AUTHOR_INDEX, MEDIA_HOLDINGS_DEVICE_INDEX, MEDIA_HOLDINGS_LIVE_INDEX,// v42 — `decision`. AUTHOR_INDEX_COTTON_DECISIONS, WRITES_AUTHOR_INDEX, WRITES_OWNERS_INDEX, WRITES_HELD_INDEX, WRITES_HLC_INDEX, TOMBSTONES_HLC_INDEX, AUTHOR_INDEX_COTTON_AUTHORS, AUTHORS_MINTED_INDEX, AUTHOR_INDEX_COTTON_REVOCATIONS, REVOCATIONS_SUBJECT_INDEX, REVOCATIONS_OF_SUBJECT_INDEX, AUTHOR_INDEX_COTTON_SERVING_MACHINE, SERVING_MACHINE_EPOCH_INDEX, AUTHOR_INDEX_COTTON_VAULT_RETIRED_KEYS, VAULT_RETIRED_KEYS_VERSION_INDEX, AUTHOR_INDEX_COTTON_MEDIA_ERASURES, MEDIA_ERASURES_KEY_INDEX, AUTHOR_INDEX_COTTON_UNDOS, UNDOS_CHANGE_INDEX, AUTHOR_INDEX_COTTON_GRANT_ROTATIONS, GRANT_ROTATIONS_GRANT_INDEX, AUTHOR_INDEX_COTTON_DATABASES, AUTHOR_INDEX_COTTON_DATABASE_DEPARTURES, DATABASE_DEPARTURES_DATABASE_INDEX, AUTHOR_INDEX_COTTON_PERSON_KEYS, AUTHOR_INDEX_COTTON_ADMISSIONS, ADMISSIONS_PERSON_INDEX, MEMBER_PERSON_CLAIMS_INDEX, AUTHOR_INDEX_COTTON_DEVICE_STATEMENTS, DEVICE_STATEMENTS_DEVICE_INDEX, DEVICE_STATEMENTS_PERSON_INDEX, AUTHOR_INDEX_COTTON_INVITES, AUTHOR_INDEX_COTTON_JOINED_PLACES, AUTHOR_INDEX_COTTON_IMPORTS, AUTHOR_INDEX_COTTON_CONNECTIONS,// v86 — `post`. POSTS_INDEX_1, POSTS_INDEX_2, AUTHOR_INDEX_COTTON_POSTS, AUTHOR_INDEX_COTTON_PERSON_HANDLES,r#"CREATE UNIQUE INDEX uq_cotton_person_handles_handle ON cotton_person_handles (workspace_id, kind, normalised)"#,r#"CREATE INDEX idx_cotton_person_handles_person ON cotton_person_handles (person_id)"#,// v109 — Me: a person's languages. AUTHOR_INDEX_COTTON_PERSON_LANGUAGES,r#"CREATE INDEX idx_cotton_person_languages_person ON cotton_person_languages (person_id)"#,// v114 — filing a chat: one row per (chat, database). AUTHOR_INDEX_COTTON_MSG_THREAD_FILINGS,r#"CREATE UNIQUE INDEX uq_cotton_msg_thread_filings_pair ON cotton_msg_thread_filings (workspace_id, thread_id, database_id)"#,r#"CREATE INDEX idx_cotton_msg_thread_filings_state ON cotton_msg_thread_filings (workspace_id, state)"#,// v118 — what a device keeps: one rule per (device, kind, target). AUTHOR_INDEX_COTTON_DEVICE_KEEP, AUTHOR_INDEX_COTTON_GROUPS, AUTHOR_INDEX_COTTON_GROUP_MEMBERS, AUTHOR_INDEX_COTTON_TOOL_ASSETS, AUTHOR_INDEX_COTTON_AUTOMATION_RUNS,r#"CREATE UNIQUE INDEX uq_cotton_device_keep_rule ON cotton_device_keep (workspace_id, device_id, kind, target)"#,// 137 — a group's members and a tool's pictures, one row each.r#"CREATE UNIQUE INDEX uq_cotton_group_members_member ON cotton_group_members (group_id, record_id)"#,r#"CREATE INDEX idx_cotton_group_members_record ON cotton_group_members (workspace_id, record_id)"#,r#"CREATE UNIQUE INDEX uq_cotton_tool_assets_picture ON cotton_tool_assets (workspace_id, tool_id, name)"#,r#"CREATE INDEX idx_cotton_automation_runs_automation ON cotton_automation_runs (workspace_id, automation, started_at)"#,// v125 — a reader's own marks on a filed chat: one row per (database, chat). AUTHOR_INDEX_COTTON_MSG_THREAD_MARKS,r#"CREATE UNIQUE INDEX uq_cotton_msg_thread_marks_copy ON cotton_msg_thread_marks (workspace_id, database_id, thread_id)"#,// v126 — a phone heard a push: one row per (device, push), and the push's// receipts by push for the Mac that sent it. AUTHOR_INDEX_COTTON_PUSH_ACKS, AUTHOR_INDEX_COTTON_DEVICE_RELAY_KEYS, DEVICE_RELAY_KEYS_DEVICE_INDEX,// onlyyou rise — one audience row per record; the held set by value. AUTHOR_INDEX_COTTON_AUDIENCES,r#"CREATE UNIQUE INDEX uq_cotton_audiences_record ON cotton_audiences (workspace_id, record_table, record_id)"#,r#"CREATE INDEX idx_cotton_audiences_audience ON cotton_audiences (audience)"#,r#"CREATE UNIQUE INDEX uq_cotton_push_acks_device_push ON cotton_push_acks (workspace_id, device_id, push_id)"#,r#"CREATE INDEX IF NOT EXISTS idx_cotton_push_acks_push ON cotton_push_acks (push_id)"#,// v120 — the owner's outage record. AUTHOR_INDEX_COTTON_OUTAGES,r#"CREATE INDEX idx_cotton_outages_open ON cotton_outages (workspace_id, condition) WHERE ended_at IS NULL"#,r#"CREATE INDEX idx_cotton_outages_started ON cotton_outages (workspace_id, started_at DESC)"#,// gen-kind: schema-ddl-indexes FTS_TODOS_AI, FTS_TODOS_AD, FTS_EVENTS_AI, FTS_EVENTS_AD, FTS_NOTES_AI, FTS_NOTES_AD, FTS_LOCATIONS_AI, FTS_LOCATIONS_AD, FTS_MEETINGS_AI, FTS_MEETINGS_AD, FTS_PAGES_AI, FTS_PAGES_AD, FTS_DOCUMENT_PAGES_AI, FTS_DOCUMENT_PAGES_AD, FTS_PROMPTS_AI, FTS_PROMPTS_AD, FTS_EMAILS_AI, FTS_EMAILS_AD, FTS_MOODS_AI, FTS_MOODS_AD, FTS_SESSION_MESSAGES_AI, FTS_SESSION_MESSAGES_AD, FTS_TODOS_AU, FTS_EVENTS_AU, FTS_NOTES_AU, FTS_LOCATIONS_AU, FTS_MEETINGS_AU, FTS_PAGES_AU, FTS_DOCUMENT_PAGES_AU, FTS_PROMPTS_AU, FTS_EMAILS_AU, FTS_MAIL_AI, FTS_MAIL_AD, FTS_MAIL_AU, MAIL_LANDED_MADE, MAIL_LANDED_CHANGED, MAIL_LANDED_GONE, FTS_DOCUMENTS_AI, FTS_DOCUMENTS_AD, FTS_DOCUMENTS_AU, FTS_MOODS_AU, FTS_THOUGHTS_AI, FTS_THOUGHTS_AD, FTS_THOUGHTS_AU, FTS_SESSION_MESSAGES_AU, FTS_MEMORIES_AI, FTS_MEMORIES_AD, FTS_MEMORIES_AU, FTS_MESSAGES_AI, FTS_MESSAGES_AD, FTS_MESSAGES_AU, FTS_CHAT_AI, FTS_CHAT_AD, FTS_CHAT_AU, FTS_VIDEOS_AI, FTS_VIDEOS_AD, FTS_VIDEOS_AU, FTS_PHOTOS_AI, FTS_PHOTOS_AD, FTS_PHOTOS_AU, FTS_PEOPLE_AI, FTS_PEOPLE_AD, FTS_PEOPLE_AU, FTS_SECRETS_AI, FTS_SECRETS_AD, FTS_SECRETS_AU, FTS_REPO_PULLS_AI, FTS_REPO_PULLS_AD, FTS_REPO_PULLS_AU, FTS_REPO_ISSUES_AI, FTS_REPO_ISSUES_AD, FTS_REPO_ISSUES_AU,// v42 — `decision`. FTS_DECISIONS_AI, FTS_DECISIONS_AD, FTS_DECISIONS_AU,// v86 — `post`. FTS_POSTS_AI, FTS_POSTS_AD, FTS_POSTS_AU,// A statement line is evidence once it has booked a money row. Removing// it would make the bank movement disappear while leaving the money row.r#"CREATE TRIGGER cotton_money_statement_lines_no_delete_booked BEFORE DELETE ON cotton_money_statement_lines WHEN EXISTS (SELECT 1 FROM cotton_money_evidence AS e WHERE e.kind = 'statement_line' AND e.ref_id = OLD.id) BEGIN SELECT RAISE(ABORT, 'a booked statement line is never deleted'); END"#,r#"CREATE TRIGGER cotton_ai_jobs_safe_insert BEFORE INSERT ON cotton_ai_jobs WHEN EXISTS (SELECT 1 FROM json_tree(NEW.input) WHERE lower(replace(CAST(key AS TEXT),'-','_')) IN ('data','bytes','base64','image_bytes','audio_bytes','file_bytes','api_key','apikey','authorization','credential','credentials','password','secret','token','access_token','refresh_token','private_key') OR (type='text' AND (lower(value) LIKE 'data:%;base64,%' OR value LIKE 'sk-ant-%' OR value LIKE 'Bearer %' OR value LIKE '-----BEGIN %PRIVATE KEY%'))) BEGIN SELECT RAISE(ABORT,'ai_job_unsafe_input'); END"#,r#"CREATE TRIGGER cotton_ai_jobs_safe_update BEFORE UPDATE OF input ON cotton_ai_jobs WHEN EXISTS (SELECT 1 FROM json_tree(NEW.input) WHERE lower(replace(CAST(key AS TEXT),'-','_')) IN ('data','bytes','base64','image_bytes','audio_bytes','file_bytes','api_key','apikey','authorization','credential','credentials','password','secret','token','access_token','refresh_token','private_key') OR (type='text' AND (lower(value) LIKE 'data:%;base64,%' OR value LIKE 'sk-ant-%' OR value LIKE 'Bearer %' OR value LIKE '-----BEGIN %PRIVATE KEY%'))) BEGIN SELECT RAISE(ABORT,'ai_job_unsafe_input'); END"#,// gen-kind: schema-ddl-triggers];