// Relationships and existing engine commands are definition data. An engine// adapter implements the command protocol; fixture stores cannot run commands.importCottonValuesimportFoundationimportCottonKitpublictypealiasRelatedRecords = DefinitionRelatedRecordsextensionDefinitionRelatedRecords {publicinit( label: String, table: String, column: String? = nil, filter: [String: RecordValue]? = nil, new: Bool? = nil, archived: Bool? = nil, open: String? = nil, title: String? = nil, empty: EmptyWords? = nil, when: [String: RecordValue]? = nil ) {self.init(_generated: (), label: label, table: table)self.column = columnself.filter = filterself.new = newself.archived = archivedself.open = openself.title = titleself.empty = emptyself.when = when }publicfunc applies(to record: TableRecord) -> Bool { (when ?? [:]).allSatisfy { key, wanted in record[key] == wanted } }/// The table as this list draws it: under its own title and empty words,/// with none of the table's list-level links or its "+" — those belong to/// the table's own list, and an archive that offered "Archived chats" again/// would lead to itself.publicfunc listed(_ definition: TableDefinition) -> TableDefinition {guard title != nil || empty != nilelse { return definition }var copy = definitioniflet title { copy.plural = title }iflet empty { copy.empty = empty } copy.related = definition.related?.filter { $0.column != nil } copy.create = nilreturn copy }publicfunc whereValues(parent: TableRecord) -> [String: RecordValue] {var values = filter ?? [:]iflet column { values[column] = .text(parent.id) }return values }}/// What a command is: the core's closed list (`commands.rs`).publictypealiasCommandKind = DefinitionCommandKind/// What an act does to its record — the definition's `does` — which decides/// its card's colour the same way in every tool, so a person learns it once/// (architect, 13 Oct 2026): it completes or affirms, moves the record in/// time, moves it in place or hands it over, destroys it, or puts it away./// Everything else is said by no word at all.publictypealiasCommandDoes = DefinitionCommandDoesprivateenumCommandConditionOperator: String { case not }/// One value the command asks the person to choose before the engine runs./// The engine binds `argument`; Swift sends only the chosen value as `picked`.publictypealiasRecordCommandPick = DefinitionCommandPickextensionDefinitionCommandPick {publictypealiasKind = DefinitionPickKind/// The filter a record pick lists its choices by, for an act on the record/// `id`: a value `"$id"` is that record's own id (a dish's Order offers its/// own menu days) — the core's `CommandPick::accepts_on`.publicfunc filter(on id: String?) -> [String: RecordValue] {func at(_ value: RecordValue) -> RecordValue {ifcase .text("$id") = value, let id { return .text(id) }return value }return (filter ?? [:]).mapValues { value inifcase .list(let any) = value { return .list(any.map(at)) }return at(value) } }publicinit( argument: String, kind: Kind, table: String? = nil, filter: [String: RecordValue]? = nil, choicesFrom: String? = nil, databaseBy: String? = nil, optional: Bool? = nil, min: Double? = nil, defaultValue: Double? = nil, max: Double? = nil ) {self.init(_generated: (), argument: argument, kind: kind)self.table = tableself.filter = filterself.choicesFrom = choicesFromself.databaseBy = databaseByself.optional = optionalself.min = minself.defaultValue = defaultValueself.max = max }publicfunc database(in record: TableRecord?) throws -> String? {guardlet databaseBy else { returnnil }let id = databaseBy == "$id" ? record?.id : record?[databaseBy].textguardlet id, !id.isEmpty else { throwActionRefused(ShellLines.line("definitions", "refused.no_database")) }return id }}/// A list's act: offered at the head of the list while at least this many/// listed rows are ones its `when` holds on (`RecordCommand::list`).publictypealiasRecordCommandList = DefinitionCommandListextensionDefinitionCommandList {publicinit(atLeast: Int = 1) { self.init(_generated: (), atLeast: atLeast) }}publictypealiasRecordCommand = DefinitionRecordCommandextensionRecordCommand {publicstaticvar copySealed: String { "$sealed" }publicinit(id: String, label: String, sheet: String? = nil, verb: String? = nil, method: String? = nil, kind: CommandKind? = nil, opens: String? = nil, copies: String? = nil, receipt: String? = nil, undo: String? = nil, data: [String: RecordValue]? = nil, destructive: Bool? = nil, confirm: String? = nil, bindings: [String: String]? = nil, when: [String: RecordValue]? = nil, pickTable: String? = nil, pick: RecordCommandPick? = nil, picks: [RecordCommandPick]? = nil, doesWord: String? = nil, object: String? = nil, form: Bool? = nil, reveals: RecordCommandReveal? = nil) {self.init(_generated: (), id: id, label: label)self.id = idself.label = labelself.sheet = sheetself.verb = verbself.method = methodself.kind = kindself.opens = opensself.copies = copiesself.receipt = receiptself.undo = undoself.data = dataself.destructive = destructiveself.confirm = confirmself.bindings = bindingsself.when = whenself.pickTable = pickTableself.pick = pickself.picks = picksself.doesWord = doesWordself.object = objectself.form = formself.reveals = reveals }publicvar needsPick: Bool { pickTable != nil || pick != nil || picks?.isEmpty == false }publicvar isForm: Bool { form == true }publicvar does: CommandDoes? { doesWord.flatMap(CommandDoes.init(rawValue:)) }/// Where a list act's words say how many rows it is for.publicstaticvar countWord: String { "{count}" }/// How many of a list's `rows` this list act is for, when it is offered/// over them: those its `when` holds on, at least `list.atLeast` of them/// (`RecordCommand::offered_over`). `nil` for a record's act.publicfunc offered(over rows: [TableRecord]) -> Int? {guardlet list else { returnnil }var record = self record.list = nillet count = rows.filter(record.applies(to:)).countreturn count >= list.atLeast ? count : nil }/// `words` saying `count` where they say `{count}`.publicstaticfunc counted(_ words: String, _ count: Int) -> String { words.replacingOccurrences(of: countWord, with: String(count)) }/// Offered while every `when` holds — and, for an `open`, while its/// column holds something to open (the core refuses it otherwise).publicfunc applies(to record: TableRecord) -> Bool {// The form's act is the form's alone: a kept record never offers it,// and a list's act is the list's.if isForm || list != nil { returnfalse }if kind == .open, opens.map({ RecordValue.isBlank(record[$0]) }) != false { returnfalse }if kind == .copy, let copies, copies != Self.copySealed, RecordValue.isBlank(record[copies]) { returnfalse }return (when ?? [:]).allSatisfy { key, wanted inlet held = record[key]let matches = { (value: RecordValue) in held == value || (held == .null && value == .bool(false)) }ifcase .object(let object) = wanted, object.count == 1, let excluded = object[CommandConditionOperator.not.rawValue] {ifcase .list(let choices) = excluded { return !choices.contains(where: matches) }return !matches(excluded) }ifcase .list(let choices) = wanted { return choices.contains(where: matches) }return matches(wanted) } }/// Whether the command asks before it runs: every delete, and any command/// its definition marks destructive, confirmed or as one that destroys./// The one way a surface learns it — no surface reads `destructive` itself.publicvar asksFirst: Bool { kind == .delete || destructive == true || confirm != nil || does == .destroys }publicfunc arguments(for record: TableRecord) -> [String: RecordValue] {var args = data ?? [:]for (argument, column) in bindings ?? [:] {if column == "$id_list" { args[argument] = .list([.text(record.id)]) } else { args[argument] = column == "$id" ? .text(record.id) : record[column] } }return args }}/// What a command shows once from its method's answer: the answer's key,/// the heading over the value and why it will not be shown again.publictypealiasRecordCommandReveal = DefinitionCommandRevealextensionDefinitionCommandReveal {publicinit(answer: String, title: String, note: String) {self.init(_generated: (), answer: answer, title: title, note: note) }}publicprotocolRecordCommands: Records {/// The engine owns atomic provenance, validation and change receipts./// `picked` is the chosen table, record id, or ISO 8601 instant.func command(table: String, id: String, command: RecordCommand, picked: String?) asyncthrows -> ChangeRecord/// Ordered answers for a package act; the writer resolves their typed arguments.func command(table: String, id: String, command: RecordCommand, pickedValues: [String]) asyncthrows -> ChangeRecord/// An app method's own way back (`CommandTaken.undoCall`). A store that/// runs no app methods has none to take.func undo(_ call: CommandUndoCall, taken: CommandTaken) asyncthrows -> ChangeRecord}extensionRecordCommands {publicfunc command(table: String, id: String, command: RecordCommand) asyncthrows -> ChangeRecord {tryawaitself.command(table: table, id: id, command: command, picked: nil) }publicfunc command(table: String, id: String, command: RecordCommand, pickedValues: [String]) asyncthrows -> ChangeRecord {throwActionRefused(ShellLines.line("definitions", "refused.not_here")) }publicfunc undo(_ call: CommandUndoCall, taken: CommandTaken) asyncthrows -> ChangeRecord {throwChangeUndoError.unavailable }}extensionTableDefinition {/// Native commands and typed package acts both run through records.command.publicvar canRunCommands: Bool { (engine != nil || !(acts ?? []).isEmpty) && !(commands ?? []).isEmpty }/// The command this table binds to `mark` drawn over a card (`marks`),/// while it applies to `record` as it stands: nil where the table binds/// nothing to it, or the record is past it (a todo already done).func command(forMark mark: String, on record: TableRecord) -> RecordCommand? {guard canRunCommands, let id = marks?[mark] else { returnnil }return ((commands ?? []) + (acts ?? [])).first { $0.id == id && $0.applies(to: record) } }}extensionRecordCommand {/// What a command that did not run says: the core's own sentence/// ("“Open person” is not offered on this record as it stands now."),/// else the plain one.staticfunc refusal(_ error: Error) -> String {iflet refused = error as? ActionRefused, !refused.sentence.isEmpty { return refused.sentence }iflet refused = error as? CottonCallError, !refused.message.isEmpty { return refused.message }returnShellLines.line("definitions", "refused.not_completed") }/// The menu line's symbol, by what the command is called.var symbol: String? {switch id {case"pin": "pin"case"unpin": "pin.slash"case"mute": "bell.slash"case"unmute": "bell"case"archive": "archivebox"case"unarchive": "tray.and.arrow.up"case"clear": "trash"default: nil } }}