// Every definition a database draws — tables, boards, themes — as the CORE// resolved and decoded them (`definitions.catalogue`,// `crates/cotton-ffi/src/phone/catalogue.rs`), read into the view types this// app draws from.//// ONE DECODER OF THE DEFINITION FORMAT (architect, 14 Oct 2026). Phone cut 273// crashed before its first screen: a definition file the core accepted failed// this app's own decoder of the same file. The app no longer reads a// definition file: the core reads them, validates them, says once in// Feedback any stored one it cannot draw, and hands each back as its typed// value serialized.//// A database draws the tables its own definition rows describe and no other// (tools are records only, 21 Oct 2026): no table is drawn from this build.// What the app draws before any database answers is the core's last resort —// this build's boards and themes, no table:// * the app's process asks its core once, right after opening it// (`receiveLastResort(from:)`), and keeps the boards — a shape this build// cannot read, or a board it cannot draw, is a refusal the open screen// says, never a crash;// * a process with no core of its own (the package's tests) reads// the same answer from the snapshot beside the resources// (`Resources/Shipped/catalogue.json`).// A database's own catalogue is cached per database (`DefinitionCatalogues`).// Previews and the package's tests draw a synthetic household that took the// kit (`Resources/Fixtures/catalogue.json`, `fixture(in:)`), never the app.//// THIS FILE IS THE ONE BOUNDARY: no other Swift decodes a table or board// definition (`NoSecondDecoderTests`).importCottonKitimportFoundationimport osextensionTableDefinition {/// Decodes one definition from the format's JSON — only what the core/// handed over, and only here (and in the tests' fixtures).staticfunc decode(_ data: Data) throws -> TableDefinition {try JSONDecoder().decode(TableDefinition.self, from: data) }}extensionBoardDefinition {/// The board a row describes, or nil for data that is not a board (no id/// or no parts) — only what the core handed over, and only here.staticfunc decode(_ data: Data) -> BoardDefinition? {guardlet board = try? JSONDecoder().decode(Self.self, from: data), !board.id.isEmpty, !board.parts.isEmpty else { returnnil }return board }staticfunc decode(_ object: [String: Any]) -> BoardDefinition? {guardlet data = try? JSONSerialization.data(withJSONObject: object) else { returnnil }return decode(data) }}publicstructDefinitionCatalogue: Sendable {/// Every table the answer carried, by id.publiclet tables: [TableDefinition]/// Every table as the core serialized it, by id — what a screen that/// edits a definition compares a database's row against.publiclet tableRows: [String: Data]/// Every board by id.publiclet boards: [String: BoardDefinition]/// Every shipped theme's row by id, as `Theme.decode` reads one.publiclet themeRows: [String: Data]/// Each definition the answer carried that this build could not draw,/// named with why. A last-resort hand-over with any is refused.publiclet failures: [String]staticlet empty = DefinitionCatalogue(tables: [], tableRows: [:], boards: [:], themeRows: [:], failures: [])/// A shipped answer this build cannot draw all of.structUndrawable: Error, Equatable, CustomStringConvertible {let failures: [String]var description: String {ShellLines.line("definitions", "catalogue.undrawable", ["count": String(failures.count), "failures": failures.joined(separator: "; ")]) } }/// The tables of one answer: a table that does not decode is named in/// `failures` and left out — never a trap.staticfunc tables(_ raw: RawCatalogue) -> (tables: [TableDefinition], failures: [String]) {var tables: [TableDefinition] = []var failures: [String] = []for (index, data) in raw.tables.enumerated() {let id = raw.tableIDs[index]do { tables.append(try table(data, id: id, in: raw)) } catch { failures.append("table \(id.isEmpty ? "#\(index)" : id): \(error)") } }return (tables, failures) }/// The lines `sayUndrawn` has written in this process.privatestaticlet said = OSAllocatedUnfairLock<Set<String>>(initialState: [])/// What the reader holds of one answer, said ONCE per process for each/// database and outcome: how many tables it draws of the rows served, and/// every row it draws nowhere by id with why — the storage tables kept as/// rows, the rows the core refused, any table this build could not decode/// (`failures`) and any imported table the tool catalogue does not name/// (`unnamed`). A row is never left out silently (tables-dropped, 28 Oct/// 2026: 35 of Personal's 144 reached the fan as nothing at all)./// Returns the line, written now or already said. @discardableResultstaticfunc sayUndrawn( _ raw: RawCatalogue, drawn: Int, failures: [String], unnamed: [String] = [], database: String ) -> String {let line = undrawnLine(raw, drawn: drawn, failures: failures, unnamed: unnamed, database: database)let fresh = said.withLock { $0.insert(line).inserted }if fresh {let wrong = raw.undrawn.contains { $0.kind == .refused } || !failures.isEmpty || !unnamed.isEmptyif wrong { Log.warn(line) } else { Log.write(line) } }return line }/// `sayUndrawn`'s line: `definitions: <database> draws 109 of 144 tables served; kept as rows (<why>): a, b; refused: c (<why>); not decoded: …; imported, not in the tool catalogue: …`.staticfunc undrawnLine( _ raw: RawCatalogue, drawn: Int, failures: [String], unnamed: [String] = [], database: String ) -> String {let served = raw.tables.count + raw.undrawn.countvar parts = [ShellLines.line("definitions", "catalogue.draws", ["database": database.isEmpty ? "personal" : database, "drawn": String(drawn), "served": String(served)])]let kept = raw.undrawn.filter { $0.kind == .keptAsRows }for reason inArray(Set(kept.map(\.reason))).sorted() { parts.append(ShellLines.line("definitions", "catalogue.kept_reason", ["reason": reason]) + " " + kept.filter { $0.reason == reason }.map(\.id).sorted().joined(separator: ", ")) }let refused = raw.undrawn.filter { $0.kind == .refused }if !refused.isEmpty { parts.append("refused: " + refused.map { "\($0.id) (\($0.reason))" }.joined(separator: ", ")) }if !failures.isEmpty { parts.append(ShellLines.line("definitions", "catalogue.not_decoded") + " " + failures.joined(separator: ", ")) }if !unnamed.isEmpty { parts.append(ShellLines.line("definitions", "catalogue.not_in_catalogue") + " " + unnamed.sorted().joined(separator: ", ")) }return parts.joined(separator: "; ") }/// No page came with a table: the core resolves every table's page.structNoPage: Error, CustomStringConvertible {var description: String { ShellLines.line("definitions", "catalogue.no_page") } }/// One table of an answer, with the page the core resolved for it.staticfunc table(_ data: Data, id: String, in raw: RawCatalogue) throws -> TableDefinition {guardlet page = raw.pages[id] else { throwNoPage() }returntryTableDefinition.decode(data).drawing(JSONDecoder().decode(DrawnPage.self, from: page)).saying(raw.said[id]) }/// The board a catalogue's row describes, or nil for data that is not a/// board (no id or no parts): the caller then draws this build's default.publicstaticfunc board(_ drawn: DrawnBoard) -> BoardDefinition? {BoardDefinition.decode(drawn.definition) }/// Read one answer into the view types.publicstaticfunc read(_ raw: RawCatalogue) -> DefinitionCatalogue {var (tables, failures) = tables(raw)var boards: [String: BoardDefinition] = [:]for (id, drawn) in raw.boards {iflet board = board(drawn) { boards[id] = board } else { failures.append(ShellLines.line("definitions", "catalogue.not_a_board", ["id": id])) } } tables.sort { $0.id < $1.id }var tableRows: [String: Data] = [:]for (id, data) in zip(raw.tableIDs, raw.tables) where !id.isEmpty { tableRows[id] = data }returnDefinitionCatalogue(tables: tables, tableRows: tableRows, boards: boards, themeRows: raw.themes, failures: failures) }/// The last-resort snapshot a bundle carries, or nil when it carries none.staticfunc lastResort(in bundle: Bundle?) throws -> DefinitionCatalogue? {try read(bundle?.url(forResource: "catalogue", withExtension: "json", subdirectory: "Shipped")) }/// The synthetic household's catalogue a bundle carries — the kit as a/// database that imported it draws it — or nil when it carries none./// Previews and the package's tests draw it; a database never does.publicstaticfunc fixture(in bundle: Bundle?) throws -> DefinitionCatalogue? {try read(bundle?.url(forResource: "catalogue", withExtension: "json", subdirectory: "Fixtures")) }privatestaticfunc read(_ url: URL?) throws -> DefinitionCatalogue? {guardlet url else { returnnil }return read(tryDefinitionCatalogues.read(FixtureDefinitions.readBundledJSON(url, limit: 8_388_608))) }// ── This process's last resort: boards ────────────────────────────────privatestaticlet held = OSAllocatedUnfairLock<[String: BoardDefinition]?>(initialState: nil)/// The boards this build ships, drawn before a database's catalogue has/// answered: the last resort this process's core handed over, or — in a/// process that opened no core — the snapshot in the app's resources./// Empty only in a build with no resources at all; it never traps.publicstaticvar shippedBoards: [String: BoardDefinition] {iflet boards = held.withLock({ $0 }) { return boards }let bundled = (try? lastResort(in: CottonUIResources.bundle))??.boardsreturn held.withLock { held inlet boards = held ?? bundled ?? [:] held = boardsreturn boards } }/// The shipped themes' rows: the core's answer once it has handed one/// over, else the snapshot's.publicstaticvar shippedThemeRows: [String: Data] { ShippedThemes.rows }/// Ask the core for its last resort and keep its boards and themes as this/// process's. Refused — and nothing kept — when the shape is not this/// build's, the answer is not one, or any board in it cannot be drawn.publicstaticfunc receiveLastResort(from core: any CottonCalling) asyncthrows {let answer = read(tryawaitDefinitionCatalogues.ask(core, shipped: true))guard answer.failures.isEmpty else { throwUndrawable(failures: answer.failures) } held.withLock { $0 = answer.boards }ShippedThemes.receive(answer.themeRows) }}