// 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.importCottonValuesimportFoundationextensionCottonMethod {/// Pull the business's definitions and the rows the credential's role/// may see into the core's cache.publicstaticlet businessSync = "business.sync"/// Every view the cached role reads, with its rows drawn: no network.publicstaticlet businessPages = "business.pages"/// Ask the business for a code for a number.publicstaticlet businessCode = "business.code"/// Sign in with that code; the answer carries the credential.publicstaticlet businessSignIn = "business.signIn"/// Sign out at the business; the cache starts over as a stranger's.publicstaticlet businessSignOut = "business.signOut"/// Ask the open host for a code for a number: its own database, made on/// its first sign-in.publicstaticlet personalCode = "personal.code"/// Sign in at that database with the code; the answer carries the/// credential and the database id.publicstaticlet 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.publicstaticlet 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.publicstaticlet personalAdopt = "personal.adopt"/// Where that adopt stands: sending, making the copy, done or failed.publicstaticlet personalAdoptStatus = "personal.adoptStatus"/// This phone keeps whatever copy it holds as its local database and/// dials the object no more.publicstaticlet personalStandLocal = "personal.standLocal"publicstaticlet shellAccount = "shell.account"/// The copy this phone holds is deleted, so a fresh local start follows.publicstaticlet personalRemove = "personal.remove"/// Post one act to the business's object.publicstaticlet 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.publicstructBusinessAddress: Codable, Equatable, Sendable {publicvar server: Stringpublicvar slug: String?publicvar window: [String: Int]?publicinit(server: String, slug: String? = nil, window: [String: Int]? = nil) {self.server = serverself.slug = slugself.window = window }privateenumCodingKeys: 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`).publicstaticlet side = CodingUserInfoKey(rawValue: "cotton.business.side")!publicinit(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)iflet one = try? keys.decode(String.self, forKey: .server) { server = onereturn }let sides = try keys.decode([String: String].self, forKey: .server)let side = decoder.userInfo[Self.side] as? AppFlavor ?? AppFlavor.currentguardlet server = sides[side.rawValue] else {throwDecodingError.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`).publicstructPersonalConnected: Decodable, Equatable, Sendable {publiclet databaseId: String?publiclet ownerId: String?publiclet adopt: PersonalAdopt?publicinit(databaseId: String?, ownerId: String? = nil, adopt: PersonalAdopt? = nil) {self.databaseId = databaseIdself.ownerId = ownerIdself.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.publicstructPersonalAdopt: Decodable, Equatable, Sendable {publiclet status: Stringpubliclet rows: Intpubliclet sent: Intpubliclet refused: Intpubliclet code: String?publicinit(status: String, rows: Int, sent: Int = 0, refused: Int = 0, code: String? = nil) {self.status = statusself.rows = rowsself.sent = sentself.refused = refusedself.code = code }privateenumKeys: String, CodingKey { case status, rows, sent, refused, code }publicinit(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) }publicstaticlet started = "started"publicstaticlet sending = "sending"publicstaticlet makingCopy = "making_copy"publicstaticlet done = "done"publicstaticlet failed = "failed"publicstaticlet none = "none"/// Whether the rows are still on their way.publicvar 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.publicstructAccountSetToGo: Error, Equatable, Sendable {publicstructWords: Decodable, Equatable, Sendable {publiclet eraseAt: String?publiclet date: String?publiclet heading: Stringpubliclet line: Stringpubliclet keep: Stringpubliclet leave: String }publiclet words: Wordslet server: Stringlet credential: Stringlet person: BusinessPersonlet expiresIn: Intlet databaseId: String?let phone: Stringpublicinit(words: Words, server: String, credential: String, person: BusinessPerson, expiresIn: Int, databaseId: String?, phone: String) {self.words = wordsself.server = serverself.credential = credentialself.person = personself.expiresIn = expiresInself.databaseId = databaseIdself.phone = phone }}/// Who the object takes the credential's holder for.publicenumBusinessRole: String, Codable, Equatable, Sendable {case `public`, member, staff, ownerpublicinit(from decoder: Decoder) throws {self = BusinessRole(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .public }}/// The signed-in person, as the object names them.publicstructBusinessPerson: Codable, Equatable, Sendable {publiclet id: Stringpubliclet phone: String?publiclet name: String?publiclet role: BusinessRole?publicinit(id: String, phone: String? = nil, name: String? = nil, role: BusinessRole? = nil) {self.id = idself.phone = phoneself.name = nameself.role = role }}/// The business itself, as its definitions name it.publicstructBusinessFacts: Decodable, Equatable, Sendable {publiclet slug: String?publiclet name: String?publiclet currency: String?publiclet timezone: String?publiclet upiId: String?enumCodingKeys: String, CodingKey {case slug, name, currency, timezonecase 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.publicstructBusinessPages: Decodable, Equatable, Sendable {publiclet business: BusinessFacts?publiclet role: BusinessRolepubliclet person: BusinessPerson?publiclet version: Int/// Where photos are fetched: a photo column holds a key, shown from/// `photos + key`.publiclet photos: Stringpubliclet tools: [BusinessTool]publicinit(business: BusinessFacts? = nil, role: BusinessRole = .public, person: BusinessPerson? = nil, version: Int = 0, photos: String = "", tools: [BusinessTool] = []) {self.business = businessself.role = roleself.person = personself.version = versionself.photos = photosself.tools = tools }/// The address a photo column's `key` is shown from: the object's/// photos route with the key after it.publicfunc photo(_ key: String) -> URL? {Self.photo(key, at: photos) }publicstaticfunc photo(_ key: String, at photos: String) -> URL? {guard !key.isEmpty, !photos.isEmpty else { returnnil }let path = key.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? keyreturn URL(string: photos + path) }/// Every row any view holds, each once: what a record pick offers.publicvar 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.publicstructBusinessTool: Decodable, Equatable, Sendable {publiclet tool: Stringpubliclet name: Stringpubliclet picture: JSONValue?publiclet cardStock: String?publiclet views: [BusinessView]enumCodingKeys: String, CodingKey {case tool, name, picture, viewscase cardStock = "card_stock" }publicinit(tool: String, name: String, picture: JSONValue? = nil, cardStock: String? = nil, views: [BusinessView] = []) {self.tool = toolself.name = nameself.picture = pictureself.cardStock = cardStockself.views = views }}/// One view: its label, who reads it, its table and its rows in its order.publicstructBusinessView: Decodable, Equatable, Sendable, Identifiable {publiclet id: Stringpubliclet label: Stringpubliclet visibility: String?publiclet isDefault: Bool?publiclet face: JSONValue?publiclet table: Stringpubliclet count: Intpubliclet 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`).publiclet day: String?enumCodingKeys: String, CodingKey {case id, label, visibility, face, table, count, rows, daycase isDefault = "is_default" }publicinit(id: String, label: String, table: String, rows: [BusinessRow] = [], visibility: String? = nil, isDefault: Bool? = nil, face: JSONValue? = nil, day: String? = nil) {self.id = idself.label = day.flatMap { CottonDate.weekday(of: $0) } ?? labelself.visibility = visibilityself.isDefault = isDefaultself.face = faceself.table = tableself.count = rows.countself.rows = rowsself.day = day }publicinit(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.countself.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.publicstructBusinessRow: Decodable, Equatable, Sendable, Identifiable {publiclet table: Stringpubliclet id: Stringpubliclet data: [String: JSONValue]publiclet title: Stringpubliclet line: String?publiclet owner: String?publiclet acts: [BusinessAct]enumCodingKeys: String, CodingKey { case table, id, data, title, line, owner, acts }publicinit(table: String, id: String, data: [String: JSONValue] = [:], title: String, line: String? = nil, owner: String? = nil, acts: [BusinessAct] = []) {self.table = tableself.id = idself.data = dataself.title = titleself.line = lineself.owner = ownerself.acts = acts }publicinit(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:)`).publicstructBusinessAct: Decodable, Equatable, Sendable, Identifiable {publiclet id: Stringpubliclet label: Stringpubliclet kind: String?publiclet confirm: String?publiclet act: Stringpubliclet args: [String: JSONValue]publiclet picks: [BusinessPick]/// The one act the core ranks first and prints on the brand's fill (a/// session's Book).publiclet primary: Bool/// It takes the thing away (a cancel): the core ranks it last, red.publiclet red: Bool/// The picture the core paints it with, where there is one.publiclet icon: String?enumCodingKeys: String, CodingKey { case id, label, kind, confirm, act, args, picks, primary, red, icon }publicinit(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 = primaryself.red = redself.icon = iconself.id = idself.label = labelself.kind = kindself.confirm = confirmself.act = actself.args = argsself.picks = picks }publicinit(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.publicvar 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.publicfunc arguments(answering answers: [String]) -> [String: JSONValue]? {var args = argsfor (index, pick) in picks.enumerated() {let answer = answers.indices.contains(index) ? answers[index].trimmingCharacters(in: .whitespacesAndNewlines) : ""if answer.isEmpty {if pick.optional == true { continue }returnnil }let value: JSONValueif pick.kind == "number" {guardlet number = Double(answer), number.isFinite else { returnnil } value = .number(number) } else { value = .string(answer) }Self.put(value, at: pick.argument.split(separator: ".").map(String.init), into: &args) }return args }privatestaticfunc put(_ value: JSONValue, at path: [String], into object: inout [String: JSONValue]) {guardlet first = path.first else { return }guard path.count > 1else { object[first] = valuereturn }var inner: [String: JSONValue]ifcase .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.publicstructBusinessPick: Decodable, Equatable, Sendable {publiclet argument: Stringpubliclet kind: Stringpubliclet label: String?publiclet table: String?publiclet min: Double?publiclet max: Double?publiclet `default`: Double?publiclet optional: Bool?enumCodingKeys: String, CodingKey { case argument, kind, label, table, min, max, `default`, optional }publicinit(argument: String, kind: String, label: String? = nil, table: String? = nil, min: Double? = nil, max: Double? = nil, default: Double? = nil, optional: Bool? = nil) {self.argument = argumentself.kind = kindself.label = labelself.table = tableself.min = minself.max = maxself.default = `default`self.optional = optional }publicinit(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.publicstructBusinessSynced: Decodable, Equatable, Sendable {publiclet version: Intpubliclet changed: Intpubliclet role: BusinessRolepubliclet person: BusinessPerson?}/// What an act made: the version it reached and the rows it changed, already/// in the cache.publicstructBusinessActed: Decodable, Equatable, Sendable {publiclet version: Intpubliclet made: JSONValue?publiclet notices: JSONValue?}/// The business's answer to a number: the challenge to sign in against. The/// code itself is the person's to type.publicstructBusinessChallenge: Decodable, Equatable, Sendable {publiclet challengeId: Stringpubliclet 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.publiclet known: Bool?/// At the open host, the number's own database: the code is proved there.publiclet 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.publiclet sentTo: String?publicinit(challengeId: String, expiresIn: Int? = nil, known: Bool? = nil, databaseId: String? = nil, sentTo: String? = nil) {self.challengeId = challengeIdself.expiresIn = expiresInself.known = knownself.databaseId = databaseIdself.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.publicenumBusinessSignInStep: 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.publicstructBusinessSession: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {/// The number as it was typed at sign-in; the person's own from the object.publiclet phone: String?publiclet person: BusinessPerson/// Seconds since 1970 the credential stops being taken.publiclet 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.publiclet databaseId: String?privatelet credential: Stringfileprivateinit(phone: String?, person: BusinessPerson, expiresAt: Int, databaseId: String?, credential: String) {self.phone = phoneself.person = personself.expiresAt = expiresAtself.databaseId = databaseIdself.credential = credential }publicvar description: String { "BusinessSession(\(person.id))" }publicvar debugDescription: String { description }publicvar customMirror: Mirror {Mirror(self, children: ["phone": phone asAny, "person": person, "expiresAt": expiresAt, "databaseId": databaseId asAny]) }/// The Keychain's copy: the one place the credential is written.fileprivatestructKept: Codable {let phone: String?let person: BusinessPersonlet expiresAt: Intlet databaseId: String?let credential: String }fileprivatevar kept: Kept { Kept(phone: phone, person: person, expiresAt: expiresAt, databaseId: databaseId, credential: credential) }fileprivatevar bearer: String { credential }}/// One business's object, through the core. Never on the main thread: the/// Keychain read blocks (`SecretStore`).publicstructBusinessClient: Sendable {privatelet core: any CottonCallingpubliclet address: BusinessAddressprivatelet store: any SecretStoreprivatelet now: @Sendable () -> Date/// The core the client asks, for a pick asked of its cache (`DeckPicking`).publicvar calling: any CottonCalling { core }/// The object, as a pick names it to the core.publicvar addressed: JSONValue {var said: [String: JSONValue] = ["server": .string(address.server)]iflet slug = address.slug { said["slug"] = .string(slug) }return .object(said) }publicinit(core: any CottonCalling, address: BusinessAddress, store: any SecretStore = KeychainSecretStore(), now: @escaping @Sendable () -> Date = Date.init) {self.core = coreself.address = addressself.store = storeself.now = now }/// The Keychain slot one business's session is kept in; Cotton's, at the/// open host, is its own.publicstaticfunc 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).publicfunc session() -> BusinessSession? {guardlet text = store.read(Self.slot(address)),let kept = try? JSONDecoder().decode(BusinessSession.Kept.self, from: Data(text.utf8))else { returnnil }guardDouble(kept.expiresAt) > now().timeIntervalSince1970 else { forget()returnnil }returnBusinessSession(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.publicfunc 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.publicfunc sync(zone: String) asyncthrows -> BusinessSynced {structAsk: Encodable { let server: String; let slug: String?; let credential: String?; let zone: String }let credential = session()?.bearerreturntryawait signed(credential) {tryawait 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.publicfunc pages(zone: String) asyncthrows -> BusinessPages {structAsk: Encodable { let server: String; let slug: String?; let zone: String }returntryawait 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.publicfunc act(_ act: BusinessAct, answers: [String], zone: String) asyncthrows -> BusinessActed {guardlet args = act.arguments(answering: answers) else {throwCottonCallError(code: "pick_unanswered", message: ShellLines.line("board", "customer.refusal.pick_unanswered")) }structAsk: Encodable {let server: String; let slug: String?; let credential: String?; let act: String; let args: [String: JSONValue]; let zone: String }let credential = session()?.bearerreturntryawait signed(credential) {tryawait 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.publicfunc connectPersonal(deviceName: String, appVersion: String, topUp: Bool = false, unmetered: Bool? = nil, dataKeys: any DataKeyKeeping = DataKeychain()) asyncthrows -> PersonalConnected {structAsk: Encodable {let server: String; let databaseId: String; let credential: String; let windows: [String: Int]?; let deviceName: String; let appVersion: Stringlet topUp: Boollet dataKey: String?let unmetered: Bool? }guardlet session = session(), let databaseId = session.databaseId else {throwCottonCallError(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)returntryawait signed(credential) {tryawait 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`).publicfunc adoptStatus() asyncthrows -> PersonalAdopt {structAnswer: Decodable { let adopt: PersonalAdopt }returntryawait 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.publicfunc standLocal(signedOut: Bool = false) asyncthrows {structAsk: Encodable { let signedOut: Bool } _ = tryawait 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.publicfunc removeCopy() asyncthrows { _ = tryawait 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.publicfunc askCode(phone: String) asyncthrows -> BusinessChallenge {guardlet slug = address.slug else {structOpen: Encodable { let server: String; let phone: String }returntryawait core.call(CottonMethod.personalCode, Open(server: address.server, phone: phone), as: BusinessChallenge.self) }structAsk: Encodable { let server: String; let slug: String; let phone: String }returntryawait 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.publicfunc signIn(phone: String, challenge: BusinessChallenge, code: String, name: String? = nil) asyncthrows -> BusinessSession {guardcase .signedIn(let session) = tryawait signIn(phone: phone, challenge: challenge, code: code, name: name, nameAfter: false) else {throwCottonCallError(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.publicfunc signIn(phone: String, challenge: BusinessChallenge, code: String, name: String?, nameAfter: Bool) asyncthrows -> BusinessSignInStep {structGranted: Decodable {let credential: String; let person: BusinessPerson; let expiresIn: Int; let databaseId: String?let deleting: AccountSetToGo.Words? }let answer: JSONValueiflet slug = address.slug {structAsk: Encodable { let server: String; let slug: String; let challengeId: String; let code: String; let name: String?; let nameAfter: Bool? } answer = tryawait core.callJSON(CottonMethod.businessSignIn,Ask(server: address.server, slug: slug, challengeId: challenge.challengeId, code: code, name: name, nameAfter: nameAfter ? true : nil)) } else {structOpen: Encodable { let server: String; let databaseId: String; let challengeId: String; let code: String; let name: String?; let nameAfter: Bool? }guardlet databaseId = challenge.databaseId else {throwCottonCallError(code: "no_database_id", message: ShellLines.line("board", "customer.refusal.refused")) } answer = tryawait 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))iflet 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.throwAccountSetToGo(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.publicfunc keep(_ setToGo: AccountSetToGo) asyncthrows -> BusinessSession {structAsk: Encodable { let server: String; let credential: String } _ = tryawait core.call("account.keep", Ask(server: setToGo.server, credential: setToGo.credential), as: JSONValue.self)returntry 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.publicfunc leave(_ setToGo: AccountSetToGo) asyncthrows {structAsk: Encodable { let server: String; let credential: String } _ = tryawait 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.publicfunc keep(granted: JSONValue, phone: String?) throws -> BusinessSession {structGranted: Decodable { let credential: String; let person: BusinessPerson; let expiresIn: Int; let databaseId: String? }let decoded: Granteddo { decoded = try JSONDecoder().decode(Granted.self, from: JSONEncoder().encode(granted)) } catch {throwCottonCallError(code: "refused", message: ShellLines.line("board", "customer.refusal.refused")) }guard decoded.databaseId?.isEmpty == falseelse {throwCottonCallError(code: "no_database_id", message: ShellLines.line("board", "customer.refusal.refused")) }returntry 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.privatefunc 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 {throwCottonCallError(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.publicfunc signOut() async {structAsk: 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.privatefunc signed<T>(_ credential: String?, _ call: () asyncthrows -> T) asyncthrows -> T {do {returntryawait call() } catchlet error asCottonCallErrorwhereBusinessRefusal.forgets(error.code) && credential != nil { forget()throw error } }}/// The refusal codes the shell answers by doing something, not only saying it.publicenumBusinessRefusal {/// The act needs a person: the sign-in sheet opens and the act is taken after.publicstaticlet notSignedIn = "not_signed_in"/// The object no longer takes the credential: forgotten, back to a stranger.publicstaticlet 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.publicstaticfunc forgets(_ code: String) -> Bool { [credentialRevoked, "credential_expired", "invalid_credential"].contains(code) }}