Cotton code
876 lines · 40.9 KB · SwiftRaw
// A business app's phone against its business's object (Sharmila's Yoga Zone,// Nancy's Naga Kitchen): one Cloudflare Worker object per business, reached// through the core's `business.*` methods (`crates/cotton-ffi/src/phone/// business.rs`). The object decides everything — who may read what, what an// act does, whether it is taken — and the core keeps this phone's cache of// what the credential's role may see. This file asks and decodes; it decides// nothing about the business's data.//// Cotton itself is the same client at the open host (`cottondb.com`): an// address with no slug, where `personal.code` finds the number's own database// (making it on a first sign-in) and `personal.signIn` proves the code there.// The database id the sign-in names is kept with the credential, so a later// launch connects its copy with no network (`personal.connect`).//// **The credential lives in the Keychain and nowhere else.** It crosses the// boundary once, inward, in the sign-in's answer, and goes straight into// one Keychain slot (one per business, by its slug; one for Cotton); every later call reads it// back out of that slot onto the request's `credential` field and nowhere// else. `BusinessSession` holds it privately, says nothing of it when// described, mirrored or dumped, and is not `Encodable`, so no log line,// definition or JSON can carry it. A refusal that says the object no longer// takes it (`credential_revoked`, `credential_expired`, `invalid_credential`)// forgets it here.import CottonValuesimport Foundationextension CottonMethod {    /// Pull the business's definitions and the rows the credential's role    /// may see into the core's cache.    public static let businessSync = "business.sync"    /// Every view the cached role reads, with its rows drawn: no network.    public static let businessPages = "business.pages"    /// Ask the business for a code for a number.    public static let businessCode = "business.code"    /// Sign in with that code; the answer carries the credential.    public static let businessSignIn = "business.signIn"    /// Sign out at the business; the cache starts over as a stranger's.    public static let businessSignOut = "business.signOut"    /// Ask the open host for a code for a number: its own database, made on    /// its first sign-in.    public static let personalCode = "personal.code"    /// Sign in at that database with the code; the answer carries the    /// credential and the database id.    public static let personalSignIn = "personal.signIn"    /// Make the person's own personal object this phone's database: its copy,    /// its connection, and the sync loop's far end.    public static let personalConnect = "personal.connect"    /// A local database a person used, brought into their object: started    /// at once, the rows going up on the core's own thread.    public static let personalAdopt = "personal.adopt"    /// Where that adopt stands: sending, making the copy, done or failed.    public static let personalAdoptStatus = "personal.adoptStatus"    /// This phone keeps whatever copy it holds as its local database and    /// dials the object no more.    public static let personalStandLocal = "personal.standLocal"    public static let shellAccount = "shell.account"    /// The copy this phone holds is deleted, so a fresh local start follows.    public static let personalRemove = "personal.remove"    /// Post one act to the business's object.    public static let businessAct = "business.act"}/// Where one business's object answers: the Worker's address and the/// business's slug, as the manifest names them (`FlavourManifest.business`)./// No slug is the open host (Cotton's `https://cottondb.com`), where the/// sign-in finds the person's own database. `window` is what a phone keeping/// a copy keeps only the newest days of, `{table: days}` (Cotton's messages).////// A manifest names `server` once, or once per side of the build —/// `{"real": …, "dev": …}` — and the address is the side's this build is/// (`AppFlavor`, `COTTON_FLAVOR`): Cotton signs in at cottondb.com and Cotton/// Dev at the dev Worker (`apps/business/wrangler.jsonc` `env.dev`; owner,/// 29 Oct 2026), the manifest the one place either is written. A side the/// manifest does not name is a build that does not open.public struct BusinessAddress: Codable, Equatable, Sendable {    public var server: String    public var slug: String?    public var window: [String: Int]?    public init(server: String, slug: String? = nil, window: [String: Int]? = nil) {        self.server = server        self.slug = slug        self.window = window    }    private enum CodingKeys: String, CodingKey { case server, slug, window }    /// The decoder's `userInfo` key for the side a two-sided `server` is read    /// for; absent, this build's own (`AppFlavor.current`).    public static let side = CodingUserInfoKey(rawValue: "cotton.business.side")!    public init(from decoder: Decoder) throws {        let keys = try decoder.container(keyedBy: CodingKeys.self)        slug = try keys.decodeIfPresent(String.self, forKey: .slug)        window = try keys.decodeIfPresent([String: Int].self, forKey: .window)        if let one = try? keys.decode(String.self, forKey: .server) {            server = one            return        }        let sides = try keys.decode([String: String].self, forKey: .server)        let side = decoder.userInfo[Self.side] as? AppFlavor ?? AppFlavor.current        guard let server = sides[side.rawValue] else {            throw DecodingError.dataCorruptedError(forKey: .server, in: keys, debugDescription: "the business names no server for the \(side.rawValue) side")        }        self.server = server    }}/// What `personal.connect` made this phone's: the object's database and its/// owner — or, when the phone's own local database holds rows a person made,/// the adopt that brings them into the object, started (`personal.adopt`).public struct PersonalConnected: Decodable, Equatable, Sendable {    public let databaseId: String?    public let ownerId: String?    public let adopt: PersonalAdopt?    public init(databaseId: String?, ownerId: String? = nil, adopt: PersonalAdopt? = nil) {        self.databaseId = databaseId        self.ownerId = ownerId        self.adopt = adopt    }}/// `personal.adopt`'s answer and `personal.adoptStatus`'s: the rows a/// person made on this phone before backup and where bringing them into the/// object stands — `started`, `sending`, `making_copy`, `done` or `failed`/// (with the object's word), `none` when no adopt ran this launch.public struct PersonalAdopt: Decodable, Equatable, Sendable {    public let status: String    public let rows: Int    public let sent: Int    public let refused: Int    public let code: String?    public init(status: String, rows: Int, sent: Int = 0, refused: Int = 0, code: String? = nil) {        self.status = status        self.rows = rows        self.sent = sent        self.refused = refused        self.code = code    }    private enum Keys: String, CodingKey { case status, rows, sent, refused, code }    public init(from decoder: any Decoder) throws {        let keys = try decoder.container(keyedBy: Keys.self)        status = try keys.decode(String.self, forKey: .status)        rows = try keys.decodeIfPresent(Int.self, forKey: .rows) ?? 0        sent = try keys.decodeIfPresent(Int.self, forKey: .sent) ?? 0        refused = try keys.decodeIfPresent(Int.self, forKey: .refused) ?? 0        code = try keys.decodeIfPresent(String.self, forKey: .code)    }    public static let started = "started"    public static let sending = "sending"    public static let makingCopy = "making_copy"    public static let done = "done"    public static let failed = "failed"    public static let none = "none"    /// Whether the rows are still on their way.    public var underway: Bool { [Self.started, Self.sending, Self.makingCopy].contains(status) }}/// A sign-in to an account set to be deleted (`personal.signIn`'s `deleting`, DELETE_ACCOUNT.md "(30 days)"): the/// core's words, and what Keep needs to go on. Nothing of it is kept until the person chooses.public struct AccountSetToGo: Error, Equatable, Sendable {    public struct Words: Decodable, Equatable, Sendable {        public let eraseAt: String?        public let date: String?        public let heading: String        public let line: String        public let keep: String        public let leave: String    }    public let words: Words    let server: String    let credential: String    let person: BusinessPerson    let expiresIn: Int    let databaseId: String?    let phone: String    public init(words: Words, server: String, credential: String, person: BusinessPerson, expiresIn: Int, databaseId: String?, phone: String) {        self.words = words        self.server = server        self.credential = credential        self.person = person        self.expiresIn = expiresIn        self.databaseId = databaseId        self.phone = phone    }}/// Who the object takes the credential's holder for.public enum BusinessRole: String, Codable, Equatable, Sendable {    case `public`, member, staff, owner    public init(from decoder: Decoder) throws {        self = BusinessRole(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .public    }}/// The signed-in person, as the object names them.public struct BusinessPerson: Codable, Equatable, Sendable {    public let id: String    public let phone: String?    public let name: String?    public let role: BusinessRole?    public init(id: String, phone: String? = nil, name: String? = nil, role: BusinessRole? = nil) {        self.id = id        self.phone = phone        self.name = name        self.role = role    }}/// The business itself, as its definitions name it.public struct BusinessFacts: Decodable, Equatable, Sendable {    public let slug: String?    public let name: String?    public let currency: String?    public let timezone: String?    public let upiId: String?    enum CodingKeys: String, CodingKey {        case slug, name, currency, timezone        case upiId = "upi_id"    }}/// Everything the phone shows, read from the cache (`business.pages`): each/// tool the role reads, each of its views with its rows drawn.public struct BusinessPages: Decodable, Equatable, Sendable {    public let business: BusinessFacts?    public let role: BusinessRole    public let person: BusinessPerson?    public let version: Int    /// Where photos are fetched: a photo column holds a key, shown from    /// `photos + key`.    public let photos: String    public let tools: [BusinessTool]    public init(business: BusinessFacts? = nil, role: BusinessRole = .public, person: BusinessPerson? = nil, version: Int = 0,                photos: String = "", tools: [BusinessTool] = []) {        self.business = business        self.role = role        self.person = person        self.version = version        self.photos = photos        self.tools = tools    }    /// The address a photo column's `key` is shown from: the object's    /// photos route with the key after it.    public func photo(_ key: String) -> URL? {        Self.photo(key, at: photos)    }    public static func photo(_ key: String, at photos: String) -> URL? {        guard !key.isEmpty, !photos.isEmpty else { return nil }        let path = key.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? key        return URL(string: photos + path)    }    /// Every row any view holds, each once: what a record pick offers.    public var rows: [BusinessRow] {        var seen = Set<String>()        return tools.flatMap { $0.views.flatMap(\.rows) }.filter { seen.insert($0.table + "/" + $0.id).inserted }    }}/// One tool the role reads: its picture and stock as its definition names/// them, and the views of it the role may read.public struct BusinessTool: Decodable, Equatable, Sendable {    public let tool: String    public let name: String    public let picture: JSONValue?    public let cardStock: String?    public let views: [BusinessView]    enum CodingKeys: String, CodingKey {        case tool, name, picture, views        case cardStock = "card_stock"    }    public init(tool: String, name: String, picture: JSONValue? = nil, cardStock: String? = nil, views: [BusinessView] = []) {        self.tool = tool        self.name = name        self.picture = picture        self.cardStock = cardStock        self.views = views    }}/// One view: its label, who reads it, its table and its rows in its order.public struct BusinessView: Decodable, Equatable, Sendable, Identifiable {    public let id: String    public let label: String    public let visibility: String?    public let isDefault: Bool?    public let face: JSONValue?    public let table: String    public let count: Int    public let rows: [BusinessRow]    /// The day a view kept to its next day keeps (YYYY-MM-DD), when the core    /// names it: its label is that day's weekday ("Monday"), never "Next    /// class day", as the staff's ring says it (`ToolView.day`).    public let day: String?    enum CodingKeys: String, CodingKey {        case id, label, visibility, face, table, count, rows, day        case isDefault = "is_default"    }    public init(id: String, label: String, table: String, rows: [BusinessRow] = [], visibility: String? = nil,                isDefault: Bool? = nil, face: JSONValue? = nil, day: String? = nil) {        self.id = id        self.label = day.flatMap { CottonDate.weekday(of: $0) } ?? label        self.visibility = visibility        self.isDefault = isDefault        self.face = face        self.table = table        self.count = rows.count        self.rows = rows        self.day = day    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        let day = try c.decodeIfPresent(String.self, forKey: .day)        id = try c.decode(String.self, forKey: .id)        let declared = try c.decode(String.self, forKey: .label)        label = day.flatMap { CottonDate.weekday(of: $0) } ?? declared        visibility = try c.decodeIfPresent(String.self, forKey: .visibility)        isDefault = try c.decodeIfPresent(Bool.self, forKey: .isDefault)        face = try c.decodeIfPresent(JSONValue.self, forKey: .face)        table = try c.decode(String.self, forKey: .table)        rows = try c.decodeIfPresent([BusinessRow].self, forKey: .rows) ?? []        count = try c.decodeIfPresent(Int.self, forKey: .count) ?? rows.count        self.day = day    }}/// One row as a page draws it: its data whole (its table's card under/// `@card`), its slip's title and line, its owner, and the acts the role/// takes on it, as the core worked them out from the object's rules.public struct BusinessRow: Decodable, Equatable, Sendable, Identifiable {    public let table: String    public let id: String    public let data: [String: JSONValue]    public let title: String    public let line: String?    public let owner: String?    public let acts: [BusinessAct]    enum CodingKeys: String, CodingKey { case table, id, data, title, line, owner, acts }    public init(table: String, id: String, data: [String: JSONValue] = [:], title: String, line: String? = nil,                owner: String? = nil, acts: [BusinessAct] = []) {        self.table = table        self.id = id        self.data = data        self.title = title        self.line = line        self.owner = owner        self.acts = acts    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        table = try c.decode(String.self, forKey: .table)        id = try c.decode(String.self, forKey: .id)        data = try c.decodeIfPresent([String: JSONValue].self, forKey: .data) ?? [:]        title = try c.decodeIfPresent(String.self, forKey: .title) ?? ""        line = try c.decodeIfPresent(String.self, forKey: .line)        owner = try c.decodeIfPresent(String.self, forKey: .owner)        acts = try c.decodeIfPresent([BusinessAct].self, forKey: .acts) ?? []    }}/// One act the role takes on a row: its label and kind as its definition says/// them, and what to post — `act` with `args`, each pick's answer put at its/// `argument` (`arguments(answering:)`).public struct BusinessAct: Decodable, Equatable, Sendable, Identifiable {    public let id: String    public let label: String    public let kind: String?    public let confirm: String?    public let act: String    public let args: [String: JSONValue]    public let picks: [BusinessPick]    /// The one act the core ranks first and prints on the brand's fill (a    /// session's Book).    public let primary: Bool    /// It takes the thing away (a cancel): the core ranks it last, red.    public let red: Bool    /// The picture the core paints it with, where there is one.    public let icon: String?    enum CodingKeys: String, CodingKey { case id, label, kind, confirm, act, args, picks, primary, red, icon }    public init(id: String, label: String, kind: String? = nil, confirm: String? = nil, act: String,                args: [String: JSONValue] = [:], picks: [BusinessPick] = [], primary: Bool = false, red: Bool = false,                icon: String? = nil) {        self.primary = primary        self.red = red        self.icon = icon        self.id = id        self.label = label        self.kind = kind        self.confirm = confirm        self.act = act        self.args = args        self.picks = picks    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        id = try c.decode(String.self, forKey: .id)        label = try c.decode(String.self, forKey: .label)        kind = try c.decodeIfPresent(String.self, forKey: .kind)        confirm = try c.decodeIfPresent(String.self, forKey: .confirm)        act = try c.decode(String.self, forKey: .act)        args = try c.decodeIfPresent([String: JSONValue].self, forKey: .args) ?? [:]        picks = try c.decodeIfPresent([BusinessPick].self, forKey: .picks) ?? []        primary = try c.decodeIfPresent(Bool.self, forKey: .primary) ?? false        red = try c.decodeIfPresent(Bool.self, forKey: .red) ?? false        icon = try c.decodeIfPresent(String.self, forKey: .icon)    }    /// It takes the thing away: drawn red, as the core ranked it.    public var destroys: Bool { red }    /// The act's `args` with each pick's answer (in the picks' order) put at    /// its `argument` — a dotted argument (`data.customer`) inside its    /// object. A number is sent as a number; an optional pick left empty is    /// not sent. Nil when an answer is missing or a number does not read.    public func arguments(answering answers: [String]) -> [String: JSONValue]? {        var args = args        for (index, pick) in picks.enumerated() {            let answer = answers.indices.contains(index) ? answers[index].trimmingCharacters(in: .whitespacesAndNewlines) : ""            if answer.isEmpty {                if pick.optional == true { continue }                return nil            }            let value: JSONValue            if pick.kind == "number" {                guard let number = Double(answer), number.isFinite else { return nil }                value = .number(number)            } else {                value = .string(answer)            }            Self.put(value, at: pick.argument.split(separator: ".").map(String.init), into: &args)        }        return args    }    private static func put(_ value: JSONValue, at path: [String], into object: inout [String: JSONValue]) {        guard let first = path.first else { return }        guard path.count > 1 else {            object[first] = value            return        }        var inner: [String: JSONValue]        if case .object(let held)? = object[first] { inner = held } else { inner = [:] }        put(value, at: Array(path.dropFirst()), into: &inner)        object[first] = .object(inner)    }}/// One pick an act asks before it is posted: what `arguments` needs of it.public struct BusinessPick: Decodable, Equatable, Sendable {    public let argument: String    public let kind: String    public let label: String?    public let table: String?    public let min: Double?    public let max: Double?    public let `default`: Double?    public let optional: Bool?    enum CodingKeys: String, CodingKey { case argument, kind, label, table, min, max, `default`, optional }    public init(argument: String, kind: String, label: String? = nil, table: String? = nil, min: Double? = nil,                max: Double? = nil, default: Double? = nil, optional: Bool? = nil) {        self.argument = argument        self.kind = kind        self.label = label        self.table = table        self.min = min        self.max = max        self.default = `default`        self.optional = optional    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        argument = try c.decode(String.self, forKey: .argument)        kind = try c.decode(String.self, forKey: .kind)        label = try c.decodeIfPresent(String.self, forKey: .label)        table = try c.decodeIfPresent(String.self, forKey: .table)        min = try c.decodeIfPresent(Double.self, forKey: .min)        max = try c.decodeIfPresent(Double.self, forKey: .max)        self.default = try c.decodeIfPresent(Double.self, forKey: .default)        optional = try c.decodeIfPresent(Bool.self, forKey: .optional)    }}/// What a sync pulled: the version it reached, how many rows changed, and/// whom the object takes this phone for.public struct BusinessSynced: Decodable, Equatable, Sendable {    public let version: Int    public let changed: Int    public let role: BusinessRole    public let person: BusinessPerson?}/// What an act made: the version it reached and the rows it changed, already/// in the cache.public struct BusinessActed: Decodable, Equatable, Sendable {    public let version: Int    public let made: JSONValue?    public let notices: JSONValue?}/// The business's answer to a number: the challenge to sign in against. The/// code itself is the person's to type.public struct BusinessChallenge: Decodable, Equatable, Sendable {    public let challengeId: String    public let expiresIn: Int?    /// Whether the business knows the number; a number it has not met is    /// asked a name with the code, so the person's card carries one.    public let known: Bool?    /// At the open host, the number's own database: the code is proved there.    public let databaseId: String?    /// Where the code went, in the core's words, the number masked (NEXT-SIGNIN, 28 Nov 2026): the card says it as is.    public let sentTo: String?    public init(challengeId: String, expiresIn: Int? = nil, known: Bool? = nil, databaseId: String? = nil, sentTo: String? = nil) {        self.challengeId = challengeId        self.expiresIn = expiresIn        self.known = known        self.databaseId = databaseId        self.sentTo = sentTo    }}/// What a code sign-in came to: signed in, or (the number having no account yet) the name to ask before it is made.public enum BusinessSignInStep: Sendable {    case signedIn(BusinessSession)    /// The code is proved and the number has no account: the card asks the name, then sends the same code with it.    case nameNeeded}/// Who is signed in, as the Keychain holds it.public struct BusinessSession: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {    /// The number as it was typed at sign-in; the person's own from the object.    public let phone: String?    public let person: BusinessPerson    /// Seconds since 1970 the credential stops being taken.    public let expiresAt: Int    /// At the open host, the database the credential names: kept with it, so    /// a later launch (or a reinstall) connects without asking anyone.    public let databaseId: String?    private let credential: String    fileprivate init(phone: String?, person: BusinessPerson, expiresAt: Int, databaseId: String?, credential: String) {        self.phone = phone        self.person = person        self.expiresAt = expiresAt        self.databaseId = databaseId        self.credential = credential    }    public var description: String { "BusinessSession(\(person.id))" }    public var debugDescription: String { description }    public var customMirror: Mirror {        Mirror(self, children: ["phone": phone as Any, "person": person, "expiresAt": expiresAt, "databaseId": databaseId as Any])    }    /// The Keychain's copy: the one place the credential is written.    fileprivate struct Kept: Codable {        let phone: String?        let person: BusinessPerson        let expiresAt: Int        let databaseId: String?        let credential: String    }    fileprivate var kept: Kept { Kept(phone: phone, person: person, expiresAt: expiresAt, databaseId: databaseId, credential: credential) }    fileprivate var bearer: String { credential }}/// One business's object, through the core. Never on the main thread: the/// Keychain read blocks (`SecretStore`).public struct BusinessClient: Sendable {    private let core: any CottonCalling    public let address: BusinessAddress    private let store: any SecretStore    private let now: @Sendable () -> Date    /// The core the client asks, for a pick asked of its cache (`DeckPicking`).    public var calling: any CottonCalling { core }    /// The object, as a pick names it to the core.    public var addressed: JSONValue {        var said: [String: JSONValue] = ["server": .string(address.server)]        if let slug = address.slug { said["slug"] = .string(slug) }        return .object(said)    }    public init(core: any CottonCalling, address: BusinessAddress, store: any SecretStore = KeychainSecretStore(),                now: @escaping @Sendable () -> Date = Date.init) {        self.core = core        self.address = address        self.store = store        self.now = now    }    /// The Keychain slot one business's session is kept in; Cotton's, at the    /// open host, is its own.    public static func slot(_ address: BusinessAddress) -> String {        address.slug.map { "business-session.\($0)" } ?? "personal-session"    }    /// Who is signed in: nil when nobody is, or the credential has lapsed    /// (a lapsed one is forgotten, so the next sign-in starts clean).    public func session() -> BusinessSession? {        guard let text = store.read(Self.slot(address)),              let kept = try? JSONDecoder().decode(BusinessSession.Kept.self, from: Data(text.utf8))        else { return nil }        guard Double(kept.expiresAt) > now().timeIntervalSince1970 else {            forget()            return nil        }        return BusinessSession(phone: kept.phone, person: kept.person, expiresAt: kept.expiresAt, databaseId: kept.databaseId, credential: kept.credential)    }    /// The Keychain forgets the credential: this phone is a stranger again.    public func forget() {        store.forget(Self.slot(address))    }    /// Pull the definitions and the rows this phone may see, carrying the    /// Keychain's credential when someone is signed in.    public func sync(zone: String) async throws -> BusinessSynced {        struct Ask: Encodable { let server: String; let slug: String?; let credential: String?; let zone: String }        let credential = session()?.bearer        return try await signed(credential) {            try await core.call(CottonMethod.businessSync,                                Ask(server: address.server, slug: address.slug, credential: credential, zone: zone),                                as: BusinessSynced.self)        }    }    /// What the phone shows, from the cache: no network, no credential.    public func pages(zone: String) async throws -> BusinessPages {        struct Ask: Encodable { let server: String; let slug: String?; let zone: String }        return try await core.call(CottonMethod.businessPages, Ask(server: address.server, slug: address.slug, zone: zone),                                   as: BusinessPages.self)    }    /// Post `act` with its picks' `answers` (in their order). The rows it    /// changed land in the cache, so the next `pages` shows them.    public func act(_ act: BusinessAct, answers: [String], zone: String) async throws -> BusinessActed {        guard let args = act.arguments(answering: answers) else {            throw CottonCallError(code: "pick_unanswered", message: ShellLines.line("board", "customer.refusal.pick_unanswered"))        }        struct Ask: Encodable {            let server: String; let slug: String?; let credential: String?; let act: String; let args: [String: JSONValue]; let zone: String        }        let credential = session()?.bearer        return try await signed(credential) {            try await core.call(CottonMethod.businessAct,                                Ask(server: address.server, slug: address.slug, credential: credential, act: act.act, args: args, zone: zone),                                as: BusinessActed.self)        }    }    /// Make the person's own personal object this phone's database, carrying    /// the Keychain's credential and the database it names to the core for the    /// sync loop. `topUp` says this connect is a sign-in or a Back up now:    /// the core then asks the object what it holds and sends every row it    /// lacks (`personal.connect {topUp}`); a launch's connect does not.    ///    /// `unmetered` (Cotton Data alone, CONTRACT iPhone brief 14): whether this phone's network is Wi-Fi or Ethernet    /// that is neither expensive nor constrained, so Keep everything's whole copy starts only there. Nil says nothing.    public func connectPersonal(deviceName: String, appVersion: String, topUp: Bool = false, unmetered: Bool? = nil,                                dataKeys: any DataKeyKeeping = DataKeychain()) async throws -> PersonalConnected {        struct Ask: Encodable {            let server: String; let databaseId: String; let credential: String; let windows: [String: Int]?; let deviceName: String; let appVersion: String            let topUp: Bool            let dataKey: String?            let unmetered: Bool?        }        guard let session = session(), let databaseId = session.databaseId else {            throw CottonCallError(code: BusinessRefusal.notSignedIn, message: ShellLines.line("board", "customer.refusal.not_signed_in"))        }        let credential = session.bearer        // The data key this phone keeps for the database rides the connect,        // so the core holds it before the copy's first page is pulled and no        // sealed row waits parked for a later one (launch-fast, 21 Nov 2026).        let dataKey = dataKeys.read(database: databaseId)        return try await signed(credential) {            try await core.call(CottonMethod.personalConnect,                                Ask(server: address.server, databaseId: databaseId, credential: credential, windows: address.window,                                    deviceName: deviceName, appVersion: appVersion, topUp: topUp, dataKey: dataKey, unmetered: unmetered),                                as: PersonalConnected.self)        }    }    /// Where the adopt of this launch stands (`personal.adoptStatus`).    public func adoptStatus() async throws -> PersonalAdopt {        struct Answer: Decodable { let adopt: PersonalAdopt }        return try await core.call(CottonMethod.personalAdoptStatus, as: Answer.self).adopt    }    /// This phone holds no credential the object takes: whatever copy it    /// holds stays as its local database and no pass dials the object    /// (`personal.standLocal`). The Keychain is this client's to forget.    ///    /// `signedOut` says the credential went with it (Sign out, or the    /// object's 401), so the core stops saying a sign-in that failed; a    /// connect that was refused stands local without it, and the core keeps    /// saying why.    public func standLocal(signedOut: Bool = false) async throws {        struct Ask: Encodable { let signedOut: Bool }        _ = try await core.callJSON(CottonMethod.personalStandLocal, Ask(signedOut: signedOut))    }    /// The copy this phone holds is deleted (`personal.remove`); a fresh    /// local database follows from the next start.    public func removeCopy() async throws {        _ = try await core.callJSON(CottonMethod.personalRemove)    }    /// Ask the business for a code for `phone` — at the open host, the    /// number's own database, made now when it has none.    public func askCode(phone: String) async throws -> BusinessChallenge {        guard let slug = address.slug else {            struct Open: Encodable { let server: String; let phone: String }            return try await core.call(CottonMethod.personalCode, Open(server: address.server, phone: phone), as: BusinessChallenge.self)        }        struct Ask: Encodable { let server: String; let slug: String; let phone: String }        return try await core.call(CottonMethod.businessCode, Ask(server: address.server, slug: slug, phone: phone),                                   as: BusinessChallenge.self)    }    /// Sign in with the code, and keep the credential in the Keychain — at    /// the open host with the database it names. A Keychain that will not    /// take it is a refusal, never a signed-in screen.    public func signIn(phone: String, challenge: BusinessChallenge, code: String, name: String? = nil) async throws -> BusinessSession {        guard case .signedIn(let session) = try await signIn(phone: phone, challenge: challenge, code: code, name: name, nameAfter: false) else {            throw CottonCallError(code: "refused", message: ShellLines.line("board", "customer.refusal.refused"))        }        return session    }    /// The sign-in card's way (NEXT-SIGNIN, owner, 28 Nov 2026): with `nameAfter` the code goes alone, and a number    /// with no account yet answers `.nameNeeded` once its code is proved; the card then asks the name and sends the    /// same code again with it. A number with an account is signed in straight away. Whether a number has an account    /// is never said before its code is proved.    public func signIn(phone: String, challenge: BusinessChallenge, code: String, name: String?, nameAfter: Bool) async throws -> BusinessSignInStep {        struct Granted: Decodable {            let credential: String; let person: BusinessPerson; let expiresIn: Int; let databaseId: String?            let deleting: AccountSetToGo.Words?        }        let answer: JSONValue        if let slug = address.slug {            struct Ask: Encodable { let server: String; let slug: String; let challengeId: String; let code: String; let name: String?; let nameAfter: Bool? }            answer = try await core.callJSON(                CottonMethod.businessSignIn,                Ask(server: address.server, slug: slug, challengeId: challenge.challengeId, code: code, name: name, nameAfter: nameAfter ? true : nil))        } else {            struct Open: Encodable { let server: String; let databaseId: String; let challengeId: String; let code: String; let name: String?; let nameAfter: Bool? }            guard let databaseId = challenge.databaseId else {                throw CottonCallError(code: "no_database_id", message: ShellLines.line("board", "customer.refusal.refused"))            }            answer = try await core.callJSON(                CottonMethod.personalSignIn,                Open(server: address.server, databaseId: databaseId, challengeId: challenge.challengeId, code: code, name: name, nameAfter: nameAfter ? true : nil))        }        if answer.flag("nameNeeded") { return .nameNeeded }        let granted = try JSONDecoder().decode(Granted.self, from: JSONEncoder().encode(answer))        if let deleting = granted.deleting {            // Set to be deleted (DELETE_ACCOUNT.md "Signing in during the 30 days"): nothing is kept and nothing            // connects until the person says Keep or Leave.            throw AccountSetToGo(words: deleting, server: address.server, credential: granted.credential, person: granted.person,                                 expiresIn: granted.expiresIn, databaseId: granted.databaseId, phone: phone)        }        return .signedIn(try keep(phone: phone, person: granted.person, credential: granted.credential, expiresIn: granted.expiresIn, databaseId: granted.databaseId))    }    /// Keep my account (`account.keep` with the sign-in's own credential), then the sign-in goes on as any other.    public func keep(_ setToGo: AccountSetToGo) async throws -> BusinessSession {        struct Ask: Encodable { let server: String; let credential: String }        _ = try await core.call("account.keep", Ask(server: setToGo.server, credential: setToGo.credential), as: JSONValue.self)        return try keep(phone: setToGo.phone, person: setToGo.person, credential: setToGo.credential, expiresIn: setToGo.expiresIn,                        databaseId: setToGo.databaseId)    }    /// Leave it to be deleted (`account.leave`): that sign-in ends at the server and nothing is kept.    public func leave(_ setToGo: AccountSetToGo) async throws {        struct Ask: Encodable { let server: String; let credential: String }        _ = try await core.call("account.leave", Ask(server: setToGo.server, credential: setToGo.credential), as: JSONValue.self)    }    /// A credential granted another way than a code — another device's    /// approval (`personal.askPoll`'s `approved`) or a passkey    /// (`personal.passkeySignIn`) — kept exactly as `signIn` keeps one:    /// `{credential, person, expiresIn, databaseId}` as the core answers it.    public func keep(granted: JSONValue, phone: String?) throws -> BusinessSession {        struct Granted: Decodable { let credential: String; let person: BusinessPerson; let expiresIn: Int; let databaseId: String? }        let decoded: Granted        do {            decoded = try JSONDecoder().decode(Granted.self, from: JSONEncoder().encode(granted))        } catch {            throw CottonCallError(code: "refused", message: ShellLines.line("board", "customer.refusal.refused"))        }        guard decoded.databaseId?.isEmpty == false else {            throw CottonCallError(code: "no_database_id", message: ShellLines.line("board", "customer.refusal.refused"))        }        return try keep(phone: phone, person: decoded.person, credential: decoded.credential, expiresIn: decoded.expiresIn, databaseId: decoded.databaseId)    }    /// The one place a credential is written: the Keychain, or a refusal —    /// never a signed-in screen over a write it would not take.    private func keep(phone: String?, person: BusinessPerson, credential: String, expiresIn: Int, databaseId: String?) throws -> BusinessSession {        let session = BusinessSession(phone: phone, person: person,                                      expiresAt: Int(now().timeIntervalSince1970) + expiresIn, databaseId: databaseId,                                      credential: credential)        let text = String(decoding: try JSONEncoder().encode(session.kept), as: UTF8.self)        guard store.write(text, to: Self.slot(address)) else {            throw CottonCallError(code: "keychain_refused", message: ShellLines.line("board", "customer.refusal.keychain_refused"))        }        return session    }    /// Sign out at the business and forget the credential here — forgotten    /// whatever the business answers, so a sign-out never leaves it kept.    public func signOut() async {        struct Ask: Encodable { let server: String; let slug: String?; let credential: String? }        let credential = session()?.bearer        _ = try? await core.callJSON(CottonMethod.businessSignOut, Ask(server: address.server, slug: address.slug, credential: credential))        forget()    }    /// A call carrying `credential`: a refusal that the object no longer    /// takes it forgets it, then is passed on.    private func signed<T>(_ credential: String?, _ call: () async throws -> T) async throws -> T {        do {            return try await call()        } catch let error as CottonCallError where BusinessRefusal.forgets(error.code) && credential != nil {            forget()            throw error        }    }}/// The refusal codes the shell answers by doing something, not only saying it.public enum BusinessRefusal {    /// The act needs a person: the sign-in sheet opens and the act is taken after.    public static let notSignedIn = "not_signed_in"    /// The object no longer takes the credential: forgotten, back to a stranger.    public static let credentialRevoked = "credential_revoked"    /// Whether a refusal says the object no longer takes the credential —    /// revoked, run out, or not one it knows — so the Keychain forgets it.    public static func forgets(_ code: String) -> Bool {        [credentialRevoked, "credential_expired", "invalid_credential"].contains(code)    }}