// THE CONTRACT, in one file: every method name this app asks for and every// event payload it reads.//// The ABI is six C functions and no seventh, so a capability is a METHOD NAME// inside `cotton_call` — which means the names ARE the surface between the two// halves of sub-step 4b, and a typo in one of them is an `unknown_method` at// runtime rather than a compile error.//// **Every shape below is read off the Rust worktree, not off the brief.** The// first cut of this file was written to the design note; the two disagreed in// six places and the app was wrong in all six — a paired phone never left Join,// the digits pane was unreachable, and Home painted over a replica that did not// exist. So the rule from here is the one the code already implies: where the// brief and `crates/cotton-ffi` disagree, the crate wins and// the comments here say the REAL shape. `BoundaryContractTests` reads those// files by path and fails loudly, so this file cannot drift back.//// The tables, as the crate declares them// (`methods.rs::CLIENT_METHODS`, `phone/commands.rs`,// `phone/reads.rs`)://// | Method | Answers | Called by |// |---|---|---|// | `read.boot` | `{paired, stage, ownerId, workspaceId, serverUrl, serverName, refusal}` — the FILES, never an attach | the gate's first question |// | `read.syncStatus` | the sync surface, through the controller — `connected` IS the gate's "is there a file?", and `loop` is what the sync loop is doing | `SyncModel`, and the gate's SECOND question |// | `read.devices` | `{devices, thisDevice}` — every device admitted, off the FILE (`SettingsMethods.swift`) | `DevicesModel`, Home's device line |// | `sync.now` | a WHOLE cycle: `{pushed, pulled, behind, pending, lastPullAt}` | pull-to-refresh |// | `sync.foreground` / `.background` | `{socket, sync}` / `{socket:"off"}` | the scene phase |// | `workspace.startLocal` | `{workspaceId, ownerId, deviceId, mode, state}` — a database on THIS device | the first screen's Start |// | `bootstrap.start` | `{started:true, alreadyRunning}` AT ONCE — never the outcome | the gate |// | `bootstrap.status` | `{running, ready, bytesWritten?, totalBytes?, failed?}` | the gate |// | `migrate.status` | the ladder's plan, or `{running:false}` | the gate |// | `write` | `{answer, rail, queued, tables, tool}` — queued, never pushed: the push is the sync loop's | every screen that writes |// | `routes.list` | `{routes, count, pushTypes, pushTypesUnmapped}` | `RouteTableTests` |//// **Decoding is deliberately generous.** Every field below is optional or has a// default, and nothing throws on a shape it does not recognise: the crate may// land a field before this app reads it, and an app that refused to boot on an// unknown key would be a phone bricked by a core it links in the same binary.// What is NOT generous is the codes — a refusal code is a wire string a screen// keys on, and an unrecognised one is surfaced, never smoothed. And generosity// is exactly why the by-path guard exists: a renamed field degrades to a// default here, silently, which is how the six defects above were invisible.importFoundation/// Every method name, said once.////// `BoundaryContractTests` holds each of these against the crate's own tables,/// so a name here that no build answers is a red test rather than a runtime/// `unknown_method`. There are no exceptions left: both Rust halves have/// landed, and every name below is one the crate answers today.publicenumCottonMethod {publicstaticlet usageRecord = "usage.record"/// Cotton Keys' passkey provider, drained by the app (`PasskeyArrivals`):/// a registration sealed into a row, a use counted, the rows as/// identities, and the scalars of rows this phone's keychain lacks.publicstaticlet passkeyRegister = "passkey.register"publicstaticlet passkeyUsed = "passkey.used"publicstaticlet passkeyIdentities = "passkey.identities"publicstaticlet passkeyMirror = "passkey.mirror"/// A Credential Exchange export handed over by another app (`PasskeyImport`).publicstaticlet passkeyImportCxf = "passkey.importCxf"/// Cotton Keys' passwords (`phone::passwords`): the list without values,/// a reveal on an open vault, add, change, remove, the generator and/// Apple Passwords' CSV; and for its provider (`PasswordArrivals`) a/// site's save, a fill's use, and the keychain copy kept fresh.publicstaticlet passwordList = "password.list"publicstaticlet passwordReveal = "password.reveal"publicstaticlet passwordAdd = "password.add"publicstaticlet passwordChange = "password.change"publicstaticlet passwordRemove = "password.remove"publicstaticlet passwordGenerate = "password.generate"publicstaticlet passwordImportCsv = "password.importCsv"publicstaticlet passwordSave = "password.save"publicstaticlet passwordUsed = "password.used"publicstaticlet passwordMirror = "password.mirror"publicstaticlet readRecentVisits = "read.recentVisits"publicstaticlet recordsList = "records.list"/// `shell.fan {chosen, tool, timezone}` — everything the fan draws: its/// tiles in its order, each with its views in the ring's order (the/// tile the fan stands on counted), where it opens and its first tier.publicstaticlet shellFan = "shell.fan"/// `shell.stream {table, query?, ink?, standing?}` — an app whose face is/// one stream of its conversations (Cotton Messages): the chats in the/// stream's order (unread first, then newest), the unread count's line,/// each chat's mark, which take a reply, and what the top button holds.publicstaticlet shellStream = "shell.stream"/// `shell.deck {table, view?, where?, cursor?, limit?, ink?, visitor?,/// holding?, timezone}` — a page of the deck, answered whole: the cards/// in the view's order, each worn, filled, placed and tap-mapped, with the/// view's head, the empty words, the hand and what Plus does.publicstaticlet shellDeck = "shell.deck"/// `shell.list {table, view?, where?, query?, archived?, section?, pick?,/// cursor?, limit?, timezone, today?}` — a page of a scrolling list,/// answered whole: its sections and rows with their words, acts, menu,/// links, groups, index, filter, empty words, clear and Select.publicstaticlet shellList = "shell.list"/// `shell.plus {table, view?}` — what a table's "+" does: its doors, its/// act at the object, its route, or a blank record.publicstaticlet shellPlus = "shell.plus"/// `shell.draft {table, values} | {id, stage}` — a card not yet made,/// kept by the core until its one create lands: every choice staged on/// it, and the card it wears, resolved from its values as a made one's is.publicstaticlet shellDraft = "shell.draft"/// `shell.input {op: ask | commit, …}` — what an input writes: the editor/// a write stands in and its words, then what a commit wrote, or why not.publicstaticlet shellInput = "shell.input"/// `tools.act {tool, act, account?}` — one of a tool's own acts, offered/// on its held cards (`shell.opened`, kind `tool`): Connect Google/// Calendar answers `{opens}`, the page the phone opens in the browser.publicstaticlet toolsAct = "tools.act"/// `tools.acts {table}` — `{actions}`, the acts of the tools owning the/// table that stand now, as `shell.opened` ranks them among a card's:/// a deck holding no card offers them on its empty placeholder's fan.publicstaticlet toolsActs = "tools.acts"/// `shell.opened {table, id | draft, view?, face?, step?}` — the held/// card answered whole: `{acts}`, ranked and flagged, or with `step`/// that step's `{step: {kind, rows}}` (No date and the days, the times,/// the repeats, the statuses). The shell draws it and decides none of it.publicstaticlet shellOpened = "shell.opened"/// `send.*` — Send, a copy of a record to one of the person's people/// (`crates/cotton-ffi/src/phone/cotton_send.rs`): the object decides/// what goes, to whom and what fits; each answer carries the words its/// card says (`shows`). `send.make {table, id, thread}` → `{id, receipt}`.publicstaticlet sendMake = "send.make"/// `send.inbox {}` → `{in, out, landed}`: what arrived and what was sent, each kept as its thread's item.publicstaticlet sendInbox = "send.inbox"/// `send.keep {id}` → `{state: kept|keeping, landed?, copied?, shows}`.publicstaticlet sendKeep = "send.keep"/// `send.decline {id}` → `{ok}`: the offer goes, and its thread item.publicstaticlet sendDecline = "send.decline"/// `send.undo {id}` → `{removed, state?, shows}`: a send made is taken back; one kept has what it brought removed.publicstaticlet sendUndo = "send.undo"/// `send.trust {number, trusted}` → `{ok}`: every send from them is kept as it arrives.publicstaticlet sendTrust = "send.trust"/// `send.picture {id, key, dir}` → `{path}`: a picture an offer names, fetched before Keep.publicstaticlet sendPicture = "send.picture"/// `shell.reader {book, at?, dark?}` — the open book answered whole: its/// file and format, where it opens, the bar's words, the face worn and/// the knobs, the fan's tiers, the highlights, or the line said in its/// place (a locked book). The reader draws it and decides none of it.publicstaticlet shellReader = "shell.reader"/// `shell.player {op?, table?, id?, at_s?, rate?, minutes?, settings?,/// face?, listened?}` — the one player answered whole: `now` (a song, its/// file and gain; an episode or a film, what it plays from, where it/// starts, its skip, its report cadence, its tracks), the `queue` after/// it, `at`, the seconds past which a play is `played_after_s`, the/// `settings`, the `face` worn and the hand's `faces`, the `words` drawn/// when nothing plays, and a `refusal`. The instrument plays it and/// decides none of it.publicstaticlet shellPlayer = "shell.player"/// `reader.moved {book, at?, page_label?, contents?, active, closing?}` —/// where the page stands; the core writes the place when its rule says/// (`{at, progress_words, wrote, again_ms}`).publicstaticlet readerMoved = "reader.moved"/// `reader.highlight {book, at, pencil?, words, note?} | {id, pencil?,/// note?} | {id, remove}` — a highlight made, changed or removed.publicstaticlet readerHighlight = "reader.highlight"/// `reader.settings {face | knob + value, dark?}` — a face or a knob/// chosen, written to the reader's face choice: `{settings, fan}`.publicstaticlet readerSettings = "reader.settings"/// `reader.seek {book}` — the seek line at the page's edge: `{here, ticks,/// pages, back, words, steps}`.publicstaticlet readerSeek = "reader.seek"/// `reader.seek.say {book, at}` — the slip's words for a dragged place.publicstaticlet readerSeekSay = "reader.seek.say"/// `reader.seek.go {book, at, width?} | {book, tick}` — a jump: the/// Locator to go to and the Back it leaves.publicstaticlet readerSeekGo = "reader.seek.go"/// `reader.seek.back {book}` — the Back place's Locator; Back is cleared.publicstaticlet readerSeekBack = "reader.seek.back"publicstaticlet cardsRepeat = "cards.repeat"/// The one write of a card's when that keeps the half it is not given/// (lane package, e57b88262; `DeckEditor.writeWhen`).publicstaticlet cardsWhen = "cards.when"/// `definitions.theme` — what a database wears: `{definition,/// passed_over}`, the shipped `paper` when it has no row of its own.publicstaticlet definitionsTheme = "definitions.theme"/// `definitions.catalogue` — every definition a database draws, as the/// core resolved and decoded them: `{shape, revision, tables, refused,/// fell_back, kept_as_rows, boards, theme, themes, database}` — only the tables its/// definition rows describe, a row with no face named in `kept_as_rows`/// instead; `{shipped: true}` answers the last resort, this build's/// boards and themes and no table (`DefinitionCatalogues`).publicstaticlet definitionsCatalogue = "definitions.catalogue"/// The app's own words, one set at a time (`ShellLines`).publicstaticlet shellLines = "shell.lines"/// A count as the core says it (`CountLines`).publicstaticlet countWords = "count.words"publicstaticlet cardsPages = "cards.pages"/// The birthdays coming round today and in the days after, soonest first/// (`cards.birthdays`, package row 8).publicstaticlet cardsBirthdays = "cards.birthdays"/// The money due in the same days: expected transactions on their day,/// active subscriptions on their next charge (`cards.moneyDue`).publicstaticlet cardsMoneyDue = "cards.moneyDue"/// `definitions.passedOver` — a board part this build does not draw, filed/// as ONE Feedback row per (database, board, part), ever:/// `{board, part, databaseId, databaseName}` → `{filed}`. A person method:/// it writes the personal database whichever database is named.publicstaticlet definitionsPassedOver = "definitions.passedOver"/// `definitions.saveTheme {definition}` — the database wears this theme:/// written as its own row, refused when this build cannot draw it,/// answered with the receipt and the undo that puts back what was worn.publicstaticlet definitionsSaveTheme = "definitions.saveTheme"/// `definitions.saveTable {table, <key>: value, …}` — a table edited from/// its tool's page: its own columns (shipped ones hidden, never retyped),/// its look, its acts and its stacks. It is `update_definition`, answered/// with the receipt and the undo that puts back what was drawn.publicstaticlet definitionsSaveTable = "definitions.saveTable"/// `records.summarize` — a table's tile figures, computed by the core.publicstaticlet recordsSummarize = "records.summarize"publicstaticlet recordsGet = "records.get"/// `records.undo {change_id}` — a change taken back, a receipt's Undo.publicstaticlet recordsUndo = "records.undo"/// `groups.*` — a table's hand-picked groups (Spec 6): listed with the top/// of each, made, changed one thing at a time, and deleted.publicstaticlet groupsList = "groups.list"publicstaticlet groupsCreate = "groups.create"publicstaticlet groupsUpdate = "groups.update"publicstaticlet groupsDelete = "groups.delete"/// Cinemas' streaming screens (assets/design/cinemas/CONTRACT-2.md; crates/cotton-ffi/src/phone/cinemas_home.rs).publicstaticlet cinemasHome = "cinemas.home"publicstaticlet cinemasRow = "cinemas.row"publicstaticlet cinemasTitle = "cinemas.title"publicstaticlet cinemasSeason = "cinemas.season"publicstaticlet cinemasSearch = "cinemas.search"publicstaticlet cinemasKind = "cinemas.kind"publicstaticlet cinemasGroups = "cinemas.groups"publicstaticlet cinemasGroupsOrder = "cinemas.groupsOrder"publicstaticlet cinemasOnPhone = "cinemas.onPhone"publicstaticlet cinemasSubtitles = "cinemas.subtitles"publicstaticlet cinemasPreparing = "cinemas.preparing"publicstaticlet cinemasRemote = "cinemas.remote"publicstaticlet cinemasToEpisode = "cinemas.toEpisode"publicstaticlet cinemasBin = "cinemas.bin"publicstaticlet cinemasYou = "cinemas.you"/// Hidden (CONTRACT-2 HIDDEN): hide a category or stop; the hidden place; the core's unlock, asked only after the/// phone's lock passed, and its lock.publicstaticlet cinemasHide = "cinemas.hide"publicstaticlet cinemasHidden = "cinemas.hidden"publicstaticlet cinemasUnlock = "cinemas.unlock"publicstaticlet cinemasLock = "cinemas.lock"publicstaticlet cinemasSetting = "cinemas.setting"publicstaticlet cinemasRestore = "cinemas.restore"publicstaticlet filmsSubtitleFile = "films.subtitleFile"/// `phrase.parse` — the one input's words read by the core's phrase/// parser (`CorePhraseParser`).publicstaticlet phraseParse = "phrase.parse"publicstaticlet readBoot = "read.boot"publicstaticlet readSyncStatus = "read.syncStatus"publicstaticlet syncNow = "sync.now"publicstaticlet syncForeground = "sync.foreground"publicstaticlet syncBackground = "sync.background"/// `sync.compact` — the copy's one whole compaction after a trim, run in/// a processing task's time (`{ budgetMs }`) or stopped (`{ stop: true }`).publicstaticlet syncCompact = "sync.compact"/// `sync.rejected` — the writes a peer made that this device would not/// fold, parked rather than dropped.publicstaticlet syncRejected = "sync.rejected"/// `sync.retryRejected` — offer the parked writes to the fold again.publicstaticlet syncRetryRejected = "sync.retryRejected"/// `workspace.startLocal {name?, deviceName?, platform?, appVersion?}` →/// `{workspaceId, ownerId, deviceId, mode, state}`.////// **Start, the other half of the first screen.** A fresh phone used to/// have one verb — Join — because a database was born on a Mac and iOS/// links no server, so nothing could be written down until there was a Mac/// in the room. This mints the workspace on THIS phone: a replica, the/// store's birth rows, this device in its own device list, and a/// connection record in `local` mode.////// **Nothing listens.** No server, no registry, no address — the answer's/// `state` is `noServerYet`, which the app renders as "No Mac yet", and it/// ends when a Mac joins. `already_started` is the refusal over a database/// this phone is already holding.////// The crate emits the same `{phase:"bootstrap", stage:"ready"}` frame a/// download ends with, because it is the same fact: there is a file and/// the app may open on it.publicstaticlet workspaceStartLocal = "workspace.startLocal"publicstaticlet write = "write"publicstaticlet routesList = "routes.list"}/// `read.boot` — the gate's FIRST question, answered BEFORE any replica exists.////// A `Controller` read: a phone with no server, no file and no device key still/// has to draw something, and "not connected" is a fact rather than an error./// The source is `client/connection.json` and `client/refusal.json` — **never/// the network and never the replica**, so a phone with no server reaches Join/// in one frame and a phone WITH one leaves Join in one frame.////// **It no longer answers `open`, and that is the repair.** It used to ask/// `sync_status`, which attaches — a SQLite open, and after a force-quit an/// open that pays the whole write-ahead log's recovery on a boundary that/// answers one call at a time. `BootModel` read it under a five-second ceiling/// and, past the ceiling, resolved "nobody is here": the Join screen, on a/// phone whose server still listed it as approved. Whether the file is open is/// `read.syncStatus`'s `connected`, asked separately and waited for as long as/// it takes.////// `phone/reads.rs::boot` is the whole shape and every field here is one of/// its. `stage` is the crate's own name for what the FILES resolved, and the/// app maps it to a screen: the core names no route.publicstructBootRead: Decodable, Equatable, Sendable {/// `connection.json` names a workspace. THE gate signal — everything else/// is downstream of it, which is why the crate puts it first too.////// `ownerId` is NOT this question: a stored connection can carry a null/// owner id, and gating on it would leave a paired phone in Join for ever.publicvar paired: Bool/// What the core resolved FROM THE FILES, as a NAME rather than a route:/// `"refused"` · `"pairing"` · `"joined"`.////// `"ready"` and `"bootstrap"` are not among them on purpose: they are the/// OPEN's two words, and the open is `read.syncStatus`'s `connected` to/// answer.publicvar stage: String/// The `ownerId` of the cached `/v1/me` answer, or `nil` when the join/// stored none. Shown, never gated on.publicvar ownerId: String?publicvar workspaceId: String?/// The address this phone learned by joining, for a refusal's pre-fill./// `connection.json`'s `base_url`.publicvar serverUrl: String?/// The short relay name that address stands for, when it is a relay one./// `cotton_core::device::pairing::relay_name_of`, never sliced in Swift.publicvar serverName: String?/// A terminal device refusal the transport is already standing on.publicvar refusal: BootRefusal?/// `{code, sentence, serverUrl, serverName, at, erase}` — the crate builds/// the sentence too (`connection::terminal_device_sentence`); this app keeps/// its own copy for the screen and reads only the code, the address and the/// flag below.publicstructBootRefusal: Decodable, Equatable, Sendable {publicvar code: Stringpublicvar sentence: String?publicvar serverUrl: String?publicvar serverName: String?publicvar at: String?/// Did the server ask this device to ERASE ITSELF rather than to stop?////// `DELETE /v1/devices/approved/{id}` with `{"erase": true}` files the/// row as erased, and the chokepoint's `403 device_revoked` then carries/// `erase: true` — so the first request this device makes after somebody/// wiped it from another device is the request that tells it.////// It changes what a screen OFFERS, not what it decides: `false` draws/// two verbs and asks, `true` takes the second one without asking,/// because the owner already answered on the device they revoked this/// one from. **Absent reads as `false`, because the safe reading is the/// one that asks.**publicvar erase: Bool?publicinit( code: String, sentence: String? = nil, serverUrl: String? = nil, serverName: String? = nil, at: String? = nil, erase: Bool? = nil ) {self.code = codeself.sentence = sentenceself.serverUrl = serverUrlself.serverName = serverNameself.at = atself.erase = erase } }publicinit( paired: Bool = false, stage: String = "pairing", ownerId: String? = nil, workspaceId: String? = nil, serverUrl: String? = nil, serverName: String? = nil, refusal: BootRefusal? = nil ) {self.paired = pairedself.stage = stageself.ownerId = ownerIdself.workspaceId = workspaceIdself.serverUrl = serverUrlself.serverName = serverNameself.refusal = refusal }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) paired = (try? container.decode(Bool.self, forKey: .paired)) ?? false stage = (try? container.decode(String.self, forKey: .stage)) ?? "pairing" ownerId = try? container.decode(String.self, forKey: .ownerId) workspaceId = try? container.decode(String.self, forKey: .workspaceId) serverUrl = try? container.decode(String.self, forKey: .serverUrl) serverName = try? container.decode(String.self, forKey: .serverName) refusal = try? container.decode(BootRefusal.self, forKey: .refusal) }/// The address this phone joined. `connection.json`'s `base_url`, and the/// only copy that survives a leave.publicvar address: String? { serverUrl }privateenumCodingKeys: String, CodingKey {case paired, stage, ownerId, workspaceId, serverUrl, serverName, refusal }}publicstructSyncStatusRead: Decodable, Equatable, Sendable {publicvar connected: Bool/// A sentence, when there is no file. Shown as written, never mapped to a/// refusal code — the controller does not put one here.publicvar reason: String?publicvar workspaceId: String?/// `"remote"` on a phone, always. `embedded` is the Mac's.publicvar mode: String?publicvar baseUrl: String?/// Where the file is. For the transparency line, never opened in Swift.publicvar replica: String?/// Local writes that have not reached the server: the queue and the/// writes held for the Mac's time alike.publicvar pending: Int/// Of `pending`, the writes made before this device had the Mac's time/// this launch, held until an answer gives it.publicvar heldWrites: Int?/// Whether a transport exists at all. `NO_TRANSPORT` must be impossible on/// a phone that has joined.publicvar canReachServer: Bool/// ISO-8601 UTC. `nil` until a pass has actually reached the server.publicvar lastPullAt: String?/// `"joined"` or `"noServerYet"` — is there anything to sync WITH.////// **Absent only on the `{connected: false, reason}` shape**, which/// carries no state because there is no file to have one. A/// device that pressed *Start* holds a database of its own and no server/// has joined it (Cotton note "Server address — how a device knows which server holds its data"); the crate answers/// `noServerYet` and the app renders it as "No Mac yet". Whether a pass is/// in flight right now is the `cycle` event's business — this answers the/// question before it.publicvar state: String?/// The `_media` ledger — THIS device's, never the workspace's — because/// "Sync & backup" draws two cards and the second one is bytes.////// Extended here by 4h rather than added as a second read: `SyncModel`/// already derives the live banner from this one answer, and two reads/// would be two chances to disagree about one banner. `nil` on the/// `{connected:false}` shape, which carries no ledger at all. The shape/// itself is `Boundary+4h.swift`'s.publicvar media: MediaActivityRead?/// What the sync LOOP is doing right now, for a reader that was not/// listening when it last said so — the same object the `client` stream/// carries as `phase: "sync"` (`SyncLoopRead`).////// `nil` while no loop runs: a local database, the served Mac, a/// controller that has not attached one yet. **`nil` is "nothing in/// flight", never "reachable"** — `connected` says the FILE is open, and/// only a pass that reached the server says the server is there/// (`SyncModel.live`).publicvar loop: SyncLoopRead?/// How far THIS file's mail search index is filled while it fills in the/// background (mailsearch, v122); `nil` once it is whole, and on a file/// that cannot say.publicvar searchIndex: SearchIndexFill?/// Where this database's sync stands, in the engine's words/// (`DatabaseSyncLine`) — what the page's top and the device row say;/// `nil` on the `{connected:false}` shape.publicvar sync: DatabaseSyncLine?/// The same for every database a pass has reported on, by database id —/// what the Databases sheet's caps start from before a pass ends.publicvar syncs: [String: DatabaseSyncLine]/// The way this device last reached its Mac, in the engine's words —/// "home network", "Tailscale", "over the relay"; `nil` before any/// request has got through, and on a Mac that serves.publicvar route: String?/// The one quiet line every app's home draws about its sync/// (`shell_account::seen_of`, the line `shell.home` gives Android).publicvar seen: SyncSeenRead?publicinit( connected: Bool = false, reason: String? = nil, workspaceId: String? = nil, mode: String? = nil, baseUrl: String? = nil, replica: String? = nil, pending: Int = 0, canReachServer: Bool = false, lastPullAt: String? = nil, state: String? = nil, media: MediaActivityRead? = nil, loop: SyncLoopRead? = nil, searchIndex: SearchIndexFill? = nil, sync: DatabaseSyncLine? = nil, syncs: [String: DatabaseSyncLine] = [:], route: String? = nil, seen: SyncSeenRead? = nil ) {self.connected = connectedself.reason = reasonself.workspaceId = workspaceIdself.mode = modeself.baseUrl = baseUrlself.replica = replicaself.pending = pendingself.canReachServer = canReachServerself.lastPullAt = lastPullAtself.state = stateself.media = mediaself.loop = loopself.searchIndex = searchIndexself.sync = syncself.syncs = syncsself.route = routeself.seen = seen }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) connected = (try? container.decode(Bool.self, forKey: .connected)) ?? false reason = try? container.decode(String.self, forKey: .reason) workspaceId = try? container.decode(String.self, forKey: .workspaceId) mode = try? container.decode(String.self, forKey: .mode) baseUrl = try? container.decode(String.self, forKey: .baseUrl) replica = try? container.decode(String.self, forKey: .replica) pending = (try? container.decode(Int.self, forKey: .pending)) ?? 0 canReachServer = (try? container.decode(Bool.self, forKey: .canReachServer)) ?? false lastPullAt = try? container.decode(String.self, forKey: .lastPullAt) state = try? container.decode(String.self, forKey: .state) media = try? container.decode(MediaActivityRead.self, forKey: .media) loop = try? container.decode(SyncLoopRead.self, forKey: .loop) searchIndex = try? container.decode(SearchIndexFill.self, forKey: .searchIndex) sync = try? container.decode(DatabaseSyncLine.self, forKey: .sync) syncs = (try? container.decode([String: DatabaseSyncLine].self, forKey: .syncs)) ?? [:] route = try? container.decode(String.self, forKey: .route) seen = try? container.decode(SyncSeenRead.self, forKey: .seen) }privateenumCodingKeys: String, CodingKey {case connected, reason, workspaceId, mode, baseUrl, replica, pending, canReachServercase lastPullAt, state, media, loop, searchIndex, sync, syncs, route, seen }}/// `sync.status`'s `seen` (`shell_account::seen_of`): the state, its line in the/// shell's words, what VoiceOver says once when it changes, and how long a/// pass must have run (`since`) before catching up is shown.publicstructSyncSeenRead: Decodable, Equatable, Sendable {/// `signed_out`, `alone`, `offline`, `copy_coming`, `catching_up`,/// `sending`, `up_to_date` or `not_yet`.publicvar state: Stringpublicvar line: Stringpublicvar spoken: Stringpublicvar showAfterMs: Int/// When the pass on the wire began, epoch ms, while one runs.publicvar since: Double?publicvar percent: Int?publicinit(state: String, line: String, spoken: String, showAfterMs: Int = 1_000, since: Double? = nil, percent: Int? = nil) {self.state = stateself.line = lineself.spoken = spokenself.showAfterMs = showAfterMsself.since = sinceself.percent = percent }/// A pass is running and the line counts it as catching up.publicvar catchingUp: Bool { state == "catching_up" || state == "copy_coming" }}/// `read.syncStatus`'s `searchIndex`: `{filled, total}` mail rows of the/// search index this file is filling a slice at a time.publicstructSearchIndexFill: Decodable, Equatable, Sendable {publicvar filled: Intpublicvar total: Intpublicinit(filled: Int, total: Int) {self.filled = filledself.total = total }}/// The sync loop's own status — `cotton_client::sync::SyncStatus`, exactly.////// It reaches the app two ways and this is the one shape for both: on the/// `client` stream tagged `phase: "sync"` (`ClientEvent.sync`), every time the/// loop publishes — a pass starting, a pass finishing, a backoff scheduled, a/// terminal refusal — and under `read.syncStatus`'s `loop` for a cold read.////// **`state` is the crate's word and is kept as a string**, decoded/// generously like every other field here; `SyncModel` is what turns it into/// a phase, and an unknown word there reads as "nothing in flight" rather/// than as an error. The four today are `idle`, `syncing`, `waiting` (a/// backoff, not an idle) and `stopped`.////// `lastError` is the crate's own sentence about the last failure and is/// shown as written. `nextAttemptAt` is ISO-8601, present while the loop is/// waiting AND while a pass is in flight (the ceiling's own promise)./// `stoppedReason` is present only when the loop stopped on its own — a/// refusal of this device no retry can change — and never after a person's/// own stop.publicstructSyncLoopRead: Decodable, Equatable, Sendable {publicvar state: Stringpublicvar pending: Intpublicvar lastPullAt: String?publicvar lastPushAt: String?publicvar lastError: String?/// Consecutive failures — what the backoff ladder is climbing.publicvar failures: Intpublicvar nextAttemptAt: String?publicvar stoppedReason: String?/// The server's code behind `stoppedReason` — `device_revoked` and its/// siblings — so the boot gate can place the refusal (wall or banner)/// without parsing a sentence.publicvar stoppedCode: String?/// Which side is on the older schema, while one is — the crate's word/// (`phoneBehind`, `serverBehind`), kept as a string like `state` and/// turned into a case by `SyncModel`. Absent when the two builds agree./// Never a stop: the file is open, writes land here and queue, and the/// loop keeps trying; this is the ONE fact Home's update slip is drawn/// off.publicvar schema: String?/// How many changes the serving Mac said still wait for this device after/// the last pass that reached it — what remains, never what moved, and/// counted in full. The device row's figure; the home says a percent of/// it in the engine's words. Absent until a Mac that counts has answered.publicvar behindBy: Int?/// Why the serving Mac could not wake this device the last time it tried/// (the catch-up wake), in the Mac's own sentence. Absent once a wake/// went, or when none was needed.publicvar wakeRefusal: String?publicinit( state: String, pending: Int = 0, lastPullAt: String? = nil, lastPushAt: String? = nil, lastError: String? = nil, failures: Int = 0, nextAttemptAt: String? = nil, stoppedReason: String? = nil, stoppedCode: String? = nil, schema: String? = nil, behindBy: Int? = nil, wakeRefusal: String? = nil ) {self.state = stateself.pending = pendingself.lastPullAt = lastPullAtself.lastPushAt = lastPushAtself.lastError = lastErrorself.failures = failuresself.nextAttemptAt = nextAttemptAtself.stoppedReason = stoppedReasonself.stoppedCode = stoppedCodeself.schema = schemaself.behindBy = behindByself.wakeRefusal = wakeRefusal }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)// The one field that HAS to be there: a status with no state word is// not a status, and decoding it as one would paint "idle" over a frame// that said nothing. state = try container.decode(String.self, forKey: .state) pending = (try? container.decode(Int.self, forKey: .pending)) ?? 0 lastPullAt = try? container.decode(String.self, forKey: .lastPullAt) lastPushAt = try? container.decode(String.self, forKey: .lastPushAt) lastError = try? container.decode(String.self, forKey: .lastError) failures = (try? container.decode(Int.self, forKey: .failures)) ?? 0 nextAttemptAt = try? container.decode(String.self, forKey: .nextAttemptAt) stoppedReason = try? container.decode(String.self, forKey: .stoppedReason) stoppedCode = try? container.decode(String.self, forKey: .stoppedCode) schema = try? container.decode(String.self, forKey: .schema) behindBy = try? container.decode(Int.self, forKey: .behindBy) wakeRefusal = try? container.decode(String.self, forKey: .wakeRefusal) }/// Off an event payload, by the same rule as the decoder above: no/// `state`, no status.publicstaticfunc of(_ payload: JSONValue) -> SyncLoopRead? {guardlet state = payload["state"]?.string, !state.isEmpty else { returnnil }returnSyncLoopRead( state: state, pending: payload["pending"]?.int ?? 0, lastPullAt: payload["lastPullAt"]?.string, lastPushAt: payload["lastPushAt"]?.string, lastError: payload["lastError"]?.string, failures: payload["failures"]?.int ?? 0, nextAttemptAt: payload["nextAttemptAt"]?.string, stoppedReason: payload["stoppedReason"]?.string, stoppedCode: payload["stoppedCode"]?.string, schema: payload["schema"]?.string, behindBy: payload["behindBy"]?.int, wakeRefusal: payload["wakeRefusal"]?.string ) }privateenumCodingKeys: String, CodingKey {case state, pending, lastPullAt, lastPushAt, lastError, failures, nextAttemptAtcase stoppedReason, stoppedCode, schema, behindBy, wakeRefusal }}/// What a `client` or `data` event is saying.////// One channel carries the download's figure, the/// migration's steps and the cycle's counts, keyed by `phase` — except the/// cycle, which carries none. An event with a `phase` this app does not know is/// DROPPED: the core may be one build ahead, and an unknown frame has never/// been a reason to stop.publicenumClientEvent: Equatable, Sendable {/// `{phase:"migrate", stage:"start"|"step"|"done"|"failed", …}` —/// `migration_json`, plus the `failed` frame the bootstrap thread emits/// when the ladder is what refused. **`done` is the LADDER's terminal/// word** — the bootstrap's is `ready`, one case below.case migrate(stage: String, from: Int?, to: Int?, index: Int?, total: Int?, version: Int?, message: String?)/// `{phase:"bootstrap", stage:"ready"|"failed", …}`.////// **The terminal stage is `ready`, and `done` is the MIGRATE phase's.**/// `bootstrap.start` returns AT ONCE, so its return cannot be the/// completion — this event is, and it is the only thing that opens the/// gate. The two words are one letter apart in a screen's mind and a whole/// boot apart in behaviour: a gate keyed on `done` never opens, because the/// bootstrap thread never says it. `bootstrap.status` answers `ready: true`/// for the same fact, for a screen that missed the event.case bootstrap(stage: String, workspaceId: String?, code: String?, message: String?, retryable: Bool?)/// `{phase:"personal", stage:"signed_out", code, message}` — the owner's/// personal object answered a sync 401: it no longer takes this phone's/// credential (`crates/cotton-ffi/src/phone/personal_object.rs`). Said/// once per credential; the copy stays.case personalSignedOut(code: String)/// `{phase:"personal", stage:"signed_out", code:"account_deleted", deleted:true, words:{heading, line}}` — the/// account was deleted from another phone or cottondb.com/delete (a 410 at this phone's pass): nothing of it/// stays here (assets/design/shared/DELETE_ACCOUNT.md "Deleted elsewhere"). `line` is said once.case personalDeleted(line: String?)/// `{phase:"personal", stage:"adopted"|"adopt_failed", code?}` — the/// adopt bringing a used local database into the object ended/// (`crates/cotton-ffi/src/phone/adopt.rs`); `personal.adoptStatus`/// says how.case personalAdoptEnded/// `{phase: home}` — the gate moved: the open ended (`opened`), or the/// once-a-second tick while it waits (`tick`). Ask `shell.home` again.case home(stage: String)/// `{phase:"arrival", stage, workspaceId, bytesWritten?, totalBytes?,/// reason?}` — where one listed database's arrival on this device stands,/// from each fill pass (`ClientController::fill_listed`), which downloads/// the body in the core.case arrival(stage: String, database: String, bytesWritten: Int?, totalBytes: Int?, reason: String?)/// `{phase:"databaseSync", workspaceId, sync, …}` — where one database's/// sync stands as a pass ended (or a file copy moved), in the engine's/// own words (`DatabaseSyncLine`); `nil` from a core that says none./// Never said as a pass starts. The counts the frame also carries are/// not read here: the device row reads its own off `sync.status`.case databaseSync(database: String, sync: DatabaseSyncLine?)/// `{phase:"removed", workspaceId}` — this device was removed from a/// database another person's Mac serves, and the core has just written it/// down (`ClientController::sync_joined_pass`): its copy is in this/// device's Bin and the held list no longer holds it. The frame carries/// no sentence; the list is read again on it, and a window that showed/// it goes back to Personal.case removed(database: String)/// `{workspaceId, tables:[…], origin:"write"|"pull"}` — the `data` event,/// which is the whole of invalidation. There is no sequence number: sync is/// one symmetric exchange over per-author cursors, and the tables that/// moved are the only thing a screen needs to hear — with the database/// they moved in (`workspaceId` on the wire), so a window showing another/// database is not re-read for them. `nil` when the event names none,/// which reaches every window.case data(tables: [String], origin: String?, database: String? = nil)/// A finished cycle: `{pushed, pulled, behind, behindBy, pending,/// lastPullAt}`, on the `client` stream with NO `phase`./// `ClientController::sync_now` emits it, so the pending count and the/// "last checked" stamp both move without anybody asking for them again./// `behind` here is the frame's `behindBy` — how many changes the serving/// Mac said still wait, `nil` unsaid — never the frame's page-cap flag.case cycle(pushed: Int, pulled: Int, behind: Int?, pending: Int, lastPullAt: String?)/// `{phase:"sync", state, pending, lastError, nextAttemptAt, failures,/// stoppedReason, lastPullAt, lastPushAt}` — the loop's own status, every/// time it publishes (`shell/client.rs::sync_status_event`).////// **Tagged, because the media drain's status is a phase-less frame with/// the same two keys and overlapping state words.** Before the tag this/// frame was dropped by the `.none` arm below — it carries no `pushed` —/// so a pass in flight, a backoff and a terminal refusal all reached/// nobody, and "Connected" on the settings row meant only that the file/// was open. `SyncModel` derives its phase from this.case sync(SyncLoopRead)/// The `origin` of a `data` event whose cause was BYTES landing on or/// leaving THIS device — the thumbnail sweep's tick, a tap's/// `media.ensure`, the budget's eviction (`crates/cotton-ffi/src/phone//// media.rs`, `MEDIA_EVENT_ORIGIN`). No row changed. Such an event reaches/// the `.storage` family only, and the consumers that act on every `data`/// event without reading its tables skip it: an origin-`media` event once/// re-read every mounted `.core` screen, ran the capture drain and ran a/// notifications pass — sixty times an hour/// while a library's thumbnails came down.publicstaticlet localMediaOrigin = "media"/// The `origin` of a `data` event that says a background move is DONE —/// the computed index rebuilt after the open, mail's search index filled/// (`shell/client.rs`, `MOVES_DONE_ORIGIN`). The tables it names are in/// step again: a read that answered `could_not_read` `moving` over them/// is read again on it, never on a timer or a pull (passivemove rule 3).publicstaticlet movesDoneOrigin = "moved"/// A background move of these tables is done.publicvar isMovesDone: Bool {ifcase .data(_, let origin, _) = self, origin == ClientEvent.movesDoneOrigin { returntrue }returnfalse }/// Bytes moved on this device and nothing else did.publicvar isLocalMediaArrival: Bool {ifcase .data(_, let origin, _) = self, origin == ClientEvent.localMediaOrigin { returntrue }returnfalse }/// Read one off the stream. `nil` for anything this build does not know.publicstaticfunc from(_ event: CottonEvent) -> ClientEvent? {if event.kind == "data" {return .data( tables: event.payload["tables"]?.strings ?? [], origin: event.payload["origin"]?.string, database: event.payload["workspaceId"]?.string ) }guard event.kind == "client"else { returnnil }switch event.payload["phase"]?.string {case"home":return .home(stage: event.payload["stage"]?.string ?? "")case"bootstrap":return .bootstrap( stage: event.payload["stage"]?.string ?? "", workspaceId: event.payload["workspaceId"]?.string, code: event.payload["code"]?.string, message: event.payload["message"]?.string, retryable: event.payload["retryable"]?.bool )case"personal":switch event.payload["stage"]?.string {case"signed_out":if event.payload["deleted"]?.bool == true {return .personalDeleted(line: event.payload["words"]?["line"]?.string) }guardlet code = event.payload["code"]?.string else { returnnil }return .personalSignedOut(code: code)case"adopted", "adopt_failed":return .personalAdoptEndeddefault:returnnil }case"arrival":guardlet database = event.payload["workspaceId"]?.string else { returnnil }return .arrival( stage: event.payload["stage"]?.string ?? "", database: database, bytesWritten: event.payload["bytesWritten"]?.int, totalBytes: event.payload["totalBytes"]?.int, reason: event.payload["reason"]?.string )case"databaseSync":guardlet database = event.payload["workspaceId"]?.string else { returnnil }return .databaseSync(database: database, sync: DatabaseSyncLine(event.payload["sync"]))case"removed":guardlet database = event.payload["workspaceId"]?.string else { returnnil }return .removed(database: database)case"migrate":return .migrate( stage: event.payload["stage"]?.string ?? "", from: event.payload["from"]?.int, to: event.payload["to"]?.int, index: event.payload["index"]?.int, total: event.payload["total"]?.int, version: event.payload["version"]?.int, message: event.payload["message"]?.string )case"sync":// A tagged frame with no state word is dropped rather than read// as idle — the same rule as the cycle below.returnSyncLoopRead.of(event.payload).map(ClientEvent.sync)case .none:// The cycle report. Recognised by `pushed` and `pending` rather// than by a phase, because it has none — and by BOTH, so a future// phase-less frame carrying only one of them is dropped rather// than read as a cycle that pushed nothing.guardlet pushed = event.payload["pushed"]?.int,let pending = event.payload["pending"]?.intelse { returnnil }return .cycle( pushed: pushed, pulled: event.payload["pulled"]?.int ?? 0, behind: event.payload["behindBy"]?.int, pending: pending, lastPullAt: event.payload["lastPullAt"]?.string )default:returnnil } }}/// `write`'s request: `{"tool":"<catalogue name>","args":{…}}`.publicstructWriteRequest: Encodable, Sendable {publicvar tool: Stringpublicvar args: JSONValuepublicinit(tool: String, args: JSONValue = .object([:])) {self.tool = toolself.args = args }}/// `write`'s answer — `authoring.rs::queued_answer`, plus the phone's `tool`.////// **`answer` is the TOOL's own answer, nested rather than merged**, and it is/// a whole JSON value: a handler that one day answers a `queued` of its own/// must not silently overwrite the outbox's report of the same name. `tables`/// IS the invalidation (design P5).////// **There is no `pushed` and no `notPushed`.** A write commits to the file,/// queues its op and returns; the sync loop pushes, off the screen's thread./// Whether the op has left is `SyncStatusRead.pending`'s to say, and a screen/// that wants to show "waiting for the Mac" reads it there — never off a/// write's answer, which cannot know.publicstructWriteAnswer: Decodable, Equatable, Sendable {/// Whatever the tool answered. Shape per tool, so it stays a tree.publicvar answer: JSONValue?/// `"client"` on the phone, always.publicvar rail: String?publicvar queued: Int?publicvar tables: [String]?publicvar tool: String?publicinit( answer: JSONValue? = nil, rail: String? = nil, queued: Int? = nil, tables: [String]? = nil, tool: String? = nil ) {self.answer = answerself.rail = railself.queued = queuedself.tables = tablesself.tool = tool }}// MARK: - The media half of the sync status//// From `Boundary+4h.swift`, which went with I3: `SyncStatusRead` above carries// it, and the boot gate is the one file where typed decoding stays./// What this device still owes the server in BYTES.////// `shell/client.rs::media_activity`, exactly. Device-local and never synced:/// the `_media` ledger is this phone's queue, not the workspace's.////// **A ledger that cannot be read answers `null` with the reason beside it/// rather than zeros.** A card saying "nothing to back up" because a query/// failed is the silent fallback this repo bans outright, so there are three/// shapes and the screen must tell them apart: `{counts, failed}` when both/// reads worked, `{counts: null, failed: null, unreadable}` when the counts/// failed, and `{counts, failed: null, unreadable}` when only the failed-rows/// read did.publicstructMediaActivityRead: Decodable, Equatable, Sendable {/// `nil` when the counts themselves could not be read — never zeros.publicvar counts: Counts?/// The failed uploads, capped at twenty by the crate (`FAILED_MEDIA_LIMIT`,/// the screen's number and not a default of the ledger's)./// `nil` when that read failed, which is not the same as an empty list.publicvar failed: [FailedUpload]?/// Why one of the two reads answered nothing. Present only then.////// PORT GAP: [sync-media-unreadable-undrawn] **decoded and drawn nowhere.** `useSyncActivity` has no such/// field and `settings/sync.tsx` draws no sentence for it, so under/// "move everything as it is" no screen shows it — the card falls to/// "Checking…" on a `nil` `counts`, which is what the Expo card does with/// its own `media?.counts ?? null`. It is decoded rather than dropped/// because it is the only thing that can ever say WHICH of the two reads/// failed, and a reader of this file should find the reason waiting rather/// than have to go back to the crate for it. Ledger row: same class as/// the Bin's `note`.publicvar unreadable: String?publicstructCounts: Decodable, Equatable, Sendable {publicvar pending: Intpublicvar synced: Intpublicvar failed: Intpublicvar deletePending: Intpublicinit(pending: Int = 0, synced: Int = 0, failed: Int = 0, deletePending: Int = 0) {self.pending = pendingself.synced = syncedself.failed = failedself.deletePending = deletePending }/// **The four are decoded STRICTLY, and that is the exception to this/// file's generosity rule.**////// Everywhere else a missing key falls back, because the crate may land/// a field before this app reads it and a phone bricked by its own core/// is the worse failure. These four are the opposite case: they are the/// COUNTS, and a `{"counts": {}}` decoded generously is `0/0/0/0`,/// which the card draws as "Nothing to back up yet" — a query that/// failed, said out loud as good news. That is the silent fallback the/// type's own doc comment above bans.////// Throwing here loses nothing, because the OUTER decode is the/// generous one: `counts` is `try?`-decoded, so a malformed object/// lands on `nil` and the card draws "Checking…" — the honest state for/// a ledger nobody could read. Generosity is kept where it belongs and/// removed where it lies.publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) pending = try container.decode(Int.self, forKey: .pending) synced = try container.decode(Int.self, forKey: .synced) failed = try container.decode(Int.self, forKey: .failed) deletePending = try container.decode(Int.self, forKey: .deletePending) }privateenumCodingKeys: String, CodingKey {case pending, synced, failed, deletePending } }/// One upload that did not go.////// `key` is the OBJECT key, not a path — the card draws its last segment,/// and where the bytes are is `read.mediaPath`'s question.publicstructFailedUpload: Decodable, Equatable, Sendable {publicvar key: Stringpublicvar lastError: String?publicvar updatedAt: String?publicinit(key: String = "", lastError: String? = nil, updatedAt: String? = nil) {self.key = keyself.lastError = lastErrorself.updatedAt = updatedAt }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) key = (try? container.decode(String.self, forKey: .key)) ?? "" lastError = try? container.decode(String.self, forKey: .lastError) updatedAt = try? container.decode(String.self, forKey: .updatedAt) }privateenumCodingKeys: String, CodingKey { case key, lastError, updatedAt } }publicinit( counts: Counts? = nil, failed: [FailedUpload]? = nil, unreadable: String? = nil ) {self.counts = countsself.failed = failedself.unreadable = unreadable }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) counts = try? container.decode(Counts.self, forKey: .counts) failed = try? container.decode([FailedUpload].self, forKey: .failed) unreadable = try? container.decode(String.self, forKey: .unreadable) }privateenumCodingKeys: String, CodingKey { case counts, failed, unreadable }}