// Every definition a database draws — its tables, its boards, the theme it// wears — as ONE answer of the core (`definitions.catalogue`,// `crates/cotton-ffi/src/phone/catalogue.rs`), asked once per database and// kept until a definitions row of that database moves.//// ONE DECODER OF THE DEFINITION FORMAT (architect, 14 Oct 2026): the core// reads, resolves and decodes the definitions; the app draws what it hands// over. A database draws the tables its own definition rows describe and no// other (tools are records only, 21 Oct 2026); a stored definition the core// cannot draw is said once in Feedback by the core, and every served row the// answer leaves out of its tables — a storage table with no face, a row the// core refused — comes named with why (`undrawn`), for the reader to log.//// This side carries the answer as JSON, because what a definition MEANS is// CottonUI's; it checks only the shape, so a core speaking another shape is// refused here, plainly and whole.importFoundationimport os/// One database's catalogue, as the core answered it.publicstructRawCatalogue: Sendable {/// Each table the database draws, as its JSON.publiclet tables: [Data]/// Each table's id, at the same index as `tables` ("" when the table names/// none) — so a reader that wants a few tables decodes only those.publiclet tableIDs: [String]/// Each table's page as the core resolved it (its parts and their/// order), by the table's id — the app draws this and derives no page.publiclet pages: [String: Data]/// What the core says of each table, by the table's id (`TableSaid`).publiclet said: [String: Data]/// Each board by id, as `definitions.board` answered one.publiclet boards: [String: DrawnBoard]/// The theme the database wears.publiclet theme: WornTheme/// Every theme this build ships, by id, as its row's JSON.publiclet themes: [String: Data]/// The definition rows the database serves that it draws nowhere: a/// storage table with no face (`kept_as_rows`), then a row the core could/// not read (`refused`) — each by id with why. The reader says them once/// (`DefinitionCatalogue.sayUndrawn`), never silently.publiclet undrawn: [Undrawn]/// The database the answer is of; nil in the last resort, which is of none.publiclet database: String?}/// A served definition row the catalogue does not draw, and why.publicstructUndrawn: Sendable, Equatable {/// Whether the row is drawn nowhere by design (a storage table, kept as/// rows) rather than refused.publicenumKind: Sendable, Equatable { case keptAsRows, refused }publiclet id: Stringpubliclet reason: Stringpubliclet kind: Kindpublicinit(id: String, reason: String, kind: Kind) {self.id = idself.reason = reasonself.kind = kind }}publicenumCatalogueRefusal: Error, Equatable, CustomStringConvertible {/// The core speaks a shape this build does not read.case shape(Int?)/// The answer is not the object the shape describes.case malformed(String)publicvar description: String {switchself {case .shape(let shape):return"This build reads shape \(DefinitionCatalogues.shape) of the definitions, and its core answered shape \(shape.map(String.init) ?? "none")."case .malformed(let why):return"The core's definitions could not be read: \(why)" } }}publicfinalclassDefinitionCatalogues: Sendable {/// The shape of `definitions.catalogue` this build reads (`CATALOGUE_SHAPE`).publicstaticlet shape = 10/// The process's one cache: each core's databases, each asked once.publicstaticlet shared = DefinitionCatalogues()privatestructKey: Hashable {let core: ObjectIdentifierlet database: String }/// Held under a lock rather than on an actor, so an invalidation lands/// before the redraw it causes reads again.privatelet held = OSAllocatedUnfairLock<[Key: Held]>(initialState: [:])/// One kept answer, and the core it was asked of — held weakly, so a/// later core at the same address never reads another's answer.privatestructHeld: @unchecked Sendable {weakvar core: AnyObject?let task: Task<RawCatalogue, Error> }/// The catalogue of the database `core` names. Kept for a core that is an/// object (the app's), asked afresh for any other.publicfunc catalogue(_ core: any CottonCalling) asyncthrows -> RawCatalogue {guardlet (key, root) = Self.key(core) else { returntryawaitSelf.ask(core) }let task = held.withLock { held iniflet kept = held[key], kept.core === root.object { return kept.task }let task = Task { tryawaitSelf.ask(core) } held[key] = Held(core: root.object, task: task)return task }do {returntryawait task.value } catch {// A failed ask is not kept: the next read asks again. held.withLock { held inif held[key]?.task == task { held[key] = nil } }throw error } }/// A definitions row of `database` moved (nil: of any): its catalogue is/// asked again at the next read. The personal database is also the one a/// core with no scope names, so a named one clears that too.publicfunc invalidate(database: String?) { held.withLock { held inguardlet database else { return held.removeAll() } held = held.filter { $0.key.database != database && !$0.key.database.isEmpty } } }/// This device wrote a definition of the database `core` names: its/// catalogue is asked again at the next read, without waiting on the/// write's event.publicfunc invalidate(_ core: any CottonCalling) {let scoped = core as? DatabaseScopedCore invalidate(database: scoped?.databaseID ?? "") }/// The tables whose moving changes a catalogue.publicstaticlet tables: Set<String> = ["cotton_table_definitions", "cotton_tool_definitions", "cotton_board_definitions", "cotton_theme_definitions", ]/// The core as an object, carried into the lock.privatestructRoot: @unchecked Sendable { let object: AnyObject }privatestaticfunc key(_ core: any CottonCalling) -> (Key, Root)? {let scoped = core as? DatabaseScopedCorelet root = scoped?.unscoped ?? coreguard type(of: root) isAnyClasselse { returnnil }let object = root asAnyObjectreturn (Key(core: ObjectIdentifier(object), database: scoped?.databaseID ?? ""), Root(object: object)) }/// Ask the core for a database's catalogue, or (`shipped`) for the/// last-resort answer — this build's boards and themes, no table.publicstaticfunc ask(_ core: any CottonCalling, shipped: Bool = false) asyncthrows -> RawCatalogue {let raw = tryawait core.callRaw(CottonMethod.definitionsCatalogue, requestJSON: shipped ? #"{"shipped":true}"# : "{}")guardlet envelope = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any] else {throwCatalogueRefusal.malformed("the answer is not an envelope") }guard envelope["ok"] as? Bool == true, let data = envelope["data"] else {iflet error = envelope["error"],let said = try? JSONDecoder().decode(CottonCallError.self, from: JSONSerialization.data(withJSONObject: error)) {throw said }throwCatalogueRefusal.malformed("the core refused without saying why") }returntry read(JSONSerialization.data(withJSONObject: data)) }/// Read one answer's JSON. The shape and the envelope are refused whole.publicstaticfunc read(_ data: Data) throws -> RawCatalogue {guardlet object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {throwCatalogueRefusal.malformed("the answer is not a JSON object") }let shape = object["shape"] as? Intguard shape == Self.shape else { throwCatalogueRefusal.shape(shape) }guardlet tables = object["tables"] as? [Any], let pages = object["pages"] as? [String: Any],let boards = object["boards"] as? [String: Any],let theme = object["theme"] as? [String: Any], let themes = object["themes"] as? [String: Any],let kept = object["kept_as_rows"] as? [Any], let refused = object["refused"] as? [Any]else { throwCatalogueRefusal.malformed(ShellLines.line("definitions", "catalogue.missing_sections")) }func undrawn(_ rows: [Any], _ kind: Undrawn.Kind) throws -> [Undrawn] {try rows.map { row inguardlet row = row as? [String: Any], let id = row["id"] as? String, let reason = row["reason"] as? Stringelse {throwCatalogueRefusal.malformed(ShellLines.line("definitions", "catalogue.undrawn_missing_id")) }returnUndrawn(id: id, reason: reason, kind: kind) } }func json(_ value: Any) throws -> Data { try JSONSerialization.data(withJSONObject: value) }func drawn(_ value: Any) throws -> (Data, String?) {guardlet resolved = value as? [String: Any], let definition = resolved["definition"] else {throwCatalogueRefusal.malformed("a board or theme carries no definition") }return (try json(definition), resolved["passed_over"] as? String) }var drawnBoards: [String: DrawnBoard] = [:]for (id, board) in boards {let (definition, passedOver) = try drawn(board) drawnBoards[id] = DrawnBoard(definition: definition, passedOver: passedOver) }let worn = try drawn(theme)let own = (theme["drawn"] as? String) != WornTheme.defaultDrawnreturnRawCatalogue( tables: try tables.map(json), tableIDs: tables.map { (($0 as? [String: Any])?["id"] as? String) ?? "" }, pages: try pages.mapValues(json), said: try ((object["said"] as? [String: Any]) ?? [:]).mapValues(json), boards: drawnBoards, theme: WornTheme(definition: worn.0, passedOver: worn.1, own: own), themes: try themes.mapValues(json), undrawn: try undrawn(kept, .keptAsRows) + undrawn(refused, .refused), database: object["database"] as? String ) }}