// 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.importCottonKitimportCottonValuesimportFoundationimport ospublic actor CoreRecords: UsageRecords, GenericVerbs, ThoughtKeepingRecords {publicfunc recordUsage(_ event: UsageEvent) async {let definitions = (try? await tableDefinitions()) ?? knownDefinitionstry? await core.recordUsage(homeUsage(event, definitions: definitions)) }privatelet 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.privatelet 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<Known>/// The catalogue's tables as last decoded, with the bytes they came from:/// a read that finds the same bytes decodes nothing again.privatevar decoded: Decoded?/// What the reader last said it draws and leaves out/// (`DefinitionCatalogue.sayUndrawn`): a read that finds the same says/// nothing again.privatevar saidDrawn: [String]?/// The tables `SettingsRecords` answers, by its own sources.private nonisolated let settingsTables: Set<String>private nonisolated let sourceCommandTables: Set<String>privatevar settingsStore: SettingsRecords?/// The change ids `SettingsRecords` minted: only it can take them back.privatevar settingsChanges: Set<String> = []privatevar catalogFailed = false/// When the catalogue last failed, so a definitions read retries it at/// most once per `catalogRetryEvery` — never on every call.privatevar catalogFailedAt: ContinuousClock.Instant?privatelet 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).privatevar lastCatalog: ToolPackageCatalog?privatevar catalogGeneration = 0privatevar catalogTask: Task<ToolPackageCatalog, Error>?/// `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.publicinit(core: any CottonCalling, bundle: Bundle? = nil, catalogRetryEvery: Duration = .seconds(30)) {self.core = coreself.catalogRetryEvery = catalogRetryEverylet 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.structKnown: 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<String>/// The bins (`binned`): no thought is kept on them.var binTables: Set<String>/// The Settings tables whose archive is the core's (`archived_in_core`).var archivedInCore: Set<String>/// The Settings tables a link to which may hold the core's id (`core_links`).var coreLinkTables: Set<String>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) asyncthrows -> ToolPackageCatalog {let retried = retryFailed && catalogFailedif retried { invalidateCatalog() }if catalogTask == nil { catalogTask = Task { tryawaitToolPackageCatalog.read(core) } }let generation = catalogGenerationlet task = catalogTask!do {let snapshot = tryawait task.valueif generation == catalogGeneration { catalogFailed = false catalogFailedAt = nil lastCatalog = snapshotif retried {awaitMainActor.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 } @discardableResultfunc refreshCatalog() asyncthrows -> ToolPackageCatalog { invalidateCatalog()returntryawait 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.privatevar catalogRetryDue: Bool {guardlet catalogFailedAt else { returntrue }returnContinuousClock.now - catalogFailedAt >= catalogRetryEvery }publicfunc toolDefinitions() asyncthrows -> [ToolDefinition] {tryawait 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`).publicfunc tableDefinitions() asyncthrows -> [TableDefinition] {let catalog = tryawait catalog(retryFailed: catalogRetryDue)let read = tryawait catalogueTables()let all = read.definitionslet ids = catalog.importedIDsvar 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) }iflet raw = read.raw, caselet drawn = tables.map(\.id) + ["|"] + raw.undrawn.map(\.id) + read.failures, saidDrawn != drawn { saidDrawn = drawnlet 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.privatestructDecoded {let raw: RawCataloguelet 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`.privatefunc catalogueTables() asyncthrows -> (raw: RawCatalogue?, definitions: [TableDefinition], failures: [String]) {iflet fixture { return (nil, fixture, []) }let catalogue = tryawaitDefinitionCatalogues.shared.catalogue(core)iflet 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 = madereturn (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.privatevar settings: SettingsRecords {iflet settingsStore { return settingsStore }let made = SettingsRecords(core: core, definitions: fixture, sources: SettingsRecords.sources) settingsStore = madereturn 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.privatefunc refuseRefused(_ table: String) asyncthrows {if known.withLock({ $0.engineIDs.contains(table) }) { return }let snapshot: ToolPackageCatalogiflet lastCatalog { snapshot = lastCatalog } else { snapshot = tryawait catalog() }iflet refusal = snapshot.refusal(ofTable: table) {throwActionRefused(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 ────────────────────────────────────────────────────────────structWireRecord: Decodable {let id: Stringlet 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 = dataif deletable == false { values[TableRecord.deletableKey] = .bool(false) }iflet 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) }iflet computed_unavailable, !computed_unavailable.isEmpty { values[TableRecord.unavailableKey] = .object(computed_unavailable) }returnTableRecord(id: id, values: values) } }privatestructWirePage: 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 inDictionary(heads.map { ($0.value?.text ?? "", $0.lines) }, uniquingKeysWith: { first, _ in first }) } } }privatestructWireGroupHead: Decodable {let value: RecordValue?let lines: [String] }privatestructWireSection: Decodable {let key: Stringlet day: String?let count: Int }/// `records.list`'s `total`: how many live records every page holds together.privatestructWireTotal: 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.publicfunc list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) asyncthrows -> RecordPage {tryawait 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?) asyncthrows -> RecordPage {tryawait refuseRefused(table)var request: [String: RecordValue] = ["table": .text(table), "tile": .bool(true), "today": .text(today())]iflet project { request["project"] = .text(project) }structTile: Decodable { let records: [WireRecord]; let count: Int? }let answer = tryawait core.call(CottonMethod.shellList, request, as: Tile.self)returnRecordPage(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`).publicfunc list(table: String, project: String?, page: Int, keep: BoardRowKeep, limit: Int) asyncthrows -> RecordPage {tryawait refuseRefused(table)var request = listRequest(table, project: project, query: nil, page: page, where: keep.filter, limit: min(max(1, limit), Self.idsPerAsk))iflet period = keep.period { request["period"] = .text(period) }let answer = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)returnRecordPage(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.publicfunc list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int ) asyncthrows -> RecordPage {if isSettings(table) {returntryawait settings.list(table: table, project: project, query: query, page: page, where: filter) }tryawait refuseRefused(table)let asked = min(max(1, limit), Self.idsPerAsk)let answer = tryawait 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.returnRecordPage( 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.publicfunc archivedCount( table: String, project: String?, query: String?, where filter: [String: RecordValue] ) asyncthrows -> 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) }) { returnnil }tryawait refuseRefused(table)var request = listRequest(table, project: project, query: query, page: 0, where: filter, limit: 1) request["limit"] = .number(0) request["archived"] = .bool(true)returntryawait core.call(CottonMethod.recordsList, request, as: WireTotal.self).total }/// The records put away (S7): `archived: true`, in the list's own order.publicfunc listArchived( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue] ) asyncthrows -> RecordPage {if isSettings(table), !known.withLock({ $0.archivedInCore.contains(table) }) {returntryawait settings.list(table: table, project: project, query: query, page: page, where: filter) }tryawait refuseRefused(table)var request = listRequest(table, project: project, query: query, page: page, where: filter, limit: Self.pageSize) request["archived"] = .bool(true)let answer = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)returnRecordPage(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.publicfunc list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView ) asyncthrows -> RecordPage {if isSettings(table) {returntryawait settings.list(table: table, project: project, query: query, page: page, where: filter) }tryawait 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)iflet day = plan.day { request["day"] = .text(day) }iflet today = plan.today { request["today"] = .text(today) }let answer = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)returnRecordPage( 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 (`<tool>/<id>`) 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.publicfunc list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView?, view: String ) asyncthrows -> RecordPage {if isSettings(table) {returntryawait settings.list(table: table, project: project, query: query, page: page, where: filter) }tryawait 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)iflet plan { request["section"] = .text(plan.section) request["timezone"] = .text(plan.timezone)iflet day = plan.day { request["day"] = .text(day) }iflet today = plan.today { request["today"] = .text(today) } }let answer = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)returnRecordPage( 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.staticlet pageSize = 50privatefunc 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()), ]iflet project { request["project"] = .text(project) }iflet query { request["query"] = .text(query) }if !filter.isEmpty { request["where"] = .object(filter) }return request }/// The core's whole visible total, without constructing record pages.publicfunc count(table: String) asyncthrows -> Int {if isSettings(table) { returntryawait settings.count(table: table) }tryawait refuseRefused(table)returntryawait core.call(CottonMethod.recordsList, ["table": RecordValue.text(table), "today": .text(today()), "count_only": .bool(true)],as: WireTotal.self ).total }privatestructWireLastChanged: Decodable {let last_changed: String? }publicfunc lastChanged(table: String) asyncthrows -> String? {if isSettings(table) { returntryawait settings.lastChanged(table: table) }tryawait refuseRefused(table)returntryawait core.call(CottonMethod.recordsList, ["table": RecordValue.text(table), "last_changed": .bool(true)],as: WireLastChanged.self ).last_changed }privatestructWireSummary: Decodable {let summary: [SummaryFigure] }/// The core's figures for the table's tile (`records.summarize`).publicfunc summarize(table: String) asyncthrows -> [SummaryFigure] {if isSettings(table) { return [] }tryawait refuseRefused(table)let request: [String: RecordValue] = ["table": .text(table)]returntryawait core.call(CottonMethod.recordsSummarize, request, as: WireSummary.self).summary }privatestructWireLine: Decodable {let sparkline: SparklineLine? }/// The core's points for the table's sparkline face (`records.summarize`).publicfunc sparkline(table: String) asyncthrows -> SparklineLine? {if isSettings(table) { returnnil }tryawait refuseRefused(table)let request: [String: RecordValue] = ["table": .text(table)]returntryawait core.call(CottonMethod.recordsSummarize, request, as: WireLine.self).sparkline }privatestructWireChart: Decodable {let chart: ChartSeries?let viewChart: ChartSeries?enumCodingKeys: String, CodingKey {case chartcase 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`).publicfunc chart(table: String, today: String, at: String) asyncthrows -> ChartSeries? {if isSettings(table) { returnnil }tryawait refuseRefused(table)let request: [String: RecordValue] = ["table": .text(table), "today": .text(today), "at": .text(at)]let wire = tryawait core.call(CottonMethod.recordsSummarize, request, as: WireChart.self)return wire.chart ?? wire.viewChart }publicfunc get(table: String, id: String) asyncthrows -> TableRecord? {if isSettings(table) { returntryawait settings.get(table: table, id: id) }tryawait refuseRefused(table)let request: [String: RecordValue] = ["table": .text(table), "id": .text(id), "today": .text(today())]do {returntryawait core.call(CottonMethod.recordsGet, request, as: WireRecord.self).record } catchlet error asCottonCallErrorwhere 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.returnnil } }/// 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.publicfunc linkTitles(for links: [RecordLink]) asyncthrows -> LinkTitles {guard !links.isEmpty else { returnLinkTitles() }// 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 = tryawait catalogueTables().definitionslet coreLinkTables = Known(definitions).coreLinkTableslet settingsLinks = links.filter { isSettings($0.table) && (!coreLinkTables.contains($0.table) || $0.id.contains("#")) }let settled = settingsLinks.isEmpty ? LinkTitles() : tryawait settings.linkTitles(for: settingsLinks)var titles = settled.byIDvar pictures = settled.pictureslet localLinks = Set(settingsLinks)let rest = links.filter { !localLinks.contains($0) }guard !rest.isEmpty else { returnLinkTitles(titles, pictures: pictures) }for table inSet(rest.map(\.table)) {// A link into a table no definition names is a defect to show,// never a column quietly drawn blank.guardlet definition = definitions.first(where: { $0.id == table }) else {throwRecordsError.unknownTable(table) }tryawait 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..<min(start + Self.idsPerAsk, ids.count)]let request: [String: RecordValue] = ["table": .text(table), "ids": .list(asked.map(RecordValue.text)), "today": .text(today()), ]let rows = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)for row in rows.records { titles[row.id] = row.record.said?.slip.name pictures[row.id] = LinkTitles.picture(of: row.record, in: definition) } } }returnLinkTitles(titles, pictures: pictures) }/// `list_records`' most ids in one ask (its `MAX_PAGE_SIZE`).staticlet idsPerAsk = 200/// Each of `ids`' card as the core resolves it (`@card`), by id — what a/// source that reads its own rows draws its deck with, since its rows/// carry none. Nothing for an id the core answers no card for.publicfunc cards(table: String, ids: [String]) asyncthrows -> [String: RecordValue] {var cards: [String: RecordValue] = [:]for start in stride(from: 0, to: ids.count, by: Self.idsPerAsk) {let asked = ids[start..<min(start + Self.idsPerAsk, ids.count)]let request: [String: RecordValue] = ["table": .text(table), "ids": .list(asked.map(RecordValue.text)), "today": .text(today()), ]let rows = tryawait core.call(CottonMethod.recordsList, request, as: WirePage.self)for row in rows.records {iflet card = row.record.values[DeckCard.key], card != .null { cards[row.id] = card } } }return cards }// ── Groups ─────────────────────────────────────────────────────────────structWireGroup: Decodable {let id: Stringlet name: Stringlet table: Stringlet count: Int?let top: [WireRecord]?let holds: Bool?/// Every member's id in the group's order — a group of tools says it/// (Spec 9.2), whose page lists them.let members: [String]?/// A group that is another table's record (an album) says which.let kept_in: String?let byline: String?let `where`: [String: RecordValue]?var group: RecordGroup {RecordGroup(id: id, name: name, of: table, count: count, keptIn: kept_in, byline: byline, filter: `where`) }var stack: GroupStack { GroupStack(group: group, top: (top ?? []).map(\.record), holds: holds) } }structWireGroups: Decodable {let groups: [WireGroup] }structWireGroupWrite: Decodable {let change: WireChangelet group: WireGroup? }publicfunc groups(of table: String, holding record: String?) asyncthrows -> [GroupStack] {tryawait core.listGroups(of: table, holding: record) }publicfunc createGroup(named name: String, of table: String, records: [String]) asyncthrows -> (change: ChangeRecord, group: RecordGroup?) {tryawait core.makeGroup(named: name, of: table, records: records) }publicfunc updateGroup(_ id: String, _ change: GroupChange) asyncthrows -> ChangeRecord {tryawait core.changeGroup(id, change) }publicfunc deleteGroup(_ id: String) asyncthrows -> ChangeRecord {tryawait 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).structWireChange: Decodable {let id: Stringlet 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: Boollet reason: String?/// The core's words for what happened; absent from an older core.let receipt: ChangeSaid? }structWireWrite: Decodable {let change: WireChangelet record: WireRecord? }staticfunc change(_ answer: WireWrite) -> ChangeRecord {let change = answer.changelet record = answer.record?.recordfunc side(_ moved: [String: RecordValue]?, over base: TableRecord?) -> TableRecord? {guardlet moved, let id = change.record_id ?? base?.id else { returnnil }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"returnChangeRecord( 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) }privatefunc write(_ method: String, _ request: [String: RecordValue]) asyncthrows -> ChangeRecord {Self.change(tryawait core.call(method, request, as: WireWrite.self)) }privatefunc settingsWrite(_ write: () asyncthrows -> ChangeRecord) asyncthrows -> ChangeRecord {let change = tryawait 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`.privatestructWireCreate: Decodable {let change: WireChange?let record: WireRecord?let ask: CreateQuestion? }func continueFilePick(_ pick: RecordFilePick, file: URL) asyncthrows -> 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.guardtryawait catalogueTables().definitions.contains(where: { $0.id == pick.table && $0.engine != nil && $0.canRunCommands }) else {throwActionRefused(ShellLines.line("definitions", "refused.not_an_engine")) }tryawait refuseRefused(pick.table)let answer = tryawait core.call("records.create", pick.arguments(file: file), as: WireCreate.self)iflet 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 {throwDecodingError.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 }guardvar question = answer.ask, question.table.isEmpty || question.table == pick.table else {throwDecodingError.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 }publicfunc create(table: String, data: [String: RecordValue]) asyncthrows -> ChangeRecord {if isSettings(table) {returntryawait settingsWrite { tryawait settings.create(table: table, data: data) } }tryawait refuseRefused(table)let request: [String: RecordValue] = ["table": .text(table), "data": .object(data)]let answer = tryawait core.call("records.create", request, as: WireCreate.self)iflet change = answer.change {Self.writtenHere(table: table, data: data)returnSelf.change(WireWrite(change: change, record: answer.record)) }guardvar question = answer.ask else {throwDecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "records.create answered no change and no question")) } question.table = table question.data = datathrow question }publicfunc update(table: String, id: String, patch: [String: RecordValue]) asyncthrows -> ChangeRecord {if isSettings(table) { returntryawait settingsWrite { tryawait settings.update(table: table, id: id, patch: patch) } }tryawait refuseRefused(table)let change = tryawait 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).privatestaticfunc writtenHere(table: String, data: [String: RecordValue]) {NotificationCenter.default.post(name: .cottonRecordWrittenHere, object: nil, userInfo: ["table": table, "data": data]) }publicfunc update(table: String, id: String, patch: [String: RecordValue], scope: WriteScope?) asyncthrows -> ChangeRecord {guardlet scope else { returntryawait update(table: table, id: id, patch: patch) }tryawait refuseRefused(table)returntryawait write("records.update", ["table": .text(table), "id": .text(id), "patch": .object(patch), "scope": .text(scope.rawValue)]) }publicfunc delete(table: String, id: String, scope: WriteScope?) asyncthrows -> ChangeRecord {guardlet scope else { returntryawait delete(table: table, id: id) }tryawait refuseRefused(table)returntryawait write("records.delete", ["table": .text(table), "id": .text(id), "today": .text(today()), "scope": .text(scope.rawValue)]) }publicfunc delete(table: String, id: String) asyncthrows -> ChangeRecord {if isSettings(table) { returntryawait settingsWrite { tryawait settings.delete(table: table, id: id) } }tryawait refuseRefused(table)returntryawait write("records.delete", ["table": .text(table), "id": .text(id), "today": .text(today())]) }publicfunc reorder(table: String, ids: [String]) asyncthrows -> ChangeRecord {if isSettings(table) { returntryawait settingsWrite { tryawait settings.reorder(table: table, ids: ids) } }tryawait refuseRefused(table)returntryawait write("records.reorder", ["table": .text(table), "ids": .list(ids.map(RecordValue.text))]) }publicfunc link(table: String, id: String, column: String, target: String) asyncthrows -> ChangeRecord {if isSettings(table) {returntryawait settingsWrite { tryawait settings.link(table: table, id: id, column: column, target: target) } }tryawait refuseRefused(table)returntryawait 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.privatestructWireCapture: 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) } }publicfunc captureMedia( file: URL, mime: String, kind: CaptureMediaKind, filename: String?, forThought: Bool ) asyncthrows -> MediaCaptured {tryawaitCoreMediaCapture(core: core, forThought: forThought) .capture(file: file, mime: mime, kind: kind, filename: filename) }publicfunc keepThought( _ words: String, table: String?, recordId: String?, attachments: [CaptureAttachment] ) asyncthrows -> ChangeRecord {var request: [String: RecordValue] = ["text": .text(words)]iflet table { request["saidTable"] = .text(table) }iflet 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 = tryawait core.call(CottonMethod.captureCreate, request, as: WireCapture.self)returnSelf.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.publicfunc undo(change: String) asyncthrows -> ChangeRecord {if settingsChanges.contains(change) { returntryawait settingsWrite { tryawait settings.undo(change: change) } }returntryawait 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.publicfunc undo(changeId: String) asyncthrows -> ChangeRecord {tryawait write("records.undo", ["change_id": .text(changeId)]) }}// ── Engine commands ───────────────────────────────────────────────────────extensionCoreRecords: 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.publicfunc command(table: String, id: String, command: RecordCommand, picked: String?) asyncthrows -> ChangeRecord {tryawait refuseRefused(table)returntryawait core.recordCommand(table: table, id: id, command: command, picked: picked) }publicfunc command(table: String, id: String, command: RecordCommand, pickedValues: [String]) asyncthrows -> ChangeRecord {tryawait refuseRefused(table)returntryawait 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.publicfunc undo(_ call: CommandUndoCall, taken: CommandTaken) asyncthrows -> ChangeRecord {tryawait core.recordUndoCall(call, taken: taken) }}extensionCottonCalling {/// Every record store runs a definition's command through the same native boundary.func recordCommand(table: String, id: String, command: RecordCommand, picked: String?) asyncthrows -> ChangeRecord {tryawait 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()) asyncthrows -> ChangeRecord {let outcome: CommandOutcomelet request: [String: RecordValue] = ["table": .text(table), "id": .text(id), "command": .text(command.id), "picked": pickedValue]do { outcome = tryawait call("records.command", request, as: CommandOutcome.self) } catchlet refusal asCottonCallErrorwhere refusal.code == "vault_locked" { outcome = tryawait recordCommandWithVaultKey(request, keyring: keyring) } catchlet refusal asCottonCallError {throwActionRefused(refusal.message) }returntry 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.privatefunc recordCommandWithVaultKey(_ request: [String: RecordValue], keyring: VaultKeyring) asyncthrows -> CommandOutcome {let read = awaitTask.detached(priority: .userInitiated) { () -> Result<String, Error> indo { return .success(try keyring.privateKey()) } catch { return .failure(error) } }.valuelet key: Stringswitch read {case .success(let found): key = foundcase .failure(let error):switch error as? VaultKeyError {case .cancelled: throwCancellationError()default: throwActionRefused(ShellLines.line("passwords", "vault.phone_own_key")) } }var lent = request lent["privateKey"] = .text(key)do {returntryawait call("records.command", lent, as: CommandOutcome.self) } catchlet refusal asCottonCallError {throwActionRefused(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) asyncthrows -> ChangeRecord {let outcome: CommandOutcomedo { outcome = tryawait call("records.command", ["table": RecordValue.text(table), "command": .text(command), "count": .number(Double(count))],as: CommandOutcome.self) } catchlet refusal asCottonCallError {throwActionRefused(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) })iflet 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) asyncthrows -> ChangeRecord {let said: UndoCallSaiddo {let args = try JSONDecoder().decode(JSONValue.self, from: Data(call.args.utf8)) said = tryawaitself.call(call.method, args, as: UndoCallSaid.self) } catchlet refusal asCottonCallError {throwActionRefused(refusal.message) }returnChangeRecord( 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.structUndoCallSaid: Decodable {let receipt: String?}/// `records.command`'s answer: `{command, kind, receipt, undo, answer, open}`.structCommandOutcome: Decodable {structOpen: Decodable {let table: String?let id: String?let url: String?/// The record comes by sync (`RecordCommand.lands`).let by_sync: Bool? }structAnswer: Decodable {let write: CoreRecords.WireWrite?let pending: Boollet 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.ifcase .object(let fields) = value, let waiting = fields["pending"] {switch waiting {case .number: pending = falsecase .bool(let isPending) where !isPending || fields["change"] == nil || fields["change"] == .null: pending = isPendingdefault:throwDecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A pending command has a boolean state and no completed change")) } } else { pending = false }ifcase .object = value { platformAction = tryRecordPlatformAction.fromAnswer(decoder) }else { platformAction = nil }ifcase .object(let fields) = value, case .string(let shown)? = fields["shows_database"], !shown.isEmpty { showsDatabase = shown } else { showsDatabase = nil }ifcase .object(let fields) = value, let asked = fields["ask"], asked != .null {guardcase .object(let continuation) = asked,case .object? = continuation["data"], fields["change"] == nil || fields["change"] == .nullelse {throwDecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A command question must carry create data and no change")) }structQuestion: Decodable { let ask: CreateQuestion }var question = tryQuestion(from: decoder).askguard !question.table.isEmpty else {throwDecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "A command question must name its create table")) } question.openCreated = true ask = question write = nil } elseifcase .object(let fields) = value, let change = fields["change"], change != .null { write = tryCoreRecords.WireWrite(from: decoder) ask = nil } else { write = nil ask = nil } } }/// An app method's own way back: `{method, args}`.structUndoCall: Decodable {let method: Stringlet args: JSONValue }let command: Stringlet kind: String?let receipt: String?let undo: String?letopen: Open?let answer: Answer?let undo_call: UndoCall?/// A value shown once (`RecordCommand.reveals`).let reveal: Reveal?structReveal: Decodable {let title: Stringlet value: Stringlet 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? {guardlet call = undo_call, let args = try? JSONEncoder().encode(call.args) else { returnnil }returnCommandUndoCall(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 {iflet question = answer?.ask { throw question }iflet 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.iflet undoCall { change.command = CommandTaken(table: table, record: record, undo: undo, undoCall: undoCall) }iflet 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.iflet 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?iflet shown = answer?.showsDatabase { opened = .database(shown) } elseiflet effect = answer?.platformAction { opened = .platform(effect) } elseiflet target = open?.table, let id = open?.id { opened = open?.by_sync == true ? .landed(RecordLink(table: target, id: id)) : .record(RecordLink(table: target, id: id)) } elseiflet url = open?.url { opened = .address(url) }let pending = answer?.pending == truevar 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 = pendingreturn 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.extensionCoreRecords: ActingRecords, CreationRecords {func prepareCreation(table: String, where filter: [String: RecordValue]) asyncthrows {if isSettings(table) { tryawait settings.prepareCreation(table: table, where: filter) } }publicfunc permitsCreation(table: String, where filter: [String: RecordValue]) async -> Bool { isSettings(table) ? await settings.permitsCreation(table: table, where: filter) : true }publicfunc listActions(table: String) async -> [RecordAction] {await listActions(table: table, where: [:]) }publicfunc listActions(table: String, where filter: [String: RecordValue]) async -> [RecordAction] {if isSettings(table) { returnawait settings.listActions(table: table, where: filter) }returnawait 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.privatefunc 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 inguardlet count = command.offered(over: rows) else { returnnil }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) }returnRecordAction(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.privatefunc everyRow(_ table: String, where filter: [String: RecordValue]) asyncthrows -> [TableRecord] {var rows: [TableRecord] = []var page = 0whiletrue {let read = tryawait list(table: table, project: nil, query: nil, page: page, where: filter, limit: Self.idsPerAsk) rows += read.recordsguardlet next = read.next, next != page else { return rows } page = next } }publicfunc 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) }publicfunc slipActions(table: String, record: TableRecord) async -> [RecordAction] { isSettings(table) ? await settings.slipActions(table: table, record: record) : [] }publicfunc perform(_ action: RecordAction, table: String, record: TableRecord?) asyncthrows -> ActionOutcome {tryawait perform(action, values: [:], table: table, record: record) }publicfunc perform(_ action: RecordAction, values: [String: String], table: String, record: TableRecord?)asyncthrows -> ActionOutcome {if isSettings(table) { returntryawait settings.perform(action, values: values, table: table, record: record) }guard record == nil, let count = action.count, let command = action.commandID else {throwSettingsRecordsError.refusedVerb(table: table, verb: action.id) }tryawait refuseRefused(table)let change = tryawait core.recordListCommand(table: table, command: command, count: count)// A list act that opens a kept flow (Approve a request) hands it on.ifcase .platform(.openFlow(let flow))? = change.opened { return .flow(flow.flow.kept) }return .change(change) }publicfunc listNote(table: String) async -> String? { isSettings(table) ? await settings.listNote(table: table) : nil }}extensionCoreRecords: 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.extensionCottonCalling {func listGroups(of table: String, holding record: String?) asyncthrows -> [GroupStack] {var request: [String: RecordValue] = ["table": .text(table)]iflet record { request["record"] = .text(record) }returntryawait 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) asyncthrows -> [String] {let request: [String: RecordValue] = ["table": .text(table)]let groups = tryawait call(CottonMethod.groupsList, request, as: CoreRecords.WireGroups.self).groupsreturn groups.first { $0.id == id }?.members ?? [] }func makeGroup(named name: String, of table: String, records: [String]) asyncthrows -> (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 = tryawait 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) asyncthrows -> ChangeRecord {let answer = tryawait call(CottonMethod.groupsUpdate, group.request(id: id), as: CoreRecords.WireGroupWrite.self)returnCoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil)) }func binGroup(_ id: String) asyncthrows -> ChangeRecord {let request: [String: RecordValue] = ["id": .text(id)]let answer = tryawait call(CottonMethod.groupsDelete, request, as: CoreRecords.WireGroupWrite.self)returnCoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil)) }/// A group change taken back: the core's one undo.func undoGroupChange(_ id: String) asyncthrows -> ChangeRecord {CoreRecords.change(tryawait call("records.undo", ["change_id": RecordValue.text(id)], as: CoreRecords.WireWrite.self)) }}extensionCoreRecords: RecordFileCommands {}