Cotton code
267 lines · 10.0 KB · SwiftRaw
// 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.import CottonKitimport Foundationimport OSLogimport SwiftUI/// Where the gate's numbers go that the cards never print.enum GateLog {    static let log = Logger(subsystem: "com.cottondb.boot", category: "gate")}@MainActor@Observablepublic final class BootModel {    /// What the root paints. Exactly one of these at a time.    public enum Screen: 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    }    public private(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.    public private(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.    static func problem(of screen: Screen) -> String? {        guard case .gate(let gate) = screen, ["stalled", "failed", "refused", "move_failed"].contains(gate.stage) else { return nil }        return [gate.stage, gate.code, gate.words.detail].compactMap { $0 }.joined(separator: ": ")    }    /// Whether `connection.json` names a workspace, from `read.boot`.    public private(set) var paired = false    /// Who is here, from the cached `/v1/me` answer. Shown, never gated on.    public private(set) var ownerId: String?    public private(set) var workspaceId: String?    public private(set) var serverUrl: String?    public private(set) var serverName: String?    /// The refusal the core says stands, wherever it is drawn.    public var 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.    public var readOnly: ServerRefusal? {        guard let gate = home?.gate, gate.refusal == "banner" else { return nil }        return ServerRefusal(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.    public var holdsDrains: Bool { readOnly != nil }    /// The owner already said this device is to erase itself.    public var mustErase: Bool { home?.gate.erase == true }    private let core: any CottonCalling    /// A refusal the app holds before the core can (the Keychain's), sent    /// with every ask.    private var held: String?    private var asking = false    private var askAgain = false    /// A revocation is noticed once per refusal.    private var 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.    public var beforeLeaving: (@Sendable () async -> Void)?    public init(core: any CottonCalling) {        self.core = core        Diagnostics.sayBuild(core)        UsageReporter.shared.start(core)    }    // MARK: - Asking    /// Read who is here, and ask the gate.    public func 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()`.    public func preset(_ refusal: ServerRefusal) {        held = refusal.code    }    /// `read.boot`: who this device belongs to, off `connection.json`.    private func readIdentity() async {        guard let 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.    public func ask(retry: Bool = false) async {        if asking, !retry {            askAgain = true            return        }        asking = true        defer { asking = false }        repeat {            askAgain = false            do {                let answer = try await 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    }    private func 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 = .waiting        case "door": screen = .door        case "open": screen = .ready        default: 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.    public func 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.    private func note(_ gate: HomeAnswer.Gate) {        guard gate.code == "device_revoked", noticed != gate.code else { return }        noticed = gate.code        Task { [beforeLeaving] in await beforeLeaving?() }    }    // MARK: - The ways out    /// Hide mounted readers before deleting the database they draw.    public func waitForReplacement() {        home = nil        screen = .waiting    }    /// The core already opened the replacement copy; read who is here again.    public func refreshCopy() async {        await readIdentity()        await ask()    }    /// Try again: a new wait and a new open.    public func 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.    public func sendReport() async -> String {        do {            let report = try await Diagnostics.sendReport(core)            if report.documentId != nil { return ShellLines.line("boot", "report.saved") }            SystemClipboard().put(ShellLines.line("boot", "report.clipboard", ["why": report.refused ?? ShellLines.line("boot", "report.no_reason"), "text": report.text]))            return ShellLines.line("boot", "report.copied", ["why": report.refused ?? ShellLines.line("boot", "report.no_reason")])        } catch {            return ShellLines.line("boot", "report.none", ["why": ActionRefused.words(for: error)])        }    }    /// Leave this database: back to the first screen. The device key STAYS.    public func 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`).    public func erase(store: some DeviceKeyStore, 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.    public func resetKey(store: some DeviceKeyStore, vault: VaultKeyring = VaultKeyring()) async {        DeviceKey.forget(store: store)        vault.forget()        ListSeeds.eraseAll()        await leave()    }    private func forgetIdentity() {        paired = false        ownerId = nil        workspaceId = nil        serverUrl = nil        serverName = nil    }}/// What `shell.home` is asked with.struct HomeAsk: 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}