//! `packages/core/__tests__/primitives.test.ts`, and what a pure crate could//! make of each of its cases.//!//! The discipline is the TypeScript's: the registry is EXPLICIT, not derived,//! so this is where it gets to disagree with the code. A kind added to a//! facility list without a registry decision fails here — and so does a//! registry claim no list backs. Every failure message names the seam to fix.//!//! # Where the port put each of the TypeScript's cases//!//! - The nine facility arrays are [`crate::constants`] enums here, so the//! comparison is the same one, spelled against `ALL`.//! - `EVERYTHING_KINDS` is `rules::search_everything`'s, so the case is the//! TypeScript's exactly: two Rust declarations of one decision, held equal.//! - The four cases that OPENED A MIGRATED DATABASE do not need one: the//! canonical v45 DDL is `cotton_store`'s generated `SCHEMA_DDL`, which is the//! text those `CREATE TABLE`s and triggers are issued from. Reading the CHECK//! out of it asks the same question of the same authority, and a pure crate//! opens no file.//! - `VERSIONED_TABLES` is `cotton_store::schema::versioned::VERSIONED_TABLES`//! now, so the case is two Rust declarations of one decision, held equal.//! - `AUTHORED_TABLES` and `SCOPE_SPECS` had a case each, both against the//! `sharing` module. That module is gone with the multi-person sharing data//! plane (the code is on the branch `archive/sharing-v1`), and with it the//! only second declaration either case could be held against. What survives//! here is the registry's own half: `shareable` is still a written decision//! per kind, and `matches_the_tables_the_schema_gave_an_origin_handle_//! exactly` still holds it against the columns the schema actually carries.use cotton_store::schema::fts::FTS_SOURCES;use cotton_store::schema::ddl::SCHEMA_DDL;use cotton_store::schema::table_specs::TABLE_SPECS;use cotton_store::schema::decl::Codec;usecrate::constants::{BinKind, CommentRecordKind, LinkKind, PrimitiveKind, ProjectLinkKind, RecordKind,RouteTargetKind, ShareableKind, SummaryKind, VersionRecordKind, GROUP_MEMBER_CAP, SHAREABLE_LINK_TABLES,};usecrate::rules::chunk::EMBED_SOURCES;usecrate::rules::search_everything::EVERYTHING_KINDS;usesuper::{ kinds_with, primitive, searchable_kinds, supporting_table, Facility, Membership, SearchLane, RETIRED_KINDS, RETIRED_TABLES, SUPPORTING_TABLES,};fn sorted(values: implIntoIterator<Item = String>) -> Vec<String> {letmut out: Vec<String> = values.into_iter().collect(); out.sort(); out}fn kind_strings(facility: Facility) -> Vec<String> { sorted( kinds_with(facility) .into_iter() .map(|kind| kind.as_str().to_string()), )}// The by-path reader of packages/core's VERSIONED_TABLES went with the package; the Rust list is the store's own.// ── the registry agrees with every facility's membership list ──────────────#[test]fn versioned_equals_version_record_kinds() { assert_eq!( kind_strings(Facility::Versioned), sorted(VersionRecordKind::ALL.iter().map(|k| k.to_string())),"PRIMITIVES kinds marked versioned must equal VERSION_RECORD_KINDS — decide in primitives.rs AND the list (plus its DB CHECK)" );}#[test]fn commentable_equals_comment_record_kinds() { assert_eq!( kind_strings(Facility::Commentable), sorted(CommentRecordKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn summarized_equals_summary_kinds() { assert_eq!( kind_strings(Facility::Summarized), sorted(SummaryKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn binnable_equals_bin_kinds() {// A news topic goes to the bin through the// shared path without being a primitive, so the registry can only answer// for the bin kinds that are: each of those is binnable, and nothing else is. assert_eq!( kind_strings(Facility::Binnable), sorted(BinKind::ALL .iter() .map(|k| k.to_string()) .filter(|k| PrimitiveKind::parse(k).is_some()), ), );}#[test]fn project_linkable_equals_project_link_kinds() { assert_eq!( kind_strings(Facility::ProjectLinkable), sorted(ProjectLinkKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn linkable_equals_link_kinds() { assert_eq!( kind_strings(Facility::Linkable), sorted(LinkKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn route_target_equals_route_target_kinds() { assert_eq!( kind_strings(Facility::RouteTarget), sorted(RouteTargetKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn addressable_equals_record_kinds() { assert_eq!( kind_strings(Facility::Addressable), sorted(RecordKind::ALL.iter().map(|k| k.to_string())), );}#[test]fn shareable_equals_shareable_kinds() { assert_eq!( kind_strings(Facility::Shareable), sorted(ShareableKind::ALL.iter().map(|k| k.to_string())), );}/// The one search-lane case.////// `rules::search_everything` declares `EVERYTHING_KINDS` as its own enum, the/// way `searchEverything.ts` does — the lane loop's order lives there and the/// registry's decision lives here, which is precisely the pair this test exists/// to hold together. A kind given a lane here and absent there is a section the/// one search surface never runs.////// RULE: The one search surface reaches every primitive with a search lane and/// nothing else.#[test]fn search_membership_equals_everything_kinds() { assert_eq!( sorted( searchable_kinds() .into_iter() .map(|kind| kind.as_str().to_string()) ), sorted( EVERYTHING_KINDS .iter() .map(|kind| kind.as_str().to_string()) ),"PRIMITIVES kinds with a search lane must equal EVERYTHING_KINDS (rules::search_everything)" );}// ── the registry agrees with the store ─────────────────────────────────────/// RULE: Every record kind in the master registry names a table that really exists in the database.#[test]fn every_primitives_table_is_a_real_synced_table() {for kind inPrimitiveKind::ALL {let table = primitive(kind).table; assert!( TABLE_SPECS.iter().any(|spec| spec.name == table),"{kind} names table {table}, which TABLE_SPECS does not know" ); }}/// RULE: Every table in a person's database either holds a record kind, states in writing what it supports, or is named retired with its rows kept (`RETIRED_TABLES`, owner 17 Nov 2026: the old screenplay tables); there is no silent state.#[test]fn primitive_tables_plus_supporting_tables_partition_table_specs_exactly() {let primitive_tables: Vec<&str> = PrimitiveKind::ALL .iter() .map(|kind| primitive(*kind).table) .collect();let supporting: Vec<&str> = SUPPORTING_TABLES.iter().map(|(name, _)| *name).collect();let unclaimed: Vec<&str> = TABLE_SPECS .iter() .map(|spec| spec.name) .filter(|table| { !primitive_tables.contains(table) && !supporting.contains(table) && !RETIRED_TABLES.contains(table) }) .collect(); assert_eq!( unclaimed,Vec::<&str>::new(),"every synced table either holds a primitive, says in SUPPORTING_TABLES what it supports, or is named in RETIRED_TABLES — there is no silent state" );for table in RETIRED_TABLES { assert!(TABLE_SPECS.iter().any(|spec| spec.name == *table), "RETIRED_TABLES names {table}, which storage no longer holds"); assert!(!primitive_tables.contains(table) && !supporting.contains(table), "{table} is retired and claimed"); }let ghosts: Vec<&str> = supporting .iter() .copied() .filter(|table| !TABLE_SPECS.iter().any(|spec| spec.name == *table)) .collect(); assert_eq!( ghosts,Vec::<&str>::new(),"SUPPORTING_TABLES names tables that no longer exist" );let both: Vec<&str> = supporting .iter() .copied() .filter(|table| primitive_tables.contains(table)) .collect(); assert_eq!( both,Vec::<&str>::new(),"a table cannot both hold a primitive and be a supporting table" );letmut seen: Vec<&str> = Vec::new();for table in &supporting { assert!(!seen.contains(table), "{table} listed twice"); seen.push(table); } assert_eq!( supporting_table("cotton_comments"),Some( SUPPORTING_TABLES .iter() .find(|(name, _)| *name == "cotton_comments") .expect("declared") .1 ) ); assert_eq!(supporting_table("cotton_todos"), None);}/// Child tables may carry an index of their own (document pages ride under the/// document kind) — only primitive tables are gated here.#[test]fn fts_member_kinds_are_exactly_the_fts_sources_tables() {let supporting: Vec<&str> = SUPPORTING_TABLES .iter() .map(|(name, _)| *name) .collect();let from_registry = sorted( kinds_with(Facility::Fts) .into_iter() .map(|kind| primitive(kind).table.to_string()) .collect::<Vec<_>>() .into_iter() .collect::<std::collections::BTreeSet<_>>(), );let from_store = sorted( FTS_SOURCES .iter() .map(|source| source.source) .filter(|table| !supporting.contains(table) && !RETIRED_TABLES.contains(table)) .map(|table| table.to_string()) .collect::<std::collections::BTreeSet<_>>(), ); assert_eq!( from_registry, from_store,"PRIMITIVES fts members must equal the primitive-held FTS_SOURCES tables (store schema/fts.ts)" );}/// Both directions, and the direction that bites is the second one: a source/// added to `EMBED_SOURCES` whose kind still carries a written refusal would/// send that kind's text to a provider the registry says it never sends.////// Compared by KIND rather than by table, because they do not line up —/// `document_page` reads a supporting table and its owner is `document`, which/// is why the source declares its kind.#[test]fn embedded_member_kinds_are_exactly_the_kinds_embed_sources_names() {let from_sources = sorted( EMBED_SOURCES .iter() .map(|source| source.kind.to_string()) .filter(|kind| !RETIRED_KINDS.contains(&kind.as_str())) .collect::<std::collections::BTreeSet<_>>(), ); assert_eq!( kind_strings(Facility::Embedded), from_sources,"PRIMITIVES embedded members must equal the kinds EMBED_SOURCES names" );}#[test]fn every_embed_source_reads_a_real_tables_real_text_columns() {let names: Vec<&str> = EMBED_SOURCES.iter().map(|source| source.source).collect();letmut unique = names.clone(); unique.sort_unstable(); unique.dedup(); assert_eq!( unique.len(), names.len(),"two sources sharing a name would share a partition" );for source in EMBED_SOURCES.iter() {let spec = TABLE_SPECS .iter() .find(|spec| spec.name == source.table) .unwrap_or_else(|| { panic!("{} names table {}, which TABLE_SPECS does not know", source.source, source.table ) });for column in source.columns {let codec = spec .columns .iter() .find(|(name, _)| name == column) .map(|(_, codec)| *codec); assert_eq!( codec,Some(Codec::Text),"{}: {}.{column} must be a text column to be chunked", source.source, source.table ); } }}/// RULE: Which record kinds keep an edit history is one decision: the registry and the database's own list say the same thing./// `cotton_notes` versions as note AND journal (the trigger's CASE); the store/// list carries the table once, under "note".#[test]fn versioned_kinds_are_exactly_the_stores_versioned_list() {letmut declared: Vec<String> = cotton_store::schema::versioned::VERSIONED_TABLES .iter() .filter(|entry| !RETIRED_TABLES.contains(&entry.table)) .map(|entry| entry.kind.to_string()) .collect(); assert!( declared.len() >= 8, // 15 until TABLE DROP 1 retired alarm, decision, goal, location, meeting and page"read only {} kinds out of the store's declaration — its shape moved", declared.len() );let registry = kind_strings(Facility::Versioned);if registry.iter().any(|k| k == "journal") && registry.iter().any(|k| k == "note") { declared.push("journal".to_string()); } assert_eq!( registry, sorted(declared),"PRIMITIVES versioned members must equal the store's VERSIONED list (schema/versions.ts) — one decision, two files" );}// ── the registry agrees with the FILE — the CHECKs a v45 database enforces ──/// The `CREATE TABLE` statement for one table, out of the canonical DDL.////// Both spellings, because the generated DDL carries both: a table whose name/// was ever renamed comes back from `sqlite_master` QUOTED/// (`CREATE TABLE "cotton_comments"`), and one that never was does not./// Matching only the bare form would have made this guard find nothing and say/// so — which it did, before the quoted form was allowed for.fn table_ddl(table: &str) -> &'static str { SCHEMA_DDL .iter() .find(|statement| { statement.starts_with(&format!("CREATE TABLE {table} (")) || statement.starts_with(&format!("CREATE TABLE \"{table}\" (")) }) .copied() .unwrap_or_else(|| panic!("{table} missing from SCHEMA_DDL"))}/// The `<column> IN (...)` vocabulary of one table, less the kinds only the/// retired tables' kept rows still name (`RETIRED_KINDS`): storage keeps its/// CHECK, and the registry has no such kind.fn check_kinds(sql: &str, table: &str, column: &str) -> Vec<String> {let pattern = regex::Regex::new(&format!(r"(?i){column}\s+IN\s+\(([^)]+)\)")) .expect("the reader's own pattern compiles");let caps = pattern .captures(sql) .unwrap_or_else(|| panic!("{table}: no {column} IN (...) CHECK found")); caps[1] .split(',') .map(|part| part.trim().trim_matches('\'').to_string()) .filter(|kind| !RETIRED_KINDS.contains(&kind.as_str())) .collect()}/// RULE: The kinds you can comment on are the same in the registry and in the database's own rule, so widening one alone cannot strand the other.#[test]fn cotton_comments_check_equals_the_registrys_commentable_kinds() { assert_eq!( kind_strings(Facility::Commentable), sorted(check_kinds( table_ddl("cotton_comments"),"cotton_comments","record_kind" )),"cotton_comments's record_kind CHECK must equal the registry's commentable kinds — widening either side alone strands the other" );}/// Exactly: `store` left the CHECK with the Stores tables (schema 105), so/// the vocabulary names no kind the registry does not link.#[test]fn cotton_project_links_check_equals_the_registrys_project_linkable_kinds() {let registry = kind_strings(Facility::ProjectLinkable); assert_eq!( sorted(registry), sorted(check_kinds( table_ddl("cotton_project_links"),"cotton_project_links","record_kind" )), );}#[test]fn cotton_links_from_and_to_checks_equal_the_registrys_linkable_kinds() {let sql = table_ddl("cotton_links"); assert_eq!( kind_strings(Facility::Linkable), sorted(check_kinds(sql, "cotton_links", "from_kind")), ); assert_eq!( kind_strings(Facility::Linkable), sorted(check_kinds(sql, "cotton_links", "to_kind")), );}#[test]fn the_statement_primitive_names_a_real_table_with_the_columns_the_spec_gave_it() {let spec = TABLE_SPECS .iter() .find(|spec| spec.name == "cotton_money_statements") .expect("cotton_money_statements is a synced table");for column in ["document_id", "account_id", "read_status", "balance_check"] { assert!( spec.columns.iter().any(|(name, _)| *name == column),"cotton_money_statements has no {column}" ); } assert_eq!( primitive(PrimitiveKind::Statement).table,"cotton_money_statements" );}/// RULE: A bank or card statement is not commentable, linkable, searchable or shareable; it is read, not filed./// Ten written "no"s in one entry — the registry's whole point is that each is a/// decision somebody made, so this asserts the SHAPE of that decision rather/// than restating the reasons.#[test]fn statement_stays_out_of_every_facility_list() {for facility in [Facility::Versioned,Facility::Commentable,Facility::Summarized,Facility::ProjectLinkable,Facility::Linkable,Facility::RouteTarget,Facility::Addressable,Facility::Shareable, ] { assert!( !kinds_with(facility).contains(&PrimitiveKind::Statement),"{facility}" ); } assert!(matches!( primitive(PrimitiveKind::Statement).search,SearchLane::No(_) ));}// ── exclusions carry their reasons ─────────────────────────────────────────/// RULE: When a record kind is left out of a capability, the registry carries a written reason for it rather than a blank or a to-do.#[test]fn every_no_is_written_prose_never_a_bare_flag_or_placeholder() {let placeholder = regex::Regex::new(r"\b(TODO|TBD|FIXME)\b").expect("compiles");for kind inPrimitiveKind::ALL {let spec = primitive(kind);letmut reasons: Vec<(&str, &str)> = Vec::new();for facility inFacility::ALL {ifletMembership::No(reason) = spec.facility(facility) { reasons.push((facility.as_str(), reason)); } }ifletSearchLane::No(reason) = spec.search { reasons.push(("search", reason)); }for (facility, reason) in reasons { assert!( reason.trim().len() >= 10,"{kind}.{facility}: an exclusion needs a real written reason, got {reason:?}" ); assert!( !placeholder.is_match(reason),"{kind}.{facility}: {reason:?}" ); } }}/// A retired KIND has no entry at all — not a `prompt_block` refusal, not a/// written one. "A facility gains an entry when the first kind refuses it, and/// loses every entry the day the facility itself goes"; a kind that is gone has/// nothing left to say no with.#[test]fn the_retired_prompt_library_leaves_nothing_behind() { assert!(PrimitiveKind::parse("prompt_block").is_none()); assert!(!PrimitiveKind::ALL .iter() .any(|kind| primitive(*kind).table == "cotton_prompt_blocks")); assert!(supporting_table("cotton_prompt_blocks").is_none());}/// RULE: A coding session's messages are addressed to that session deliberately, and are never filed into a project or linked to other records.#[test]fn a_session_message_is_addressed_never_filed() {let spec = primitive(PrimitiveKind::SessionMessage); assert_eq!(spec.table, "cotton_session_messages"); assert_eq!( spec.route_target,Membership::No("a session is chosen deliberately, by machine and account; nothing routes there on its own" ) ); assert!(!kinds_with(Facility::ProjectLinkable).contains(&PrimitiveKind::SessionMessage)); assert!(!kinds_with(Facility::Linkable).contains(&PrimitiveKind::SessionMessage));}/// RULE: Notes and journal entries are the only two record kinds that share one table; every other kind has a table to itself.#[test]fn note_and_journal_are_the_only_kinds_sharing_a_table() {for kind inPrimitiveKind::ALL {let table = primitive(kind).table;let sharing = sorted(PrimitiveKind::ALL .iter() .filter(|other| primitive(**other).table == table) .map(|other| other.as_str().to_string()) .collect::<Vec<_>>(), );if table == "cotton_notes" { assert_eq!(sharing, ["journal", "note"]); } else { assert_eq!(sharing.len(), 1, "{table} claimed by more than one kind"); } }}// ── shareable — what may leave this file into a scope ──────────────────────/// RULE: Only the record kinds expressly marked shareable may ever leave a person's own database, and every other kind carries the reason it does not./// A "yes" is a promise: a record of this kind may leave this file into a scope/// and land in somebody else's. Each kind not marked shareable carries the/// reason it does not.#[test]fn says_yes_to_the_six_kinds_a_person_shares_and_nothing_else() { assert_eq!( sorted(ShareableKind::ALL.iter().map(|kind| kind.to_string())), ["album", "document", "note", "photo", "project", "video"] );}/// A link row carries a MEMBERSHIP rather than a record, so it has no registry/// entry to mark — and it still has to travel, or the far side gets records/// with nothing holding them together.#[test]fn declares_the_join_tables_beside_the_list_because_they_are_not_kinds() { assert_eq!( sorted(SHAREABLE_LINK_TABLES.iter().map(|t| t.to_string())), ["cotton_media_album_items","cotton_note_attachments","cotton_project_links" ] );for table in SHAREABLE_LINK_TABLES { assert!( TABLE_SPECS.iter().any(|spec| spec.name == table),"{table} is not a synced table" ); assert!( !PrimitiveKind::ALL .iter() .any(|kind| primitive(*kind).table == table),"{table} is a kind's own table, so it belongs in SHAREABLE_KINDS" ); }}/// RULE: Exactly the tables whose records can travel to somebody else can record who wrote a row./// The column and the decision are one fact in two places. A kind marked/// shareable whose table cannot say who wrote a row would mirror a peer's/// record as the owner's own; a table carrying the column for a kind that/// refuses to travel is a column nothing will ever write.#[test]fn matches_the_tables_the_schema_gave_an_origin_handle_exactly() {let with_origin_handle = sorted( TABLE_SPECS .iter() .filter(|spec| { spec.columns .iter() .any(|(name, _)| *name == "origin_handle") }) .map(|spec| spec.name.to_string()), );let from_registry = sorted(ShareableKind::ALL .iter() .map(|kind| { primitive(PrimitiveKind::parse(kind.as_str()) .unwrap_or_else(|| panic!("{kind} is a primitive")), ) .table .to_string() }) .chain(SHAREABLE_LINK_TABLES.iter().map(|t| t.to_string())), ); assert_eq!(from_registry, with_origin_handle);}/// RULE: A note can be shared and a journal entry never can, even though both live in the same table./// `note` and `journal` are one table split on a column, and they answer this/// facility differently: a diary is not a document somebody hands over. The/// membership function does the filtering at the row.#[test]fn refuses_a_journal_page_although_a_note_travels_in_the_one_shared_table() { assert_eq!(primitive(PrimitiveKind::Note).shareable, Membership::Yes); assert_eq!( primitive(PrimitiveKind::Journal).table, primitive(PrimitiveKind::Note).table ); assert!(matches!( primitive(PrimitiveKind::Journal).shareable,Membership::No(_) )); assert!(ShareableKind::parse("journal").is_none());}#[test]fn keeps_a_conversation_out_because_a_chat_is_a_scope_rather_than_a_member_of_one() {for kind in [PrimitiveKind::Message, PrimitiveKind::Thread] { assert!( matches!(primitive(kind).shareable, Membership::No(_)),"{kind}" ); }}/// Declared in core so the relay's applier and the peer producer read one/// number — two ceilings is a group that is full on one side and not the other.#[test]fn group_member_cap_is_the_one_ceiling_on_a_groups_membership() { assert_eq!(GROUP_MEMBER_CAP, 256);}