Cotton code
446 lines · 22.7 KB · SwiftRaw
// The NAMES the settings family, devices, Find, the Bin and the assistant// activity screen ask for — 4h's and 4k's.//// A separate file from `Boundary.swift` and `Boundary+4d.swift` for the reason// the second one gives: several lanes land at once, and a lane that appends to// the middle of somebody else's file makes a merge conflict out of what is// really two independent additions. The rule both of them state binds every// name and every shape in this lane too: **where this app and// `crates/cotton-ffi` disagree, the CRATE wins**, and// `BoundaryContractTests` reads `methods.rs` and `phone/reads.rs` by path so// the two cannot drift quietly.//// This file holds the NAMES alone, and the one shape every owner route shares// (`OwnerRefusal`). The answer shapes are gone (I3): a screen reads its// `JSONValue` with the scaffold's accessors, and `ReadKeySweepTests` holds// every key it spells against the crate. What is here is the vocabulary, said// once, so a screen cannot invent a method name that no build answers.//// ## Why these are METHODS and not `read.*` or `write`//// The same sentence for all four HTTP families, and it is `phone/owner.rs`'s:// **the answer is not in the person's file.** The device registry is the// server's `registry.db` and is deliberately never in the workspace; an OAuth// request lives on the server for as long as the consent page is open and is// never written down; Google's connection state is what the server's workers// last saw. `read.*` answers from the replica. These cannot.//// And there is no `URLSession` in this app for a Cotton server, so a screen// that reached the server yesterday reaches it through a method today.//// The four `settings.*` writes are a different class again: their tables are// `SUPPORTING_TABLES`, classified rather than declared, so the MCP verb grid// owes them no entry and there is no refusal to widen. They go through// `authoring::author_through_outbox`, the same writer, outbox and `data` event// `capture.create` takes. Inventing tools for them would let an assistant// rename the person's dictionary, revoke its own access, or move where they// live.//// ## What a refusal from one of them carries//// `phone/owner.rs::refused` maps the server's own `code` — because a screen's// refusal map is CLOSED over those codes and an invented word would fall// through it — and puts the HTTP **status** in `details`, plus// `retryAfterSeconds` when the server sent one. [`OwnerRefusal`] is how a// screen reads that; `useApprovedDevices` does not retry a 4xx, and a refusal// that dropped the status would leave a 401 as a permanent skeleton.import Foundationextension CottonMethod {    // ── `devices.*` — this phone as the APPROVING device ──────────────────    //    // NOT `pairing.*`. All six `pairing.*` names are `HOST_METHODS`: a Mac    // approves IN PROCESS over the server's own registry, because the app is    // the process the route would have run in. A phone holds no registry, so    // its approving half is these seven questions asked of the server over    // HTTP. `join.*` is this phone as the JOINING device and is 4b's. Three    // surfaces, not two, and they must never be merged.    /// `read.devices` — `{devices, thisDevice}` off the person's OWN file:    /// `list_devices`' rows (revoked rows included, and saying so) plus the id    /// the server admits THIS device by, which the list marks its own row    /// with. A local read, so the Devices screens draw before any Mac answers    /// and draw the same on a train. What it cannot say — the pairings still    /// waiting, the registry's last-seen stamp — is `devices.pending`'s and    /// the sync phase's (`SyncModel.phase`).    public static let readDevices = "read.devices"    /// `read.device {deviceId}` — one device's page. On a Mac's OWN page it    /// carries `host`: the four switches its `host-settings.json` holds and    /// the serving state (`hostAnsweredBy` "this_mac"); anywhere else `host`    /// is null.    public static let readDevice = "read.device"    /// `device.facts {deviceId}` — one device's record with its live columns    /// (the device table's `live_read`) and, on this device's own, its card    /// dealt over them under `@card`: what Home's `device` part draws first,    /// always (`shell.today`'s device card).    public static let deviceFacts = "device.facts"    /// `device.pushAck {pushId, receivedAt?, how?}` — this phone met a Cotton    /// push (`PushReceipt`), told to the serving Mac, which keeps the first    /// receipt per push for the signing device. A push counts as reaching the    /// owner when the phone says so, not when Apple answers 2xx (architect,    /// 12 Oct 2026).    public static let devicePushAck = "device.pushAck"    /// `GET /v1/devices/pending` — `{pending: [ … ]}`, six fields per row.    ///    /// **The digits ARE on the wire, and that is the change.** They used to be    /// a secret the approver typed off the joining phone's screen, so a pending    /// list carrying them would have handed the second factor to whoever could    /// read the list. They are not a secret any more: the server derives them    /// from the joining key and the pairing id and gives the same six to    /// everybody with a right to the question — the joining screen, this list,    /// the push. Knowing them proves nothing; SEEING THE SAME ONES is the whole    /// of the second factor.    ///    /// `phone/devices.rs::pending_row` projects exactly `pairingId, name,    /// platform, appVersion, createdAt, expiresAt, digits`, explicitly built and    /// never spread. What is still absent is the joining device's KEY, because    /// the digits are a pure function of it and the pairing id.    public static let devicesPending = "devices.pending"    /// `POST /v1/devices/pending/{pairingId}/approve` — `{pairingId, digits}`.    ///    /// **The digits are an ECHO of the row, never typed.** They are not a proof    /// of who is asking — the signature is that — but a proof of WHICH request    /// the person was looking at: a queue that moved between the draw and the    /// tap refuses rather than admitting the wrong device. Six ASCII numerals,    /// checked below the boundary too as an echo guard.    public static let devicesApprovePending = "devices.approvePending"    /// `POST /v1/devices/pending/{pairingId}/decline` — an EMPTY OBJECT body,    /// not an absent one: the signature is over the bytes as sent.    public static let devicesDeclinePending = "devices.declinePending"    // ── `settings.*` — the five writes the tool surface owes no verb ──────    // ── The reads ─────────────────────────────────────────────────────────    /// `/settings` and `/settings#city` — `{ownerName, city}`.    ///    /// ONE read of ONE row for two questions, because two reads over it would    /// be two chances to disagree about it. `ownerName` is `null` for a blank    /// name AND for the `"Personal"` placeholder — a screen that drew    /// "Personal" would be telling the person that is what they are called.    ///    /// **The ADDRESS is not here and must not be**: `read.boot` already answers    /// `serverName`, resolved through `relay_name_of` off the connection file.    /// It used to cost a `GET /v1/me/server` round trip.    public static let readAccount = "read.account"    public static let readYou = "read.you"    /// Ranked manual and automatic contextual strings, read per mic session.    public static let readVoiceContext = "read.voiceContext"    /// Every name and the person's own lines: what this device compiles its    /// dictation language model from (`CottonUI/Capture/VoiceModel.swift`).    public static let readVoiceCorpus = "read.voiceCorpus"    /// `/search` — `{hits, totals}` over    /// `cotton_core::rules::search_everything::search_everything_file`.    ///    /// The ENGINE, not the `search_records` tool: both ride the same function,    /// but the tool is the assistant's register and flattens to one `records`    /// array. The app wants hits grouped per SECTION with `totals` and its own    /// words for a title, so the grouping is Swift's. The meaning lane is OFF,    /// which is the default and what the app asked for by passing no options.    public static let readFind = "read.find"}// MARK: - The assistant: /activity, "Working on", the Keys card (4k)extension CottonMethod {    /// `/activity` — the replica's own facts, the assistant's runs, and what an    /// assistant has done in this database.    ///    /// Arguments `limit` (1…200, default 50) and `auditLimit` (1…100, default    /// 20), each **refused** outside its range with the range named, never    /// clamped — so a screen that asked for something impossible is told,    /// rather than drawn a smaller number nobody mentioned.    public static let readActivity = "read.activity"}// MARK: - The passwords (the vault)/// `vault.*` and the two reads behind `/passwords` — spec §6.2.////// **`secrets.set` is gone.** It existed because encrypting was a rail the/// phone did not have, so a credential went over the signed transport to the/// one process that could. Since schema v6 this device holds its own X25519/// key in the Keychain (`VaultKey`), seals locally, and writes through the/// ordinary outbox — nothing leaves the phone in the clear and there is no/// round trip at all.////// **There is no method that answers a value except `vaultReveal`**, and there/// is no MCP verb that does at any price: a reveal is this device, its own/// replica, its own key, behind a presence prompt.extension CottonMethod {    /// `{ publicKey }` → `{ id, deviceId, changed }`. Upserts this device's    /// `cotton_vault_keys` row so a server can wrap the master key for it.    /// Idempotent; a CHANGED key clears the wrap that was for the old one.    public static let vaultPublishKey = "vault.publishKey"    /// `{ privateKey, name? }` → `{ unlocked, until }`. Unwraps this device's copy of    /// the master key and holds it for five minutes.    ///    /// Refuses `vault_not_wrapped_yet` ("Waiting for the Mac that holds your    /// passwords to share the key") when there is no wrap or the wrap is at an    /// older version than the workspace, and `vault_key_mismatch` when the key    /// handed in is not the one published — which a screen answers by    /// publishing the key it is holding rather than by drawing a sentence.    public static let vaultUnlock = "vault.unlock"    /// `{}` → `{ card, pollSeconds }`: the oldest waiting unlock request as    /// the `unlock.card` face draws it (`card.face`, `card.fields`, every    /// word the core's; `card.acts`), or `card: null`. Answered only in an    /// app whose kit carries the request table (Keys, Cotton).    public static let unlockCard = "unlock.card"    /// `{ requestId, tables, minutes, privateKey }` → `{ grantId, endsAt,    /// tables, minutes }`. The vault key opens for this call alone, signs the    /// grant through the person key, and every vault session is locked    /// after. Refuses `request_not_waiting`, `bad_tables`, `bad_minutes`,    /// `seal_key_missing`, `vault_locked`, `no_person_key`.    public static let unlockAllow = "unlock.allow"    /// `{ requestIds, privateKey }` → `{ allowed, refused: [{ requestId, code, said }] }`: Allow all.    public static let unlockAllowAll = "unlock.allowAll"    /// `{ requestId }` → `{ declined }`: *Not now*.    public static let unlockDecline = "unlock.decline"    /// `{ grantId }` → `{ ended }`: *End now* on an open window.    public static let unlockEnd = "unlock.end"    /// `{}` → `{ windows: [{ grantId, requestId, tables, endsAt, said }],    /// acts }`: the windows open now, each row's words, and *End now*.    public static let unlockWindows = "unlock.windows"    /// `{}` → `{ keyHeld, needsKey, said: { line, act } | null, database,    /// minted, parked }`: whether the core holds this database's data key,    /// and whether this app keeps a sealed table it cannot read without it    /// (the core's words for the line that asks, and its act).    public static let sealStatus = "seal.status"    /// `{ key }` → `{ held }`: the data key the Keychain kept, handed back at    /// launch so a pull opens sealed rows with no prompt.    public static let sealUseKey = "seal.useKey"    /// `{}` → `{ key, database }`: the data key the core holds (taken when the    /// vault opened), for the Keychain. Refuses `seal_key_missing`.    public static let sealHeldKey = "seal.heldKey"    /// `{}` → `{ key, made }`: on a phone that has not signed in, standing on    /// the database it started (`seal.status` `makes`), its data key made with    /// no question, for the Keychain as a first sign-in's key is kept.    /// Refuses `seal_key_not_made_here` anywhere else.    public static let sealMakeKey = "seal.makeKey"    /// `{}` → `{ reads: [{ id, client, tables, rows, readAt, said }],    /// heading, none }`: what assistants read, newest first (R4).    public static let unlockReads = "unlock.reads"    // ── Settings, one shape in every app (21 Nov 2026) ──────────────────    /// `{ commit? }` → `{ sections, account, storage, help, about, loading }`:    /// Account, Storage, Help and feedback and About, every word the core's    /// (`crates/cotton-ffi/src/methods/shell_settings.rs`).    public static let shellSettings = "shell.settings"    /// `{ notifications? }` → the same shape from this phone alone (no network, no walk of the app's folder): the    /// list's first frame on a phone that has no whole answer remembered yet.    public static let shellSettingsNow = "shell.settings.now"    /// `{ app: notes|days|messages|story, light?, dark?, ink?, face?, size?, reset? }` → the app's papers, inks,    /// faces, sizes, what stands, the defaults, the colours every screen draws, the preview and the screen's    /// words (shared/DECISIONS.md "Look"; `crates/cotton-ffi/src/phone/look.rs`). Any choice given is written first.    public static let look = "look"    /// `{ commit? }` → `{ title, file_name, text }`: Share a report's text,    /// shown to the person whole before it is shared.    public static let shellReport = "shell.report"    /// `{ expected }` → `{ freed, said }`: Free up space, refused    /// `storage_changed` when more would go than the person agreed to.    public static let shellFreeUp = "shell.freeUp"    // ── Your Claude ──────────────────────────────────    /// `{}` → `{ heading, promise, connections: [{ grantId, memberId, client,    /// said }], none?, mayRead, tables: [{ table, label, access, needsLock,    /// choices: [{ access, label, on }] }], connect, remove? }`: Account ›    /// Your Claude, every word the core's.    public static let assistantScreen = "assistant.screen"    /// `{ table, access, privateKey? }` → `{ table, access }`: On, Ask each    /// time or Off for one sealed table; On for a table left off on the card    /// is signed (`privateKey`, behind presence).    public static let assistantScope = "assistant.scope"    /// `{}` → `{ ended, said }`: Remove: every grant to your Claude ends.    public static let assistantRemove = "assistant.remove"    /// `{}` → `{ tables, access, said }`: Ask each time instead: every table    /// on moves to Ask each time (a narrowing: no lock).    public static let assistantAskEachTime = "assistant.askEachTime"    /// `{}` → `{ ended, said }`: Stop now: every window for a while ends.    public static let assistantStop = "assistant.stop"    /// `{ privateKey }` → `{ grantId, address, said }`: Connect Claude: the    /// grant made with a member key this phone mints; the next connection    /// in 15 minutes is your Claude.    public static let assistantConnect = "assistant.connect"    // ── Approve everywhere and recovery (e2e rulings R7, R9) ──────────────    /// `{}` → `{ waiting: { deviceId, name, line, how, refuse, confirm } |    /// null, mine: { deviceId, line, ask } | null, pollSeconds }`: another    /// device asking to be let in (on a device holding a wrap), or this one    /// waiting (R7b). No Approve: a device comes in only    /// by the code its own ask shows, typed on the `signin.asks` card;    /// `vault.approveDevice` is refused `code_needed` and no shell calls it.    public static let vaultApproval = "vault.approval"    /// `{ deviceId }` → `{ id, deviceId, removed }`: Refuse.    public static let vaultRefuseDevice = "vault.refuseDevice"    /// `{}` → `{ code, google, apple, trusted, holdsVault, offer, alone,    /// signedIn, lines }`: the recovery state and every word drawn for it.    public static let recoveryStatus = "recovery.status"    /// `{ privateKey? }` → `{ code }`: make (or make anew) the recovery code.    public static let recoveryMake = "recovery.make"    /// `{ privateKey? }` → `{ code }`: show the code again.    public static let recoveryShow = "recovery.show"    /// `{ code }` → `{ ok }` or `{ ok: false, problem, line }`: the typo check.    public static let recoveryCheck = "recovery.check"    /// `{ code, privateKey, name? }` → `{ opened, line }`: open by code.    public static let recoveryOpen = "recovery.open"    /// `{ store, privateKey? }` → `{ key }`: the platform key (iCloud Keychain).    public static let recoveryMakePlatform = "recovery.makePlatform"    /// `{ store, key, privateKey, name? }` → `{ opened, line }`.    public static let recoveryOpenPlatform = "recovery.openPlatform"    /// `{ number, name?, privateKey? }` → `{ trusted, line }`: choose a helper.    public static let recoveryTrust = "recovery.trust"    /// `{ privateKey, name? }` → `{ asked, line }`: ask the helper.    public static let recoveryAskHelp = "recovery.askHelp"    /// `{ privateKey, name? }` → `{ opened: false, state }` or `open`'s answer.    public static let recoveryHelped = "recovery.helped"    /// `{}` → `{ asks: [{ id, name, code, line, approve, decline, approved }] }`.    public static let recoveryHelpAsks = "recovery.helpAsks"    /// `{ id }` → `{ approved }`.    public static let recoveryHelpApprove = "recovery.helpApprove"    /// `{ id }` → `{ declined }`.    public static let recoveryHelpDecline = "recovery.helpDecline"    /// `{ id }` → `{ id, payload }`. The typed payload, and `last_used_at`.    /// Refuses `vault_locked`, `vault_sealed_under_the_old_key`, `not_found`.    public static let vaultReveal = "vault.reveal"    /// `{ kind, name, site?, username?, service?, expiresAt?, fields }` →    /// `{ id, kind, name, site, username, service, hint }`. Seals locally.    public static let vaultCreate = "vault.create"    /// `{ id, name?, site?, username?, service?, expiresAt?, fields? }`.    /// Metadata alone needs no unlock; a new payload does.    public static let vaultUpdate = "vault.update"    /// `{ id }` → `{ id, trashed }`. To the bin, and back out of it.    public static let vaultTrash = "vault.trash"    public static let vaultRestore = "vault.restore"    /// `/passwords` — `{ secrets, status, kinds }`.    /// Arguments `kind?`, `q?`, `trashed?`. **Never a payload.**    public static let readSecrets = "read.secrets"    /// `/passwords/[id]` — `{ secret, placements, projects, status }`.    /// **Never a payload.**    public static let readSecret = "read.secret"    // ── placing a secret on a Mac (spec §7.2), and the Mac's import (§7.3) ──    //    // `vault.place` and `vault.unplace` are every device's: the phone names the    // Mac (`read.devices`) and writes the row, and the Mac it names applies it.    // `vault.importDashlane` is a HOST method: it reads a file somebody picked    // in the Finder.    /// `{ secretId, deviceId, path, format?, envName?, mode? }` →    /// `{ id, applied, problem }`. Writes the placement row; on a Mac it is    /// applied at once, elsewhere the Mac it names applies it when it syncs. `path` starts `~/` and carries no `..`; `format` is `raw` (the    /// whole file, no trailing newline) or `env` (one `NAME=` line, the rest of    /// the file kept); `mode` defaults to 0600.    public static let vaultPlace = "vault.place"    /// `{ id }` → `{ id, removed }`. Stops writing it. **The file already    /// written is deliberately left where it is.**    public static let vaultUnplace = "vault.unplace"}// MARK: - What an owner-route refusal carries/// The `details` of a refusal from any of the five HTTP families.////// `phone/owner.rs::refused` builds it: the server's own `code` becomes the/// `CottonCallError.code`, its message the message, and this rides in/// `details`. **The status is why this type exists** — `useApprovedDevices`/// does not retry a 4xx, so a devices list that came back 401 must draw a/// sentence rather than a skeleton that never resolves, and a refusal that/// dropped the status could not tell the two apart.////// `status` is `0` for a failure that never reached a server at all — no/// network, or a socket that hung past the ceiling.public struct OwnerRefusal: Equatable, Sendable {    /// The server's own code, or `"server_refused"` when it sent none.    public let code: String    public let message: String    /// The HTTP status; `0` when nothing was reached.    public let status: Int    /// Present only when the server sent `Retry-After`.    public let retryAfterSeconds: Int?    public init(code: String, message: String, status: Int = 0, retryAfterSeconds: Int? = nil) {        self.code = code        self.message = message        self.status = status        self.retryAfterSeconds = retryAfterSeconds    }    /// Read one off whatever a `call` threw.    ///    /// `nil` for anything that is not a refusal the core built — a decode    /// failure up here is not the server saying no, and a caller that read it    /// as one would show a person the wrong sentence.    public static func from(_ error: any Error) -> OwnerRefusal? {        guard let refusal = error as? CottonCallError else { return nil }        return OwnerRefusal(            code: refusal.code,            message: refusal.message,            status: refusal.details?["status"]?.int ?? 0,            retryAfterSeconds: refusal.details?["retryAfterSeconds"]?.int        )    }    /// Whether the caller should stop asking.    ///    /// A 4xx is the server's settled answer and asking again gets the same    /// one, so the screen draws a sentence. Anything else — including a    /// `status` of `0`, which is a phone with no network — is worth another go.    public var isTerminal: Bool { (400..<500).contains(status) }}