// The root's records: every table the converted tools draw, built-in and // imported alike, read and written through the core's generic verbs // (`records.*` in cotton-ffi, each one the MCP tool an assistant calls). There // is no second store behind it — what a list shows is the owner's rows, and // what a write answers is the core's own change. // // The Settings tables are the one exception: their rows are an engine's, // written by its own methods, and `records.*` does not answer them // (`SettingsRecords`). Every verb on one of those tables — and the undo of a // change one of them minted — goes to the `SettingsRecords` this actor makes // over the same core, so the board's `tool_order` read and a Settings page // read the same rows. import CottonKit import CottonValues import Foundation import os public actor CoreRecords: UsageRecords, GenericVerbs, ThoughtKeepingRecords { public func recordUsage(_ event: UsageEvent) async { let definitions = (try? await tableDefinitions()) ?? knownDefinitions try? await core.recordUsage(homeUsage(event, definitions: definitions)) } private let core: any CottonCalling /// The tables a test or preview made this store with, standing for the /// database's catalogue; nil (the app) draws the catalogue alone. private let fixture: [TableDefinition]? /// What the last read of the tables found, and what is derived from it — /// read without waiting where a verb answers at once. private nonisolated let known: OSAllocatedUnfairLock /// The catalogue's tables as last decoded, with the bytes they came from: /// a read that finds the same bytes decodes nothing again. private var decoded: Decoded? /// What the reader last said it draws and leaves out /// (`DefinitionCatalogue.sayUndrawn`): a read that finds the same says /// nothing again. private var saidDrawn: [String]? /// The tables `SettingsRecords` answers, by its own sources. private nonisolated let settingsTables: Set private nonisolated let sourceCommandTables: Set private var settingsStore: SettingsRecords? /// The change ids `SettingsRecords` minted: only it can take them back. private var settingsChanges: Set = [] private var catalogFailed = false /// When the catalogue last failed, so a definitions read retries it at /// most once per `catalogRetryEvery` — never on every call. private var catalogFailedAt: ContinuousClock.Instant? private let catalogRetryEvery: Duration /// The last catalogue that answered: a read of an imported table checks /// it without waiting on a re-ask (only a first-ever read waits). private var lastCatalog: ToolPackageCatalog? private var catalogGeneration = 0 private var catalogTask: Task? /// `bundle` is a bundle whose fixture catalogue stands for the database's /// (a test's or a preview's); nil draws the database's own catalogue — /// the tables its definition rows describe, and no other. public init(core: any CottonCalling, bundle: Bundle? = nil, catalogRetryEvery: Duration = .seconds(30)) { self.core = core self.catalogRetryEvery = catalogRetryEvery let fixture = bundle.map { FixtureDefinitions.load(from: $0).definitions } self.fixture = fixture known = OSAllocatedUnfairLock(initialState: Known(fixture ?? [])) let sources = SettingsRecords.sources settingsTables = Set(sources.map(\.table)) sourceCommandTables = Set(sources.filter(\.gatesPageCommands).map(\.table)) } /// The tables a store last read, and what it reads off them. struct Known: Sendable { var tables: [TableDefinition] /// The tables a native engine keeps (`engine`, which the core refuses /// on a table a person defined): their reads never wait on the /// package catalogue. var engineIDs: Set /// The bins (`binned`): no thought is kept on them. var binTables: Set /// The Settings tables whose archive is the core's (`archived_in_core`). var archivedInCore: Set /// The Settings tables a link to which may hold the core's id (`core_links`). var coreLinkTables: Set init(_ tables: [TableDefinition]) { self.tables = tables engineIDs = Set(tables.filter { $0.engine != nil }.map(\.id)) binTables = Set(tables.filter { $0.binned != nil }.map(\.id)) archivedInCore = Set(tables.filter(\.archivedInCore).map(\.id)) coreLinkTables = Set(tables.filter(\.coreLinks).map(\.id)) } } /// The tables the last read found: what a screen draws before its own /// read of them answers. Empty before the first read. public nonisolated var knownDefinitions: [TableDefinition] { known.withLock { $0.tables } } // ── The imported tools' catalogue ────────────────────────────────────── func catalog(retryFailed: Bool = false) async throws -> ToolPackageCatalog { let retried = retryFailed && catalogFailed if retried { invalidateCatalog() } if catalogTask == nil { catalogTask = Task { try await ToolPackageCatalog.read(core) } } let generation = catalogGeneration let task = catalogTask! do { let snapshot = try await task.value if generation == catalogGeneration { catalogFailed = false catalogFailedAt = nil lastCatalog = snapshot if retried { await MainActor.run { NotificationCenter.default.post(name: .toolPackagesChanged, object: nil) } } } return snapshot } catch { if generation == catalogGeneration { catalogFailed = true catalogFailedAt = ContinuousClock.now } throw error } } func invalidateCatalog() { // A tool package came or went: its tables are in every catalogue. DefinitionCatalogues.shared.invalidate(database: nil) catalogGeneration += 1 catalogTask = nil catalogFailed = false } @discardableResult func refreshCatalog() async throws -> ToolPackageCatalog { invalidateCatalog() return try await catalog() } /// Whether a failed catalogue is due another ask from a definitions /// read: once per `catalogRetryEvery`, so a screen that reads its /// definitions on every draw does not re-ask the serving Mac each time. private var catalogRetryDue: Bool { guard let catalogFailedAt else { return true } return ContinuousClock.now - catalogFailedAt >= catalogRetryEvery } public func toolDefinitions() async throws -> [ToolDefinition] { try await catalog(retryFailed: catalogRetryDue).tools.map(\.definition) } /// Every table the database draws: the ones its catalogue carries — its /// definition rows, nothing this build bundles — the imported ones in the /// package catalogue's order last. An imported table the package /// catalogue does not name is left out. /// Every row the database serves that it does not draw is said once, by /// id with why (`DefinitionCatalogue.sayUndrawn`). public func tableDefinitions() async throws -> [TableDefinition] { let catalog = try await catalog(retryFailed: catalogRetryDue) let read = try await catalogueTables() let all = read.definitions let ids = catalog.importedIDs var imported: [String: TableDefinition] = [:] for table in all where ids.contains(table.id) && imported[table.id] == nil { imported[table.id] = table } let tables = all.filter { !ids.contains($0.id) } + catalog.tableIDs.compactMap { imported[$0] } known.withLock { $0 = Known(tables) } if let raw = read.raw, case let drawn = tables.map(\.id) + ["|"] + raw.undrawn.map(\.id) + read.failures, saidDrawn != drawn { saidDrawn = drawn let unnamed = imported.keys.filter { !catalog.tableIDs.contains($0) } let database = raw.database ?? (core as? DatabaseScopedCore)?.databaseID ?? "" DefinitionCatalogue.sayUndrawn(raw, drawn: tables.count, failures: read.failures, unnamed: unnamed, database: database) } return tables } /// One catalogue as the reader decoded it: the answer, its tables, and /// each table this build could not decode, with why. private struct Decoded { let raw: RawCatalogue let definitions: [TableDefinition] let failures: [String] } /// The catalogue's tables, decoded — or the fixture's (no answer then). A /// table this build cannot draw is left out and named in `failures`. private func catalogueTables() async throws -> (raw: RawCatalogue?, definitions: [TableDefinition], failures: [String]) { if let fixture { return (nil, fixture, []) } let catalogue = try await DefinitionCatalogues.shared.catalogue(core) if let decoded, decoded.raw.tables == catalogue.tables, decoded.raw.undrawn == catalogue.undrawn { return (decoded.raw, decoded.definitions, decoded.failures) } let read = DefinitionCatalogue.tables(catalogue) let made = Decoded(raw: catalogue, definitions: read.tables.sorted { $0.id < $1.id }, failures: read.failures) decoded = made return (made.raw, made.definitions, made.failures) } // ── Routing ──────────────────────────────────────────────────────────── /// The Settings tables' own records, made on first use over the same core. /// It holds this actor as its definition store, so the Tools list reads /// the one catalogue snapshot this actor keeps. private var settings: SettingsRecords { if let settingsStore { return settingsStore } let made = SettingsRecords(core: core, definitions: fixture, sources: SettingsRecords.sources) settingsStore = made return made } private nonisolated func isSettings(_ table: String) -> Bool { settingsTables.contains(table) } /// The core this store asks: a list over a table its own sources answer hands the core their rows. nonisolated var calling: any CottonCalling { core } /// The core a list of `table` asks `shell.list` of directly; nil for a /// table `SettingsRecords` answers by its own sources. nonisolated func listCore(for table: String) -> (any CottonCalling)? { isSettings(table) ? nil : core } public nonisolated func gatesPageCommands(_ table: String) -> Bool { sourceCommandTables.contains(table) } /// An engine's table never waits on the catalogue (a refused package cannot gate /// the owner's own records); a table the catalogue refused is refused /// here in its words, before the core is asked. An imported table checks /// the last catalogue that answered without waiting on a re-ask; only a /// first-ever read waits for one. private func refuseRefused(_ table: String) async throws { if known.withLock({ $0.engineIDs.contains(table) }) { return } let snapshot: ToolPackageCatalog if let lastCatalog { snapshot = lastCatalog } else { snapshot = try await catalog() } if let refusal = snapshot.refusal(ofTable: table) { throw ActionRefused(refusal.reason) } } /// The owner's local day: `records.list` and `records.get` need it for /// the money views, and every other table takes it. private nonisolated func today() -> String { CottonDate.formatter("yyyy-MM-dd", Calendar.current).string(from: Date()) } // ── Reading ──────────────────────────────────────────────────────────── struct WireRecord: Decodable { let id: String let table: String? let data: [String: RecordValue] let created_at: String? let updated_at: String? /// Who last wrote the row, by name — only a shared database's record /// carries one (`records.get`), and the page's Edited line reads it. let edited_by: String? /// False on a record the core will not delete alone — one later /// occurrence of a repeating event; absent means deletable. let deletable: Bool? /// The columns whose change asks how far it reaches, on a record /// that repeats (`TableRecord.scopeColumnsKey`). let scope_columns: [String]? /// The rollup columns whose source tool is absent, each the core's /// `{table, words}` (`TableRecord.unavailableKey`). let computed_unavailable: [String: RecordValue]? /// The columns, with the row's stamps where its data has none of its /// own — what a face reads as "updated". var record: TableRecord { var values = data if deletable == false { values[TableRecord.deletableKey] = .bool(false) } if let scope_columns, !scope_columns.isEmpty { values[TableRecord.scopeColumnsKey] = .list(scope_columns.map { .text($0) }) } if values["created_at"] == nil, let created_at { values["created_at"] = .text(created_at) } if values["updated_at"] == nil, let updated_at { values["updated_at"] = .text(updated_at) } if values[TableRecord.editedByKey] == nil, let edited_by { values[TableRecord.editedByKey] = .text(edited_by) } if let computed_unavailable, !computed_unavailable.isEmpty { values[TableRecord.unavailableKey] = .object(computed_unavailable) } return TableRecord(id: id, values: values) } } private struct WirePage: Decodable { let records: [WireRecord] let next_page: Int? /// How many live records every page holds together. let total: Int? let sections: [WireSection]? /// How many the same read finds archived (S7), on a table that archives. let archived: Int? /// A grouped list's head lines (`group.summary`), one per group value. let group_heads: [WireGroupHead]? var heads: [String: [String]]? { group_heads.map { heads in Dictionary(heads.map { ($0.value?.text ?? "", $0.lines) }, uniquingKeysWith: { first, _ in first }) } } } private struct WireGroupHead: Decodable { let value: RecordValue? let lines: [String] } private struct WireSection: Decodable { let key: String let day: String? let count: Int } /// `records.list`'s `total`: how many live records every page holds together. private struct WireTotal: Decodable { let total: Int } /// `page` is the core's cursor — an offset into the table — and `next` is /// the cursor it answers; the surfaces hand it back without reading it. public func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage { try await list(table: table, project: project, query: query, page: page, where: filter, limit: Self.pageSize) } /// What a fan tile of slips shows (`shell.list {tile}`): the records the /// core chose, in the list's order, and how many the list holds. func tile(table: String, project: String?) async throws -> RecordPage { try await refuseRefused(table) var request: [String: RecordValue] = ["table": .text(table), "tile": .bool(true), "today": .text(today())] if let project { request["project"] = .text(project) } struct Tile: Decodable { let records: [WireRecord]; let count: Int? } let answer = try await core.call(CottonMethod.shellList, request, as: Tile.self) return RecordPage(records: answer.records.map(\.record), next: nil, total: answer.count) } /// A Home `list` part's rows: its `where`, and its `period` kept by the /// table's own date from the reader's day (`list_records`' `period`). public func list(table: String, project: String?, page: Int, keep: BoardRowKeep, limit: Int) async throws -> RecordPage { try await refuseRefused(table) var request = listRequest(table, project: project, query: nil, page: page, where: keep.filter, limit: min(max(1, limit), Self.idsPerAsk)) if let period = keep.period { request["period"] = .text(period) } let answer = try await core.call(CottonMethod.recordsList, request, as: WirePage.self) return RecordPage(records: answer.records.map(\.record), next: answer.next_page, total: answer.total) } /// A page of at most `limit` records (at most the core's own most); the /// answer's `total` counts every page. public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int ) async throws -> RecordPage { if isSettings(table) { return try await settings.list(table: table, project: project, query: query, page: page, where: filter) } try await refuseRefused(table) let asked = min(max(1, limit), Self.idsPerAsk) let answer = try await core.call( CottonMethod.recordsList, listRequest(table, project: project, query: query, page: page, where: filter, limit: asked), as: WirePage.self) // A planned table's read counts its sections over the WHOLE read even // unasked (a todo group's page, every member by the day plan), so // every page carries them for the headings to count from. return RecordPage( records: answer.records.map(\.record), next: answer.next_page, total: answer.total, sections: answer.sections?.map { PlanSection(key: $0.key, day: $0.day, count: $0.count) }, archived: answer.archived, groupHeads: answer.heads) } /// How many records are put away (S7): `archived: true` with `limit: 0`, /// the count alone. public func archivedCount( table: String, project: String?, query: String?, where filter: [String: RecordValue] ) async throws -> Int? { // Questions combine channels on the live list; their comment archive // still comes from the comments engine's existing archived read. if isSettings(table), !known.withLock({ $0.archivedInCore.contains(table) }) { return nil } try await refuseRefused(table) var request = listRequest(table, project: project, query: query, page: 0, where: filter, limit: 1) request["limit"] = .number(0) request["archived"] = .bool(true) return try await core.call(CottonMethod.recordsList, request, as: WireTotal.self).total } /// The records put away (S7): `archived: true`, in the list's own order. public func listArchived( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue] ) async throws -> RecordPage { if isSettings(table), !known.withLock({ $0.archivedInCore.contains(table) }) { return try await settings.list(table: table, project: project, query: query, page: page, where: filter) } try await refuseRefused(table) var request = listRequest(table, project: project, query: query, page: page, where: filter, limit: Self.pageSize) request["archived"] = .bool(true) let answer = try await core.call(CottonMethod.recordsList, request, as: WirePage.self) return RecordPage(records: answer.records.map(\.record), next: answer.next_page, total: answer.total) } /// One section of the reader's day plan (`day_plan`): the request carries /// the section and the reader's zone beside its day, and the answer says /// every section's whole count. public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView ) async throws -> RecordPage { if isSettings(table) { return try await settings.list(table: table, project: project, query: query, page: page, where: filter) } try await refuseRefused(table) let asked = min(max(1, limit ?? Self.pageSize), Self.idsPerAsk) var request = listRequest(table, project: project, query: query, page: page, where: filter, limit: asked) request["section"] = .text(plan.section) request["timezone"] = .text(plan.timezone) if let day = plan.day { request["day"] = .text(day) } if let today = plan.today { request["today"] = .text(today) } let answer = try await core.call(CottonMethod.recordsList, request, as: WirePage.self) return RecordPage( records: answer.records.map(\.record), next: answer.next_page, total: answer.total, sections: answer.sections?.map { PlanSection(key: $0.key, day: $0.day, count: $0.count) }, archived: answer.archived) } /// A tool view's read: `view` names it (`/`) and the core reads /// the table in the view's own order with its own slip, in the plan's /// section when one is named. public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView?, view: String ) async throws -> RecordPage { if isSettings(table) { return try await settings.list(table: table, project: project, query: query, page: page, where: filter) } try await refuseRefused(table) let asked = min(max(1, limit ?? Self.pageSize), Self.idsPerAsk) var request = listRequest(table, project: project, query: query, page: page, where: filter, limit: asked) request["view"] = .text(view) if let plan { request["section"] = .text(plan.section) request["timezone"] = .text(plan.timezone) if let day = plan.day { request["day"] = .text(day) } if let today = plan.today { request["today"] = .text(today) } } let answer = try await core.call(CottonMethod.recordsList, request, as: WirePage.self) return RecordPage( records: answer.records.map(\.record), next: answer.next_page, total: answer.total, sections: answer.sections?.map { PlanSection(key: $0.key, day: $0.day, count: $0.count) }, archived: answer.archived) } /// The page a list reads at a time. static let pageSize = 50 private func listRequest( _ table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int ) -> [String: RecordValue] { var request: [String: RecordValue] = [ "table": .text(table), "page": .number(Double(page)), "limit": .number(Double(limit)), "today": .text(today()), ] if let project { request["project"] = .text(project) } if let query { request["query"] = .text(query) } if !filter.isEmpty { request["where"] = .object(filter) } return request } /// The core's whole visible total, without constructing record pages. public func count(table: String) async throws -> Int { if isSettings(table) { return try await settings.count(table: table) } try await refuseRefused(table) return try await core.call( CottonMethod.recordsList, ["table": RecordValue.text(table), "today": .text(today()), "count_only": .bool(true)], as: WireTotal.self ).total } private struct WireLastChanged: Decodable { let last_changed: String? } public func lastChanged(table: String) async throws -> String? { if isSettings(table) { return try await settings.lastChanged(table: table) } try await refuseRefused(table) return try await core.call( CottonMethod.recordsList, ["table": RecordValue.text(table), "last_changed": .bool(true)], as: WireLastChanged.self ).last_changed } private struct WireSummary: Decodable { let summary: [SummaryFigure] } /// The core's figures for the table's tile (`records.summarize`). public func summarize(table: String) async throws -> [SummaryFigure] { if isSettings(table) { return [] } try await refuseRefused(table) let request: [String: RecordValue] = ["table": .text(table)] return try await core.call(CottonMethod.recordsSummarize, request, as: WireSummary.self).summary } private struct WireLine: Decodable { let sparkline: SparklineLine? } /// The core's points for the table's sparkline face (`records.summarize`). public func sparkline(table: String) async throws -> SparklineLine? { if isSettings(table) { return nil } try await refuseRefused(table) let request: [String: RecordValue] = ["table": .text(table)] return try await core.call(CottonMethod.recordsSummarize, request, as: WireLine.self).sparkline } private struct WireChart: Decodable { let chart: ChartSeries? let viewChart: ChartSeries? enum CodingKeys: String, CodingKey { case chart case viewChart = "view_chart" } } /// The core's series for the table's chart face, else its chart view's /// (`records.summarize`'s `chart`, else `view_chart`). public func chart(table: String, today: String, at: String) async throws -> ChartSeries? { if isSettings(table) { return nil } try await refuseRefused(table) let request: [String: RecordValue] = ["table": .text(table), "today": .text(today), "at": .text(at)] let wire = try await core.call(CottonMethod.recordsSummarize, request, as: WireChart.self) return wire.chart ?? wire.viewChart } public func get(table: String, id: String) async throws -> TableRecord? { if isSettings(table) { return try await settings.get(table: table, id: id) } try await refuseRefused(table) let request: [String: RecordValue] = ["table": .text(table), "id": .text(id), "today": .text(today())] do { return try await core.call(CottonMethod.recordsGet, request, as: WireRecord.self).record } catch let error as CottonCallError where error.code == "record_not_found" { // Gone is an answer, not a failure: the page says the record was // removed, never "could not be read" with a Try again. return nil } } /// The Settings tables' titles from their own rows; every other table's /// from `records.list { table, ids }` — the linked records themselves, one /// ask per table, never a walk of the whole linked table. public func linkTitles(for links: [RecordLink]) async throws -> LinkTitles { guard !links.isEmpty else { return LinkTitles() } // Native repository links hold UUIDs. Their sources list only within // a repository, so read these titles through the native id batch below. // The database's own tables: a link title never waits on the package catalogue. let definitions = try await catalogueTables().definitions let coreLinkTables = Known(definitions).coreLinkTables let settingsLinks = links.filter { isSettings($0.table) && (!coreLinkTables.contains($0.table) || $0.id.contains("#")) } let settled = settingsLinks.isEmpty ? LinkTitles() : try await settings.linkTitles(for: settingsLinks) var titles = settled.byID var pictures = settled.pictures let localLinks = Set(settingsLinks) let rest = links.filter { !localLinks.contains($0) } guard !rest.isEmpty else { return LinkTitles(titles, pictures: pictures) } for table in Set(rest.map(\.table)) { // A link into a table no definition names is a defect to show, // never a column quietly drawn blank. guard let definition = definitions.first(where: { $0.id == table }) else { throw RecordsError.unknownTable(table) } try await refuseRefused(table) var ids: [String] = [] for link in rest where link.table == table && !ids.contains(link.id) { ids.append(link.id) } // The core answers at most a page's worth of ids at once. for start in stride(from: 0, to: ids.count, by: Self.idsPerAsk) { let asked = ids[start.. [String: RecordValue] { var cards: [String: RecordValue] = [:] for start in stride(from: 0, to: ids.count, by: Self.idsPerAsk) { let asked = ids[start.. [GroupStack] { try await core.listGroups(of: table, holding: record) } public func createGroup(named name: String, of table: String, records: [String]) async throws -> (change: ChangeRecord, group: RecordGroup?) { try await core.makeGroup(named: name, of: table, records: records) } public func updateGroup(_ id: String, _ change: GroupChange) async throws -> ChangeRecord { try await core.changeGroup(id, change) } public func deleteGroup(_ id: String) async throws -> ChangeRecord { try await core.binGroup(id) } // ── Writing ──────────────────────────────────────────────────────────── /// The core's change: `before` and `after` hold only the columns the write /// moved, so each side is drawn over the record the write answered — the /// page and the list put `after` in place of the row they show, and the /// receipt prints the columns that differ. A create has no `before`, a /// delete no `after`, a reorder neither (it names no one record). struct WireChange: Decodable { let id: String let record_id: String? let byline: String? let before: [String: RecordValue]? let after: [String: RecordValue]? /// Required: a change that does not say whether it can be undone is /// a malformed answer, never one assumed undoable. let undoable: Bool let reason: String? /// The core's words for what happened; absent from an older core. let receipt: ChangeSaid? } struct WireWrite: Decodable { let change: WireChange let record: WireRecord? } static func change(_ answer: WireWrite) -> ChangeRecord { let change = answer.change let record = answer.record?.record func side(_ moved: [String: RecordValue]?, over base: TableRecord?) -> TableRecord? { guard let moved, let id = change.record_id ?? base?.id else { return nil } var drawn = base ?? TableRecord(id: id, values: [:]) drawn.values.merge(moved) { _, moved in moved } return drawn } // What the change moved wins over the record the write answered: that // record is read back without its null columns, so a column the write // CLEARED (a person brought back: archived_at null) would be missing // from it, and a page drawing it over its last read kept the old value // ("Archived, so People leaves it out" after Put back; architect 5 Oct). let after = change.after == nil ? nil : side(change.after, over: record) let before = side(change.before, over: record) // The owner's own app writes as `user`; the receipt says "You". let byline = change.byline.flatMap { $0 == "user" || $0.isEmpty ? nil : $0 } ?? "You" return ChangeRecord( id: change.id, byline: byline, before: change.record_id == nil ? nil : before, after: change.record_id == nil ? nil : after, undoable: change.undoable, reason: change.reason, said: change.receipt) } private func write(_ method: String, _ request: [String: RecordValue]) async throws -> ChangeRecord { Self.change(try await core.call(method, request, as: WireWrite.self)) } private func settingsWrite(_ write: () async throws -> ChangeRecord) async throws -> ChangeRecord { let change = try await write() settingsChanges.insert(change.id) return change } /// `records.create`'s answer: the change and the record — or, when the /// core needs one more value before it can make the record, neither and /// its question (`ask`), which is thrown as a `CreateQuestion`. private struct WireCreate: Decodable { let change: WireChange? let record: WireRecord? let ask: CreateQuestion? } func continueFilePick(_ pick: RecordFilePick, file: URL) async throws -> ChangeRecord { // An engine is never a package's (the core refuses one on a table a // person defined), so the database's catalogue answers alone. guard try await catalogueTables().definitions.contains(where: { $0.id == pick.table && $0.engine != nil && $0.canRunCommands }) else { throw ActionRefused(ShellLines.line("definitions", "refused.not_an_engine")) } try await refuseRefused(pick.table) let answer = try await core.call("records.create", pick.arguments(file: file), as: WireCreate.self) if let change = answer.change { guard answer.ask == nil, let id = answer.record?.id ?? change.record_id, answer.record?.table == nil || answer.record?.table == pick.table, change.record_id == nil || change.record_id == id else { throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "File continuation returned another destination or no record")) } var result = Self.change(WireWrite(change: change, record: answer.record)) result.created = RecordLink(table: pick.table, id: id) return result } guard var question = answer.ask, question.table.isEmpty || question.table == pick.table else { throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "File continuation answered no change or valid question")) } question.table = pick.table question.openCreated = true // The core's question data refers to its owned copy, not the selected URL. throw question } public func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { if isSettings(table) { return try await settingsWrite { try await settings.create(table: table, data: data) } } try await refuseRefused(table) let request: [String: RecordValue] = ["table": .text(table), "data": .object(data)] let answer = try await core.call("records.create", request, as: WireCreate.self) if let change = answer.change { Self.writtenHere(table: table, data: data) return Self.change(WireWrite(change: change, record: answer.record)) } guard var question = answer.ask else { throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "records.create answered no change and no question")) } question.table = table question.data = data throw question } public func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { if isSettings(table) { return try await settingsWrite { try await settings.update(table: table, id: id, patch: patch) } } try await refuseRefused(table) let change = try await write("records.update", ["table": .text(table), "id": .text(id), "patch": .object(patch)]) Self.writtenHere(table: table, data: patch) return change } /// A row the person made, or changed, on this phone: the one moment /// AlarmKit's prompt may rise, which `AlarmSyncModel` decides from the /// table and the written columns (294 row 4). private static func writtenHere(table: String, data: [String: RecordValue]) { NotificationCenter.default.post(name: .cottonRecordWrittenHere, object: nil, userInfo: ["table": table, "data": data]) } public func update(table: String, id: String, patch: [String: RecordValue], scope: WriteScope?) async throws -> ChangeRecord { guard let scope else { return try await update(table: table, id: id, patch: patch) } try await refuseRefused(table) return try await write( "records.update", ["table": .text(table), "id": .text(id), "patch": .object(patch), "scope": .text(scope.rawValue)]) } public func delete(table: String, id: String, scope: WriteScope?) async throws -> ChangeRecord { guard let scope else { return try await delete(table: table, id: id) } try await refuseRefused(table) return try await write( "records.delete", ["table": .text(table), "id": .text(id), "today": .text(today()), "scope": .text(scope.rawValue)]) } public func delete(table: String, id: String) async throws -> ChangeRecord { if isSettings(table) { return try await settingsWrite { try await settings.delete(table: table, id: id) } } try await refuseRefused(table) return try await write("records.delete", ["table": .text(table), "id": .text(id), "today": .text(today())]) } public func reorder(table: String, ids: [String]) async throws -> ChangeRecord { if isSettings(table) { return try await settingsWrite { try await settings.reorder(table: table, ids: ids) } } try await refuseRefused(table) return try await write("records.reorder", ["table": .text(table), "ids": .list(ids.map(RecordValue.text))]) } public func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { if isSettings(table) { return try await settingsWrite { try await settings.link(table: table, id: id, column: column, target: target) } } try await refuseRefused(table) return try await write( "records.link", ["table": .text(table), "id": .text(id), "column": .text(column), "target_id": .text(target)]) } /// `capture.create`'s answer: the thought's id and the add's change. private struct WireCapture: Decodable { let change: WireChange } /// A Settings table and the Bin hold no words said on them: the box is /// not drawn there (a thought said on the Bin would be kept nowhere useful). public nonisolated func keepsThoughts(table: String) -> Bool { !isSettings(table) && !known.withLock { $0.binTables.contains(table) } } public func captureMedia( file: URL, mime: String, kind: CaptureMediaKind, filename: String?, forThought: Bool ) async throws -> MediaCaptured { try await CoreMediaCapture(core: core, forThought: forThought) .capture(file: file, mime: mime, kind: kind, filename: filename) } public func keepThought( _ words: String, table: String?, recordId: String?, attachments: [CaptureAttachment] ) async throws -> ChangeRecord { var request: [String: RecordValue] = ["text": .text(words)] if let table { request["saidTable"] = .text(table) } if let recordId, table != nil { request["saidRecordId"] = .text(recordId) } if !attachments.isEmpty { request["attachments"] = .list(attachments.map { .object(["kind": .text($0.kind), "id": .text($0.id)]) }) } let answer = try await core.call(CottonMethod.captureCreate, request, as: WireCapture.self) return Self.change(WireWrite(change: answer.change, record: nil)) } /// A change a Settings table minted goes back through `SettingsRecords`; /// every other one through the core's `undo`, which decides what putting /// it back means. public func undo(change: String) async throws -> ChangeRecord { if settingsChanges.contains(change) { return try await settingsWrite { try await settings.undo(change: change) } } return try await undo(changeId: change) } // ── GenericVerbs ─────────────────────────────────────────────────────── public nonisolated var answersUndo: Bool { true } /// `records.undo` answers `{change, undone, record}`: the change is the /// undoing one, drawn like any write's. public func undo(changeId: String) async throws -> ChangeRecord { try await write("records.undo", ["change_id": .text(changeId)]) } } // ── Engine commands ─────────────────────────────────────────────────────── extension CoreRecords: RecordCommands { /// One command its table's built-in definition declares (Pin, Archive, /// Clear chat, the read stamp), run by the core: it takes the table, the /// record and the command's id, and binds the verb and its arguments from /// its own copy of the definition — never from what the app sends. /// /// The core answers what happened — the receipt's words ("Pinned", else /// the label), the command that takes it back, and for an `open` what to /// open — and the change carries exactly that: nothing is composed here. public func command(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord { try await refuseRefused(table) return try await core.recordCommand(table: table, id: id, command: command, picked: picked) } public func command(table: String, id: String, command: RecordCommand, pickedValues: [String]) async throws -> ChangeRecord { try await refuseRefused(table) return try await core.recordCommand(table: table, id: id, command: command, pickedValue: .list(pickedValues.map(RecordValue.text))) } /// The method's own way back, sent as it came; its answer's receipt is /// what the undone change says. public func undo(_ call: CommandUndoCall, taken: CommandTaken) async throws -> ChangeRecord { try await core.recordUndoCall(call, taken: taken) } } extension CottonCalling { /// Every record store runs a definition's command through the same native boundary. func recordCommand(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord { try await recordCommand(table: table, id: id, command: command, pickedValue: picked.map(RecordValue.text) ?? .null) } func recordCommand(table: String, id: String, command: RecordCommand, pickedValue: RecordValue, keyring: VaultKeyring = VaultKeyring()) async throws -> ChangeRecord { let outcome: CommandOutcome let request: [String: RecordValue] = ["table": .text(table), "id": .text(id), "command": .text(command.id), "picked": pickedValue] do { outcome = try await call("records.command", request, as: CommandOutcome.self) } catch let refusal as CottonCallError where refusal.code == "vault_locked" { outcome = try await recordCommandWithVaultKey(request, keyring: keyring) } catch let refusal as CottonCallError { throw ActionRefused(refusal.message) } return try outcome.change(table: table, record: id) } /// A command whose method opens the vault (Keys › Devices' Approve) on a /// locked vault: this device's own vault key, read from the Keychain — /// the read IS the presence prompt (Face ID or the passcode) — and handed /// to the core for this one call, which lends it to that method alone /// (`KEY_LENT_METHODS`). Nothing here keeps it, and nothing unlocks the /// vault for five minutes. A refusal after that is the core's, in its words. private func recordCommandWithVaultKey(_ request: [String: RecordValue], keyring: VaultKeyring) async throws -> CommandOutcome { let read = await Task.detached(priority: .userInitiated) { () -> Result in do { return .success(try keyring.privateKey()) } catch { return .failure(error) } }.value let key: String switch read { case .success(let found): key = found case .failure(let error): switch error as? VaultKeyError { case .cancelled: throw CancellationError() default: throw ActionRefused(ShellLines.line("passwords", "vault.phone_own_key")) } } var lent = request lent["privateKey"] = .text(key) do { return try await call("records.command", lent, as: CommandOutcome.self) } catch let refusal as CottonCallError { throw ActionRefused(refusal.message) } } /// A list's act, run by the core for the `count` rows it was offered over. func recordListCommand(table: String, command: String, count: Int) async throws -> ChangeRecord { let outcome: CommandOutcome do { outcome = try await call( "records.command", ["table": RecordValue.text(table), "command": .text(command), "count": .number(Double(count))], as: CommandOutcome.self) } catch let refusal as CottonCallError { throw ActionRefused(refusal.message) } // A list's act changes no one record: its receipt, and no Undo. var change = ChangeRecord( id: "command-\(UUID().uuidString.lowercased())", byline: "You", before: nil, after: nil, undoable: false, reason: nil, said: outcome.receipt.map { ChangeSaid(kind: "command", said: $0) }) if let effect = outcome.answer?.platformAction { change.opened = .platform(effect) } return change } /// Run an app method's own way back (`CommandUndoCall`) — the arguments /// exactly as the core answered them — and answer the change it made. func recordUndoCall(_ call: CommandUndoCall, taken: CommandTaken) async throws -> ChangeRecord { let said: UndoCallSaid do { let args = try JSONDecoder().decode(JSONValue.self, from: Data(call.args.utf8)) said = try await self.call(call.method, args, as: UndoCallSaid.self) } catch let refusal as CottonCallError { throw ActionRefused(refusal.message) } return ChangeRecord( id: "command-\(UUID().uuidString.lowercased())", byline: "You", before: nil, after: nil, undoable: false, reason: nil, said: said.receipt.map { ChangeSaid(kind: "command", said: $0) }, command: CommandTaken(table: taken.table, record: taken.record, undo: nil)) } } /// What an app method's way back answers that a change says: its receipt. struct UndoCallSaid: Decodable { let receipt: String? } /// `records.command`'s answer: `{command, kind, receipt, undo, answer, open}`. struct CommandOutcome: Decodable { struct Open: Decodable { let table: String? let id: String? let url: String? /// The record comes by sync (`RecordCommand.lands`). let by_sync: Bool? } struct Answer: Decodable { let write: CoreRecords.WireWrite? let pending: Bool let ask: CreateQuestion? let platformAction: RecordPlatformAction? /// A database the act brought back, shown when it is done. let showsDatabase: String? init(from decoder: Decoder) throws { // Engine-specific answers may have no change envelope. Once a // change is present, a malformed one must fail decoding. let value = try JSONValue(from: decoder) // `pending` is the core's word for a command still waiting only // as a boolean (`records.command` reads `pending == true`). A // method answering a NUMBER there says how many writes wait in // its outbox (`sync.now`): the command is done, and that answer // is the method's own, never refused as a malformed one. if case .object(let fields) = value, let waiting = fields["pending"] { switch waiting { case .number: pending = false case .bool(let isPending) where !isPending || fields["change"] == nil || fields["change"] == .null: pending = isPending default: throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A pending command has a boolean state and no completed change")) } } else { pending = false } if case .object = value { platformAction = try RecordPlatformAction.fromAnswer(decoder) } else { platformAction = nil } if case .object(let fields) = value, case .string(let shown)? = fields["shows_database"], !shown.isEmpty { showsDatabase = shown } else { showsDatabase = nil } if case .object(let fields) = value, let asked = fields["ask"], asked != .null { guard case .object(let continuation) = asked, case .object? = continuation["data"], fields["change"] == nil || fields["change"] == .null else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A command question must carry create data and no change")) } struct Question: Decodable { let ask: CreateQuestion } var question = try Question(from: decoder).ask guard !question.table.isEmpty else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A command question must name its create table")) } question.openCreated = true ask = question write = nil } else if case .object(let fields) = value, let change = fields["change"], change != .null { write = try CoreRecords.WireWrite(from: decoder) ask = nil } else { write = nil ask = nil } } } /// An app method's own way back: `{method, args}`. struct UndoCall: Decodable { let method: String let args: JSONValue } let command: String let kind: String? let receipt: String? let undo: String? let open: Open? let answer: Answer? let undo_call: UndoCall? /// A value shown once (`RecordCommand.reveals`). let reveal: Reveal? struct Reveal: Decodable { let title: String let value: String let note: String } /// The way back as a change carries it — the arguments kept as the JSON /// they came as, to be sent back unread. var undoCall: CommandUndoCall? { guard let call = undo_call, let args = try? JSONEncoder().encode(call.args) else { return nil } return CommandUndoCall(method: call.method, args: String(decoding: args, as: UTF8.self)) } /// The change a surface lands: the receipt's words and its Undo for a /// command that changed something, the thing to open for one that did not. func change(table: String, record: String) throws -> ChangeRecord { if let question = answer?.ask { throw question } if let write = answer?.write { // A generic write already has its durable Undo and row changes; // replacing them with a command-only receipt loses both. var change = CoreRecords.change(write) // A cross-database write returns its own paired Undo method. if let undoCall { change.command = CommandTaken(table: table, record: record, undo: undo, undoCall: undoCall) } if let effect = answer?.platformAction { change.opened = .platform(effect) } // The command names the intent (for example, moving a todo), // while its underlying generic write only knows a row changed. if let receipt { change.said = ChangeSaid(kind: "command", said: receipt) } if kind == "create", let written = write.record, let target = written.table { change.created = RecordLink(table: target, id: written.id) } return change } var opened: CommandOpened? if let shown = answer?.showsDatabase { opened = .database(shown) } else if let effect = answer?.platformAction { opened = .platform(effect) } else if let target = open?.table, let id = open?.id { opened = open?.by_sync == true ? .landed(RecordLink(table: target, id: id)) : .record(RecordLink(table: target, id: id)) } else if let url = open?.url { opened = .address(url) } let pending = answer?.pending == true var change = ChangeRecord( id: "command-\(UUID().uuidString.lowercased())", byline: "You", before: nil, after: nil, undoable: !pending && (undo != nil || undoCall != nil), reason: nil, said: pending ? nil : receipt.map { ChangeSaid(kind: "command", said: $0) }, command: CommandTaken(table: table, record: record, undo: pending ? nil : undo, undoCall: pending ? nil : undoCall), opened: opened) change.pending = pending change.quiet = pending return change } } // ── Acts ────────────────────────────────────────────────────────────────── /// The acts of a table the app answers itself (a chat import's "Choose an /// export", "I am …"), through the same `SettingsRecords` its rows come from. /// A table the core answers has none. extension CoreRecords: ActingRecords, CreationRecords { func prepareCreation(table: String, where filter: [String: RecordValue]) async throws { if isSettings(table) { try await settings.prepareCreation(table: table, where: filter) } } public func permitsCreation(table: String, where filter: [String: RecordValue]) async -> Bool { isSettings(table) ? await settings.permitsCreation(table: table, where: filter) : true } public func listActions(table: String) async -> [RecordAction] { await listActions(table: table, where: [:]) } public func listActions(table: String, where filter: [String: RecordValue]) async -> [RecordAction] { if isSettings(table) { return await settings.listActions(table: table, where: filter) } return await commandListActions(table: table, where: filter) } /// The definition's list acts (`RecordCommand.list`), each offered while /// enough of the list's rows are ones it is for, saying how many. The /// commands are the build's own, as `records.command` runs them. A list /// that cannot be read offers no act over it: the list says the read failed. private func commandListActions(table: String, where filter: [String: RecordValue]) async -> [RecordAction] { let definition = (try? await tableDefinitions())?.first { $0.id == table && $0.engine != nil } let listed = (definition?.commands ?? []).filter { $0.list != nil } guard !listed.isEmpty, let rows = try? await everyRow(table, where: filter) else { return [] } return listed.compactMap { command in guard let count = command.offered(over: rows) else { return nil } let label = RecordCommand.counted(command.label, count) let question = command.confirm.map { WriteConfirmation( title: label + "?", message: RecordCommand.counted($0, count), confirmLabel: command.kind == .delete ? "Remove" : label, destructive: command.kind == .delete || command.destructive == true) } return RecordAction(id: command.id, label: label, confirmation: question).command(command.id).counting(count) } } /// Every row of a list, page after page, as the list reads them. private func everyRow(_ table: String, where filter: [String: RecordValue]) async throws -> [TableRecord] { var rows: [TableRecord] = [] var page = 0 while true { let read = try await list(table: table, project: nil, query: nil, page: page, where: filter, limit: Self.idsPerAsk) rows += read.records guard let next = read.next, next != page else { return rows } page = next } } public func pageActions(table: String, record: TableRecord) async -> [RecordAction] { isSettings(table) ? await settings.pageActions(table: table, record: record) : [] } public nonisolated func offersSlipActions(table: String) -> Bool { isSettings(table) } public func slipActions(table: String, record: TableRecord) async -> [RecordAction] { isSettings(table) ? await settings.slipActions(table: table, record: record) : [] } public func perform(_ action: RecordAction, table: String, record: TableRecord?) async throws -> ActionOutcome { try await perform(action, values: [:], table: table, record: record) } public func perform(_ action: RecordAction, values: [String: String], table: String, record: TableRecord?) async throws -> ActionOutcome { if isSettings(table) { return try await settings.perform(action, values: values, table: table, record: record) } guard record == nil, let count = action.count, let command = action.commandID else { throw SettingsRecordsError.refusedVerb(table: table, verb: action.id) } try await refuseRefused(table) let change = try await core.recordListCommand(table: table, command: command, count: count) // A list act that opens a kept flow (Approve a request) hands it on. if case .platform(.openFlow(let flow))? = change.opened { return .flow(flow.flow.kept) } return .change(change) } public func listNote(table: String) async -> String? { isSettings(table) ? await settings.listNote(table: table) : nil } } extension CoreRecords: GroupingRecords {} // ── The group verbs over any core ───────────────────────────────────────── // This store's, and the Settings tables' (`SettingsRecords`), whose Tools // screen keeps groups of tools (Spec 9.2): one wire, read in one place. extension CottonCalling { func listGroups(of table: String, holding record: String?) async throws -> [GroupStack] { var request: [String: RecordValue] = ["table": .text(table)] if let record { request["record"] = .text(record) } return try await call(CottonMethod.groupsList, request, as: CoreRecords.WireGroups.self).groups.map(\.stack) } /// One group's members' ids in its own order; empty for a group since deleted. func groupMembers(_ id: String, of table: String) async throws -> [String] { let request: [String: RecordValue] = ["table": .text(table)] let groups = try await call(CottonMethod.groupsList, request, as: CoreRecords.WireGroups.self).groups return groups.first { $0.id == id }?.members ?? [] } func makeGroup(named name: String, of table: String, records: [String]) async throws -> (change: ChangeRecord, group: RecordGroup?) { var request: [String: RecordValue] = ["table": .text(table), "name": .text(name)] if !records.isEmpty { request["records"] = .list(records.map(RecordValue.text)) } let answer = try await call(CottonMethod.groupsCreate, request, as: CoreRecords.WireGroupWrite.self) return (CoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil)), answer.group?.group) } func changeGroup(_ id: String, _ group: GroupChange) async throws -> ChangeRecord { let answer = try await call(CottonMethod.groupsUpdate, group.request(id: id), as: CoreRecords.WireGroupWrite.self) return CoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil)) } func binGroup(_ id: String) async throws -> ChangeRecord { let request: [String: RecordValue] = ["id": .text(id)] let answer = try await call(CottonMethod.groupsDelete, request, as: CoreRecords.WireGroupWrite.self) return CoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil)) } /// A group change taken back: the core's one undo. func undoGroupChange(_ id: String) async throws -> ChangeRecord { CoreRecords.change(try await call("records.undo", ["change_id": RecordValue.text(id)], as: CoreRecords.WireWrite.self)) } } extension CoreRecords: RecordFileCommands {}