// The boot gate, as a READER of the core's answer (`shell.home`, boundary// review move 5, 5 Nov 2026).//// The core decides the gate whole — its stage, its words, the wait's step and// m:ss clock, where a refusal stands (wall, banner or nothing), its ways out —// and opens the copy itself, on its own thread. This model asks, and draws// what it is told://// * on launch (`start`), and again after a retry, a sign-in, a// sign-out or an erase;// * on every `{phase: home}` frame — the open ending, and once a second// while the gate waits, which is the clock's cadence — and on a frame that// moves the gate (a ladder's step, a loop stopped on a refusal);// * on a data event, coalesced, for this device's own facts.//// There is no first-open choice: a device holding no database has one started// by the core at the first ask (filed under this phone's name, sent with every// ask). What stays here is what only the app can do: the leave and the erase// (the Keychain's), the report, and the push registration forgotten before a// leave.importCottonKitimportFoundationimport OSLogimportSwiftUI/// Where the gate's numbers go that the cards never print.enumGateLog {staticlet log = Logger(subsystem: "com.cottondb.boot", category: "gate")}@MainActor@ObservablepublicfinalclassBootModel {/// What the root paints. Exactly one of these at a time.publicenumScreen: Equatable {/// Nothing, and the splash stays up.case waiting/// A business app's device holding no database: its business's door.case door/// A gate slip the core answered: a wait past its ceiling, a refusal's/// wall, a move, a move that failed, an open that failed.case gate(HomeAnswer.Gate)/// The file is open and the children may read it.case ready }publicprivate(set) var screen: Screen = .waiting {// What the open card shows, for the device's reported state. didSet { if screen != oldValue { Diagnostics.say(core, ["openProblem": Self.problem(of: screen)]) } } }/// The core's whole answer, last read.publicprivate(set) var home: HomeAnswer?/// The sentence a screen stands on when it is a problem; `nil` for a wait/// that is going or a door.staticfunc problem(of screen: Screen) -> String? {guardcase .gate(let gate) = screen, ["stalled", "failed", "refused", "move_failed"].contains(gate.stage) else { returnnil }return [gate.stage, gate.code, gate.words.detail].compactMap { $0 }.joined(separator: ": ") }/// Whether `connection.json` names a workspace, from `read.boot`.publicprivate(set) var paired = false/// Who is here, from the cached `/v1/me` answer. Shown, never gated on.publicprivate(set) var ownerId: String?publicprivate(set) var workspaceId: String?publicprivate(set) var serverUrl: String?publicprivate(set) var serverName: String?/// The refusal the core says stands, wherever it is drawn.publicvar standingRefusal: ServerRefusal? { home.flatMap { ServerRefusal(gate: $0.gate) } }/// The refusal the app is READING UNDER: the core placed it as a banner/// over the open copy. `nil` when none stands there.publicvar readOnly: ServerRefusal? {guardlet gate = home?.gate, gate.refusal == "banner"else { returnnil }returnServerRefusal(gate: gate) }/// Whether the mailboxes are DRAINED right now: under a banner they are/// held, and saved the moment this phone is let back in.publicvar holdsDrains: Bool { readOnly != nil }/// The owner already said this device is to erase itself.publicvar mustErase: Bool { home?.gate.erase == true }privatelet core: any CottonCalling/// A refusal the app holds before the core can (the Keychain's), sent/// with every ask.privatevar held: String?privatevar asking = falseprivatevar askAgain = false/// A revocation is noticed once per refusal.privatevar noticed: String?/// What has to happen BEFORE a leave, on either path: the push/// registration's memory is forgotten (`push.forget`). Absent in a test.publicvar beforeLeaving: (@Sendable () async -> Void)?publicinit(core: any CottonCalling) {self.core = coreDiagnostics.sayBuild(core)UsageReporter.shared.start(core) }// MARK: - Asking/// Read who is here, and ask the gate.publicfunc start() async {GateLog.log.notice("core.build=\(CottonRuntime.buildCommit ?? "unstamped", privacy: .public)")await readIdentity()await ask() }/// A refusal the app already knows before the core is asked — the/// Keychain's. Set before `start()`.publicfunc preset(_ refusal: ServerRefusal) { held = refusal.code }/// `read.boot`: who this device belongs to, off `connection.json`.privatefunc readIdentity() async {guardlet read = try? await core.call(CottonMethod.readBoot, as: BootRead.self) else { return } paired = read.paired ownerId = read.ownerId workspaceId = read.workspaceId serverUrl = read.address serverName = read.serverName }/// Ask the gate now; an ask while one is out asks once more after it.publicfunc ask(retry: Bool = false) async {if asking, !retry { askAgain = truereturn } asking = truedefer { asking = false }repeat { askAgain = falsedo {let answer = tryawait core.call(CottonMethod.shellHome, HomeAsk(retry: retry ? true : nil, refusal: held, device_name: ThisPhone.deviceName()), as: HomeAnswer.self) apply(answer) } catch {Log.write("shell.home did not answer: \(error)")return } } while askAgain }privatefunc apply(_ answer: HomeAnswer) {let opened = home?.gate.stage != "open" && answer.gate.stage == "open" home = answer note(answer.gate)switch answer.gate.stage {case"wait": screen = .waitingcase"door": screen = .doorcase"open": screen = .readydefault: screen = .gate(answer.gate) }if opened { Task { await readIdentity() } } }/// The app's one subscriber hands every event to every model: the gate/// asks again on its own frames and on a frame that moves it.publicfunc receive(_ event: ClientEvent) {switch event {case .home, .migrate, .bootstrap, .personalSignedOut, .personalDeleted, .personalAdoptEnded, .removed:Task { await ask() }case .sync(let status) where status.stoppedCode != nil:Task { await ask() }case .data:if screen == .ready { Task { await ask() } }case .sync, .cycle, .arrival, .databaseSync:break } }/// A revocation is NOTICED: the push registration's note is forgotten,/// and nothing is deleted — deleting a person's data is a decision a/// person makes.privatefunc note(_ gate: HomeAnswer.Gate) {guard gate.code == "device_revoked", noticed != gate.code else { return } noticed = gate.codeTask { [beforeLeaving] inawait beforeLeaving?() } }// MARK: - The ways out/// Hide mounted readers before deleting the database they draw.publicfunc waitForReplacement() { home = nil screen = .waiting }/// The core already opened the replacement copy; read who is here again.publicfunc refreshCopy() async {await readIdentity()await ask() }/// Try again: a new wait and a new open.publicfunc retry() async {await readIdentity()await ask(retry: true) }/// "Send a report" from a card: the report filed in the personal/// database, or — when this copy refuses the write — put on the clipboard/// headed by why. Answers what the link then says.publicfunc sendReport() async -> String {do {let report = tryawaitDiagnostics.sendReport(core)if report.documentId != nil { returnShellLines.line("boot", "report.saved") }SystemClipboard().put(ShellLines.line("boot", "report.clipboard", ["why": report.refused ?? ShellLines.line("boot", "report.no_reason"), "text": report.text]))returnShellLines.line("boot", "report.copied", ["why": report.refused ?? ShellLines.line("boot", "report.no_reason")]) } catch {returnShellLines.line("boot", "report.none", ["why": ActionRefused.words(for: error)]) } }/// Leave this database: back to the first screen. The device key STAYS.publicfunc leave() async {await beforeLeaving?() forgetIdentity()await ask(retry: true) }/// Take Cotton OFF this phone: this device's identity, its vault key and/// the rows each list last drew — the person's choice on a revoked/// phone's wall, or the owner's already (`mustErase`).publicfunc erase(store: someDeviceKeyStore, vault: VaultKeyring = VaultKeyring()) async {await beforeLeaving?()DeviceKey.forget(store: store) vault.forget()ListSeeds.eraseAll() forgetIdentity()await ask(retry: true) }/// Start over: a NEW key, the old server left, then the first screen.publicfunc resetKey(store: someDeviceKeyStore, vault: VaultKeyring = VaultKeyring()) async {DeviceKey.forget(store: store) vault.forget()ListSeeds.eraseAll()await leave() }privatefunc forgetIdentity() { paired = false ownerId = nil workspaceId = nil serverUrl = nil serverName = nil }}/// What `shell.home` is asked with.structHomeAsk: Encodable, Sendable {let retry: Bool?let refusal: String?/// What this phone is filed under in a database the core starts here.let device_name: String}