Cotton code
694 lines · 41.1 KB · SwiftRaw
// A Swift screen's answer keys, held against the keys the crate writes.//// THE GAP THIS CLOSES. A `read.*` answer is a `JSONValue` tree and a screen// reads it by spelling keys: `row.text("title")`, `answer["todos"]`. Nothing// between the two halves is a compiler — a key the crate never writes reads as// `nil`, and `nil` draws as nothing, which is the silent wrong answer this repo// bans wearing its quietest face: a person looking at a row with no title and// no way to know one was ever there. The typed `Boundary+4e.swift` structs// this sweep replaces (I3) made an ABSENT key throw for a defaulted property// and made a MISSPELLED one decode to a default, so they caught half of it at// runtime and none of it in a test. This catches all of it before a build.//// The repo already knows this shape: `CatalogueGuardTests` reads the tool// catalogue by path and holds every `run("tool", [args])` against it;// `BoundaryContractTests` holds every `"read.…"` name against `READS`. This is// the third leg — the KEYS of the answers.//// WHAT THE SWEEP CAN AND CANNOT REACH — the floor is a floor, and the next// reader should know where it stops://   • Reached, on the Swift side: every string literal spelled as an accessor//     argument — `.text("x")`, `.untrimmed("x")`, `.number("x")`,//     `.decimal("x")`, `.minor("x")`, `.flag("x")`, `.list("x")`, `.strings("x")` — and every//     literal subscript `["x"]` that is a READ (not a dictionary-literal key//     `["x": …]`, which is an argument name and `CatalogueGuardTests`' to//     hold, and not an assignment `["x"] = …`). Comments are blanked first, so//     a doc comment quoting a key is not a call site.//   • Reached, on the Rust side: every `"key":` inside a `json!({…})` block,//     every `.insert("key"`, every `answer["key"] =`, every//     `("camelKey", "snake_column")` pair handed to a row helper, every//     `put_…(out, "key", …)`, every local writer's `put("key", …)` and every bare `"key",` on a line of its own (a//     key list), in the files the `READS` table names as answering a read//     (resolved from each `ReadSource::Query(day::alarms)` ///     `Controller(boot)` / `Composed(…)` path), plus the files `alwaysRead`//     names outright, each with its reason, plus every tool handler under//     `cotton-tools/src/mcp/handlers/` — because a `ReadSource::Tool` read//     answers the TOOL's JSON, whose keys are written there and nowhere in the//     phone crate — plus the catalogue's property names, because a tool stores//     what it was sent and a read hands the stored JSON back as it is. And the//     `pub field:` names (camel-cased) and `#[serde(rename = "…")]` names of//     the structs the crate serialises whole (`serde_json::to_value`), in the//     answering files and in `serdeShapes` below — a NAMED list, each entry//     saying which key sent a reader there. And `promptedKeys`: a key a//     language model chooses in the spelling a prompt asks for, held against//     the prompt's own text.//   • NOT reached: a key held in a variable (`row.text(field)`), a key built//     by `format!` on the Rust side (the `linkedRecordFacts` map is keyed by//     id — its VALUES' keys are reached, the ids are not), a key whose writer//     is not in the tree (the recorder's segment manifest — `excused`, by//     name, with why), and WHICH read a key belongs to. The universe is one set across every read://     a `"title"` spelled in the todos screen passes because SOME read writes//     `title`, not because `read.todos` does. That is the price of the//     scaffold's shape — the read is named in the route table//     (`RouteScreen.swift`) and the keys in the screen file — and it still//     catches every misspelling, every stale rename and every key that was//     never written by anything, which is the whole class of defect. A//     per-read universe is the next step if the crate ever declares answer//     shapes; today it does not.//// Path ownership (rule (b) of AGENTS.md's by-path guard rule): every path// below is the RUST FFI lane's (`crates/cotton-ffi/src/phone/…`), the RUST// TOOLS lane's (`crates/cotton-tools/src/mcp/handlers/`), or — where a row's// spelling is the domain's and not the phone crate's — a named// `cotton-core` / `cotton-server` file. Grep them repo-wide// (test directories and every open worktree included) before moving one.// `SourceSweep.mustRead` makes a read that finds nothing fail loudly, with the// path in the message, before any comparison runs.import CottonKitimport Foundationimport XCTest// MARK: - The universe, out of the Rustenum ReadKeyUniverse {    static let ffiLane = "Rust FFI (the phone's reads)"    static let toolsLane = "Rust tools (the MCP handlers)"    static let tablePath = "crates/cotton-ffi/src/phone/reads.rs"    static let handlersDir = "crates/cotton-tools/src/mcp/handlers"    /// The four files the brief names, read whether or not the table names    /// them today — a read the table stops naming is still a file a screen    /// may be spelling keys against until its screen goes.    static let alwaysRead = [        "crates/cotton-ffi/src/phone/reads.rs",        "crates/cotton-ffi/src/phone/reads_work.rs",        "crates/cotton-ffi/src/phone/reads/day.rs",        "crates/cotton-ffi/src/phone/reads/person.rs",        "crates/cotton-ffi/src/phone/traffic.rs",        // Storage-v1's row summary and refusal are assembled outside traffic.rs.        "crates/cotton-ffi/src/phone/storage.rs",        // `city.search`'s rows (`lat`, `lon`, `label`, `timezone`), which every        // place pick reads through `CityPlace`: a method, not a `ReadSource`.        "crates/cotton-ffi/src/phone/city.rs",        // The chat state the two thread reads MERGE into their rows — `read.threads`        // and `read.thread` resolve to `traffic.rs`, which hands each row to        // `chat::own_list_state` / `own_thread_state` for `readSeq`, `unreadMarkedAt`,        // `pinnedAt`, the draft. Not a `ReadSource`, so the table cannot name it.        "crates/cotton-ffi/src/phone/chat.rs",        // The picture keys the same reads and `read.callLog` stamp afterwards —        // `pictureKey` on each conversation and call, `memberCount` on a group's        // header. Not a `ReadSource` either.        "crates/cotton-ffi/src/phone/pictures.rs",        // The one NON-read method whose answer a screen reads: `/messages/import`        // is on `READ_LESS` and draws what `import.whatsappExport` answered        // (`needs`, `imported`, `media.copied` / `omitted`). A screen spelling        // those keys is held here for the same reason a read's are.        "crates/cotton-ffi/src/phone/whatsapp_import.rs",        // `export.build` is on `READ_LESS` too: the Home footer draws what it        // answered (`path`, `fileName`, `recordCount`, `sizeBytes`).        "crates/cotton-ffi/src/phone/export.rs",        // `/rejected` is on `READ_LESS` as well, and for a reason no read could        // change: `_parked` is DEVICE-LOCAL and never syncs, so the        // parked writes are this device's own diagnosis rather than anything in        // the person's database. The screen draws what `sync.rejected` answered        // (`opId`, `table`, `reason`, `direction`, `at`, `retryable`) and what        // `sync.retryRejected` answered (`folded`, `stillRejected`).        "crates/cotton-ffi/src/phone/rejected.rs",        // The pairing and device methods answer the phone's own JSON —        // `pairingId`, `code`, `expiresAt`, the approved list — from the phone        // crate and from the owner routes on the server it forwards to.        "crates/cotton-ffi/src/phone/devices.rs",        "crates/cotton-server/src/routes/devices.rs",        // The words the reads share with the core's generic read (tool format        // Spec 0: one copy of each rule) — `read.session`'s and the queue's        // words (`session_words`), `read.devices`' role, health and disk line        // (`device::words`). The reads call them; the keys are written there.        "crates/cotton-tools/src/session_words.rs",        "crates/cotton-core/src/device/words.rs",        // AND THE STEPS INSIDE A JOB, which are the RUNNER's shape and not the        // row's. `job_json` hands `steps_json` back untouched, and that column        // is written by `service::step_json` from the protocol's own        // `StepState`: `number`, `result`, `startedAt`, `stoppedAt`,        // `logIndex`, `logLength`. A step has NO `name`, NO `status` and NO        // `finishedAt`, which is why the run page reads it through        // `RepoFacts.step…` rather than through `runStamp` — and why this file        // has to be here rather than `ci.rs` being assumed to cover it.        "crates/cotton-server/src/ci/service.rs",        // The RUNNERS and the VARIABLES on the same panel, and the LOG. All        // three are methods rather than reads, and mechanically so:        // `cotton_repo_vars` is in `SERVER_ONLY_TABLES` — specced, synced        // between servers, never handed to a device — so there is no replica        // row for a `ReadSource` to read; `cotton_repo_runners` syncs since v29        // but what the panel wants is the serving Mac's live registrations;        // and a job's log is LINES in a file on the serving Mac, which is why        // `/repos/[id]/runs/[run]/jobs/[job]` is `READ_LESS`. So `lines`,        // `next`, `finished`, `uuid`, `labels`, `lastSeenAt` and `vars` are        // written by the owner routes behind `phone/repos.rs` and        // `phone/code.rs`, both already read above, and by the owner routes        // themselves, here.        "crates/cotton-server/src/routes/ci.rs",        // And THIS MAC'S OWN RUNNER, which is a host FFI answer and not a read        // for the same mechanical reason: `code.runnerState` reports the state        // of a SUPERVISOR — a child process of this app — so `state`,        // `sentence`, `enabled`, `capacity`, `registered`, `helperPath`,        // `since` and `attempt` are composed in the shell beside it        // (`HelperController::runner_state`) and by no answering file the table        // can name.        "crates/cotton-ffi/src/shell/helpers.rs",        // The CODE CREDENTIALS (`ctg_`) the same Settings panel draws. They are        // three METHODS and no read: the grant syncs since v29, but what the        // panel needs is the serving Mac's answer right now, which no replica        // stands in for (`crates/cotton-ffi/src/phone/code.rs` says it at        // length). So        // `credentials` is written by the owner route and the row's own keys —        // `deviceId`, `scope`, `lastUsedAt`, `revokedAt`, and `secret`, which        // the mint answers exactly once — by the credential type beside it, and        // by no answering file the table can name.        "crates/cotton-server/src/routes/code_credentials.rs",        "crates/cotton-server/src/code/credentials.rs",        // THE HOUSEHOLD'S REFUSAL OF THIS MAC, which the Devices screen draws.        // Two host METHODS and no read — the refusal is a row in `registry.db`,        // which reaches no replica — so `householdRefusal`, `outcome` and        // `cleared` are written by the method file, and the        // refusal's own `refusedAt`, `clearable`, `notClearable` and `sentence`        // by the shell that judges it against this Mac (`Controller::        // household_refusal_json`), neither of them a file the table can name.        "crates/cotton-ffi/src/methods/household_refusal.rs",        "crates/cotton-ffi/src/shell/controller.rs",        // THE DEBUG GROUP, which the Debug screen draws from `diagnostics.debug`.        // A host METHOD and no read — it reports this device's own files and        // build, which reach no replica — so `sections` and `removals` are        // written by the shell's diagnostics, and each refused copy's `token`,        // `databaseName`, `filename`, `schemaVersion`, `bundleId`, `build` and        // `reason` by the offer list beside it (`refused_copies::offers`),        // neither of them a file the table can name.        "crates/cotton-ffi/src/shell/diagnostics.rs",        "crates/cotton-ffi/src/shell/refused_copies.rs",        // RULE: Shared feedback delivery is still a wire answer. Its writer        // moved into cotton-tools; reach that writer rather than excuse keys.        "crates/cotton-tools/src/feedback_delivery.rs",    ]    /// The tool catalogue — the RUST TOOLS lane's, generated from    /// `cotton-tools`' own declarations. A tool stores the properties it was    /// sent (`gitRef`, `groupLabel`, `buyerContact`) in a JSON column and a    /// read hands that column back parsed, so a property name is an answer    /// key. `CatalogueGuardTests` reads the same file for the other direction.    static let cataloguePath = "crates/cotton-tools/src/mcp/catalogue.rs"    /// Generic records.get/list projects the columns declared by these native    /// definitions; the writer loops over column keys rather than spelling them.    static let recordDefinitions = ["crates/cotton-core/definitions/story.json"]    /// Structs the crate serialises whole with `serde_json::to_value`, whose    /// field names are therefore answer keys. Each entry names the key that    /// sent a reader to it; an entry no key needs is deleted, not kept.    static let serdeShapes: [(path: String, lane: String, because: String)] = [        ("crates/cotton-store/src/storage_rules.rs", "cotton-store", "Storage-v1 serialises StorageRow: heldBytes, freeableBytes, heldCount, totalCount, measuredAt, isThisDevice"),        ("crates/cotton-client/src/media/storage.rs", "cotton-client", "storage.freeUp serialises Applied: removed, freedBytes, errors and the post-application rows"),        ("crates/cotton-core/src/rules/summaries.rs", "cotton-core", "`staleness` — read.person's summary"),        ("crates/cotton-server/src/news/types.rs", "cotton-server", "`sinceIso`, `publisher` — the news rows the server writes"),        ("crates/cotton-core/src/messages/mod.rs", "cotton-core", "`contact` — read.starred hands the stored `media` column back whole (`MessageMedia`)"),        ("crates/cotton-core/src/rules/search_everything.rs", "cotton-core", "`rank`, `struck`, `journal` — read.find serialises the engine's hits whole"),        ("crates/cotton-server/src/repos/reader.rs", "cotton-server", "`hunks`, `header`, `oldPath`, `stats`, `truncated` — the commit page and the history are READ-LESS (`repo.commit` / `repo.history`), and the clone's own reader serialises `CommitDetail` whole, so its field names are the keys those two screens spell"),        ("crates/cotton-core/src/definitions/mod.rs", "cotton-core", "`hidden`, `title_lines` — `definitions.catalogue` answers each `TableDefinition` whole, and the table editor reads a column's `hidden` and a slip's `title_lines` off it"),    ]    /// Keys a language model chooses, in the spelling a PROMPT asks for. The    /// screen must spell them the same way, and the only Rust that knows the    /// spelling is the prompt's own text — so each key is held against the    /// file that asks for it, as a word, and a prompt that stops asking fails    /// here rather than letting the screen go quiet.    static let promptedKeys: [(key: String, path: String, lane: String)] = [        ("account_last4", "crates/cotton-server/src/documents/profile.rs", "cotton-server (the documents profile prompt)"),        ("total_minor", "crates/cotton-server/src/documents/profile.rs", "cotton-server (the documents profile prompt)"),        ("due_date", "crates/cotton-server/src/documents/profile.rs", "cotton-server (the documents profile prompt)"),    ]    /// Every file the `READS` table's `ReadSource::…(path)` entries resolve    /// to, relative to the repo root — `day::alarms` is `reads/day.rs`,    /// `super::reads_work::projects` is `reads_work.rs`,    /// `crate::phone::activity::activity` is `activity.rs`,    /// `crate::methods::host_settings::device_page` is `src/methods/host_settings.rs`, and a bare    /// `boot` is `reads.rs` itself.    static func answeringFiles(in table: String) -> [String] {        let pattern = #"ReadSource::(?:Query|Controller|Composed)\(([A-Za-z_:]+)\)"#        guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] }        let code = SourceSweep.withoutComments(table)        let range = NSRange(code.startIndex..., in: code)        var files: Set<String> = []        for match in regex.matches(in: code, range: range) {            guard let hit = Range(match.range(at: 1), in: code) else { continue }            let segments = code[hit].components(separatedBy: "::").filter { !$0.isEmpty }            // The last segment is the function; the rest is the module path.            let modules = segments.dropLast().filter { $0 != "crate" && $0 != "phone" && $0 != "super" }            if segments.first == "crate" {                // A crate-qualified controller may live beside phone, as host                // settings does; resolving it under phone loses its answer keys.                files.insert("crates/cotton-ffi/src/\(segments.dropFirst().dropLast().joined(separator: "/")).rs")            } else if modules.isEmpty {                files.insert("crates/cotton-ffi/src/phone/reads.rs")            } else if modules == ["day"] || modules == ["person"] {                files.insert("crates/cotton-ffi/src/phone/reads/\(modules[0]).rs")            } else {                files.insert("crates/cotton-ffi/src/phone/\(modules.joined(separator: "/")).rs")            }        }        return files.sorted()    }    /// Every tool handler file, walked rather than listed — a list is green on    /// the day a new handler starts writing keys.    static func handlerFiles() -> [String] {        let root = SourceSweep.repoRoot.appendingPathComponent(handlersDir)        var found: [String] = []        let walker = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)        while let url = walker?.nextObject() as? URL {            guard url.pathExtension == "rs", !url.lastPathComponent.hasSuffix("_tests.rs") else { continue }            found.append(handlersDir + "/" + url.path.replacingOccurrences(of: root.path + "/", with: ""))        }        return found.sorted()    }    /// The keys one Rust file writes: `"key":` (a `json!` member, at any    /// depth), `.insert("key"`, `["key"] =`, `("key", "column")`,    /// `put_…(out, "key"`, a local writer's `put("key",` (the device words'    /// columns, `cotton_core::device::words`) and a bare `"key",` line.    static func keys(in rust: String) -> Set<String> {        let code = SourceSweep.withoutComments(rust)        let patterns = [            #""([A-Za-z_][A-Za-z0-9_]*)"\s*:"#,            #"\.insert\(\s*"([A-Za-z_][A-Za-z0-9_]*)""#,            #"\["([A-Za-z_][A-Za-z0-9_]*)"\]\s*=[^=]"#,            #"\(\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*,\s*"[A-Za-z_][A-Za-z0-9_]*"\s*\)"#,            #"put_[a-z_]+\([^,()]+,\s*"([A-Za-z_][A-Za-z0-9_]*)""#,            #"\bput\(\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*,"#,            #"(?m)^\s*"([A-Za-z_][A-Za-z0-9_]*)",\s*$"#,        ]        return matches(patterns, in: code)    }    /// A theme palette is a validated map, so its keys live in the validator's match arms.    static func themeMapKeys(in rust: String) -> Set<String> {        matches([#"\(\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*,[^\n]+?\)\s*=>"#,                 #""([A-Za-z_][A-Za-z0-9_]*)"\s*=>"#], in: SourceSweep.withoutComments(rust))    }    /// The keys a serialised struct writes: every `pub field:` camel-cased    /// (serde's `rename_all = "camelCase"`, which every shape here declares)    /// and every `#[serde(rename = "…")]`, both kept as written too. With    /// `variants: true` — for a file in `serdeShapes`, never the answering    /// files, whose function parameters would read as keys — an enum    /// variant's fields too (`Cue { character: String, … }`), which carry no    /// `pub`.    static func shapeKeys(in rust: String, variants: Bool = false) -> Set<String> {        let code = SourceSweep.withoutComments(rust)        var out = matches([#"#\[serde\(rename\s*=\s*"([A-Za-z_][A-Za-z0-9_]*)"\)\]"#], in: code)        var fields = matches([#"(?m)^\s*pub\s+([a-z_][a-z0-9_]*)\s*:"#], in: code)        if variants {            fields.formUnion(matches([#"(?m)^\s+([a-z_][a-z0-9_]*)\s*:\s+(?:Option<|Vec<|String|bool|i64|u64|f64|usize)"#], in: code))        }        for field in fields {            out.insert(field)            out.insert(camel(field))        }        return out    }    static func camel(_ snake: String) -> String {        let parts = snake.split(separator: "_").map(String.init)        guard let head = parts.first else { return snake }        return head + parts.dropFirst().map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined()    }    private static func matches(_ patterns: [String], in code: String) -> Set<String> {        var out: Set<String> = []        for pattern in patterns {            guard let regex = try? NSRegularExpression(pattern: pattern) else { continue }            let range = NSRange(code.startIndex..., in: code)            for match in regex.matches(in: code, range: range) {                if let hit = Range(match.range(at: 1), in: code) { out.insert(String(code[hit])) }            }        }        return out    }}// MARK: - The key literals, out of the Swift/// One key a screen spelled, where.struct KeyLiteral: Equatable {    let file: String    let line: Int    let key: String}enum ReadKeySweep {    static let accessors: Set<String> = ["text", "untrimmed", "number", "decimal", "minor", "flag", "list", "strings"]    /// Every accessor argument and every literal READ subscript in one file.    static func literals(in text: String, file: String) -> [KeyLiteral] {        let chars = ToolCallSweep.blankingComments(text)        // A typed table-definition index names a table, never a JSON read field.        let code = String(chars)        let pattern = #"@Environment\(\\\.tableDefinitions\)\s+(?:private\s+)?var\s+(\w+)"#        let matcher = try? NSRegularExpression(pattern: pattern)        let definitionIndexes = Set((matcher?.matches(in: code, range: NSRange(code.startIndex..., in: code)) ?? []).compactMap { match -> String? in            guard let range = Range(match.range(at: 1), in: code) else { return nil }            return String(code[range])        })        var found: [KeyLiteral] = []        var line = 1        var i = 0        while i < chars.count {            let ch = chars[i]            if ch == "\n" { line += 1; i += 1; continue }            if ch == "\"" {                // Skip a string that is not one of ours, keeping the line count.                let end = endOfString(chars, from: i)                for k in i..<end where chars[k] == "\n" { line += 1 }                i = end                continue            }            // `.accessor("key")`            if ch == ".", followsAnExpression(chars, before: i), let (name, after) = identifier(chars, from: i + 1), accessors.contains(name),                after < chars.count, chars[after] == "(", after + 1 < chars.count, chars[after + 1] == "\"" {                let end = endOfString(chars, from: after + 1)                let key = String(chars[(after + 2)..<max(after + 2, end - 1)])                if end < chars.count, chars[end] == ")", isKeyShaped(key) {                    found.append(KeyLiteral(file: file, line: line, key: key))                }                i = end                continue            }            // `["key"]` — a subscript READ: it follows an expression (`x["k"]`,            // `f()["k"]`, `x?["k"]`), it is not a dictionary literal (`["k": …]`),            // not an array literal (`= ["k"]`) and not an assignment (`["k"] =`).            if ch == "[", i + 1 < chars.count, chars[i + 1] == "\"", followsAnExpression(chars, before: i) {                let end = endOfString(chars, from: i + 1)                let key = String(chars[(i + 2)..<max(i + 2, end - 1)])                if end < chars.count, chars[end] == "]", isKeyShaped(key) {                    var next = end + 1                    while next < chars.count, chars[next] == " " { next += 1 }                    let assigns = next < chars.count && chars[next] == "="                        && !(next + 1 < chars.count && chars[next + 1] == "=")                    var receiverStart = i                    while receiverStart > 0 && (chars[receiverStart - 1].isLetter || chars[receiverStart - 1].isNumber || chars[receiverStart - 1] == "_" || chars[receiverStart - 1] == ".") { receiverStart -= 1 }                    let receiver = String(chars[receiverStart..<i])                    if !assigns && !definitionIndexes.contains(receiver) {                        found.append(KeyLiteral(file: file, line: line, key: key))                    }                    i = end + 1                    continue                }            }            i += 1        }        return found    }    /// The `read.…` names one file spells — `ScreenRead(… read: "x" …)`, a    /// `"read.x"` literal, or a `CottonMethod.readX` constant — for the    /// failure message. Informational: the universe is not per read.    static func readNames(in text: String, constants: [String: String]) -> [String] {        let code = SourceSweep.withoutComments(text)        var names: Set<String> = []        for pattern in [#"read:\s*"([A-Za-z][A-Za-z0-9]*)""#, #""read\.([A-Za-z][A-Za-z0-9]*)""#] {            guard let regex = try? NSRegularExpression(pattern: pattern) else { continue }            let range = NSRange(code.startIndex..., in: code)            for match in regex.matches(in: code, range: range) {                if let hit = Range(match.range(at: 1), in: code) { names.insert(String(code[hit])) }            }        }        if let regex = try? NSRegularExpression(pattern: #"CottonMethod\.(read[A-Za-z0-9]+)"#) {            let range = NSRange(code.startIndex..., in: code)            for match in regex.matches(in: code, range: range) {                guard let hit = Range(match.range(at: 1), in: code) else { continue }                if let name = constants[String(code[hit])] { names.insert(name) }            }        }        return names.sorted()    }    /// `static let readX = "read.x"` across CottonKit → `readX: x`.    static func readConstants(in sources: [(name: String, text: String)]) -> [String: String] {        var out: [String: String] = [:]        guard let regex = try? NSRegularExpression(pattern: #"static let (read[A-Za-z0-9]+)\s*=\s*"read\.([A-Za-z][A-Za-z0-9]*)""#) else { return out }        for source in sources where source.name.hasPrefix("CottonKit/") {            let code = SourceSweep.withoutComments(source.text)            let range = NSRange(code.startIndex..., in: code)            for match in regex.matches(in: code, range: range) {                guard let constant = Range(match.range(at: 1), in: code), let name = Range(match.range(at: 2), in: code) else { continue }                out[String(code[constant])] = String(code[name])            }        }        return out    }    private static func followsAnExpression(_ chars: [Character], before index: Int) -> Bool {        var back = index - 1        while back >= 0, chars[back].isWhitespace { back -= 1 }        guard back >= 0 else { return false }        let ch = chars[back]        if ch.isLetter {            var start = back            while start > 0, chars[start - 1].isLetter { start -= 1 }            if ["return", "throw", "case", "else", "try", "await"].contains(String(chars[start...back])) { return false }        }        return ch == "_" || ch.isLetter || ch.isNumber || ch == ")" || ch == "]" || ch == "?" || ch == "!"    }    private static func isKeyShaped(_ key: String) -> Bool {        guard let first = key.first, first == "_" || first.isLetter else { return false }        return key.allSatisfy { $0 == "_" || $0.isLetter || $0.isNumber }    }    private static func identifier(_ chars: [Character], from start: Int) -> (String, Int)? {        var i = start        while i < chars.count, chars[i] == "_" || chars[i].isLetter || chars[i].isNumber { i += 1 }        guard i > start else { return nil }        return (String(chars[start..<i]), i)    }    private static func endOfString(_ chars: [Character], from start: Int) -> Int {        var i = start + 1        while i < chars.count {            if chars[i] == "\\" { i += 2; continue }            if chars[i] == "\"" { return i + 1 }            i += 1        }        return chars.count    }}// MARK: - The guardfinal class ReadKeySweepTests: XCTestCase {    private static func universe() throws -> (keys: Set<String>, files: [String]) {        let table = try SourceSweep.mustRead(ReadKeyUniverse.tablePath, ownedBy: ReadKeyUniverse.ffiLane)        XCTAssertTrue(table.contains("pub static READS"), "\(ReadKeyUniverse.tablePath) did not read as the read table")        var files = Set(ReadKeyUniverse.alwaysRead)        files.formUnion(ReadKeyUniverse.answeringFiles(in: table))        var keys: Set<String> = []        for path in files.sorted() {            keys.formUnion(ReadKeyUniverse.keys(in: try SourceSweep.mustRead(path, ownedBy: ReadKeyUniverse.ffiLane)))        }        for path in files.sorted() {            keys.formUnion(ReadKeyUniverse.shapeKeys(in: try SourceSweep.mustRead(path, ownedBy: ReadKeyUniverse.ffiLane)))        }        let handlers = ReadKeyUniverse.handlerFiles()        /// RULE: The handler walk must find handlers before it can enforce declared read keys.        XCTAssertFalse(handlers.isEmpty, "\(ReadKeyUniverse.handlersDir) contains no handlers")        for path in handlers {            keys.formUnion(ReadKeyUniverse.keys(in: try SourceSweep.mustRead(path, ownedBy: ReadKeyUniverse.toolsLane)))        }        keys.formUnion(ReadKeyUniverse.keys(in: try SourceSweep.mustRead(ReadKeyUniverse.cataloguePath, ownedBy: ReadKeyUniverse.toolsLane)))        struct Columns: Decodable {            struct Column: Decodable { let key: String }            let columns: [Column]        }        for path in ReadKeyUniverse.recordDefinitions {            let text = try SourceSweep.mustRead(path, ownedBy: "cotton-core (native record definitions)")            let definition = try JSONDecoder().decode(Columns.self, from: Data(text.utf8))            keys.formUnion(definition.columns.map(\.key))        }        for shape in ReadKeyUniverse.serdeShapes {            keys.formUnion(ReadKeyUniverse.shapeKeys(in: try SourceSweep.mustRead(shape.path, ownedBy: shape.lane), variants: true))        }        for prompted in ReadKeyUniverse.promptedKeys {            let prompt = try SourceSweep.mustRead(prompted.path, ownedBy: prompted.lane)            let asked = try NSRegularExpression(pattern: "\\b" + NSRegularExpression.escapedPattern(for: prompted.key) + "\\b")            XCTAssertNotNil(                asked.firstMatch(in: prompt, range: NSRange(prompt.startIndex..., in: prompt)),                "\(prompted.path) no longer asks the model for `\(prompted.key)` — the screen spelling it draws nothing"            )            keys.insert(prompted.key)        }        keys.formUnion(ReadKeyUniverse.themeMapKeys(in: try SourceSweep.mustRead(            "crates/cotton-core/src/definitions/theme.rs", ownedBy: "cotton-core (theme map validation)")))        return (keys, files.sorted() + handlers)    }    /// Literal subscripts the sweep cannot hold against the crate: a plist,    /// the keychain, a `UserDefaults` record, a JSON the phone's own extension    /// wrote, and one key whose writer has not landed. NAMED, one per line    /// with why, and held live — an entry the sweep no longer finds fails, so    /// the list cannot outgrow the code it excuses. A key the crate writes    /// never belongs here: it belongs in the universe.    static let excused: [(file: String, key: String, why: String)] = [        ("CottonUI/Clips/ClipKeeper.swift", "copied_at", "a column of the clip table, whose definition (clip.json) arrives with rise 139; that rise deletes this entry and adds clip.json to `recordDefinitions`"),        ("CottonUI/Clips/ClipKeeper.swift", "source_device", "a column of the clip table, whose definition (clip.json) arrives with rise 139; that rise deletes this entry and adds clip.json to `recordDefinitions`"),        ("CottonUI/Faces/FaceText.swift", "minor", "an amount column's value in the shared definition format ({minor, currency}), which the generic record verbs will write; until they land the only writer is the bundled fixtures"),        ("CottonUI/Definitions/ContactKeys.swift", "minor", "an amount column's value in the shared definition format ({minor, currency}), read for its sign (`signs`); the generic record verbs will write it, and until they land the only writer is the bundled fixtures"),        ("CottonUI/Scaffold/PinMarker.swift", "pinNumber", "the app's OWN number, not the crate's: `RecordPin.marker` builds this row in Swift and numbers the pins in comment order (`RecordPins`), so no read writes the key. The walkthrough read did until version 33 of the store retired the kind, which is why it was in the universe before and is not now"),    ]    /// RULE: No refusal the app or its scripted core makes carries a method's name as its message: a page draws a refusal's message (a list's note, a "could not be read" state), so a read key built into one at run time reaches the person as "read.members" — a key no literal sweep above can see (architect's review R4, 18 Oct 2026: the Members page's byline and its refusal both said "read.members", from ScriptedCore's unanswered reply). The method rides in the details, for the log.    func testNoRefusalCarriesAMethodsNameAsItsMessage() async throws {        let patterns = [            ##""message"\s*:\s*"\\#?\((method|name|key)\)""##,            #"CottonCallError\([^)]*message:\s*(method|name|key)\s*[,)]"#,            #"message:\s*"\\\((method|name|key)\)""#,        ]        var found: [String] = []        for source in try SourceSweep.swiftSources() {            let code = SourceSweep.withoutComments(source.text)            for pattern in patterns where !(try SourceSweep.matches(pattern, in: code)).isEmpty {                found.append("\(source.name): \(pattern)")            }        }        XCTAssertEqual(found, [], "a refusal whose message is a method's name")        let scripted = ScriptedCore([:])        let answer = try await scripted.callRaw("read.members", requestJSON: "{}")        XCTAssertFalse(answer.contains(##""message":"read.members""##), answer)        XCTAssertTrue(answer.contains(CottonCallError.notOnThisDevice), answer)    }    func testTheTableNamesTheFilesThatAnswerIt() throws {        let table = try SourceSweep.mustRead(ReadKeyUniverse.tablePath, ownedBy: ReadKeyUniverse.ffiLane)        let files = ReadKeyUniverse.answeringFiles(in: table)        /// RULE: Every declared read handler must resolve to an existing source, so the key sweep cannot silently omit its answers.        XCTAssertFalse(files.isEmpty, "the read table names no source files")        for path in files {            _ = try SourceSweep.mustRead(path, ownedBy: ReadKeyUniverse.ffiLane)        }    }    func testCrateQualifiedControllersResolveFromTheCrateRoot() {        // Host-only reads still contribute their JSON keys to the screen guard.        XCTAssertEqual(ReadKeyUniverse.answeringFiles(in:            "ReadSource::Controller(crate::methods::host_settings::device_page)"),            ["crates/cotton-ffi/src/methods/host_settings.rs"])    }    // RULE: A typed definition catalog indexes table ids while a JSON record with the same literal still names an answer key.    func testDefinitionCatalogIndexesAreNotReadKeys() {        let source = #"@Environment(\.tableDefinitions) private var definitions; let table = definitions["email_sender"]; let value = answer["email_sender"]; let json = answer["job"]"#        XCTAssertEqual(ReadKeySweep.literals(in: source, file: "Synthetic.swift").map(\.key), ["email_sender", "job"])    }    func testThemeMapKeysComeFromValidationArms() {        let source = #"match key { ("pencil", value) => check(value), ("tags", Value::Object(tags)) => check(tags), "dyes" => check_dyes(), _ => {} }"#        XCTAssertEqual(ReadKeyUniverse.themeMapKeys(in: source), ["pencil", "tags", "dyes"])    }    /// Synthetic, so it keeps saying what it says after the real call sites    /// are right: every way a key is spelled, and every shape that is NOT one.    func testTheMatcherReadsEverySpellingAndNothingElse() {        let source = """            // a comment quoting .text("commented") and ["alsoCommented"]            let title = row.text("title") ?? ""            let body = row.untrimmed("body")            let n = row.number("count"); let d = row.decimal("sortOrder")            let on = row.flag("enabled"); let xs = row.list("items"); let ss = row.strings("emails")            let nested = answer["person"]?["fullName"]?.string            let args: [String: JSONValue] = ["id": .string(id), "note": .null]            var more: [String: JSONValue] = [:]; more["written"] = .bool(true)            if more["written"] == .bool(true) {}            let field = "dynamic"; let dyn = row.text(field)            let text = "a string mentioning .text(\\"inString\\") and [\\"inString2\\"]"            let path = list["0"]            static let retranscribable = ["ready"]            let two = f(["a", "b"])            let tail = page["lines"]?.rows.last?["kind"]            """        let found = ReadKeySweep.literals(in: source, file: "Synthetic.swift").map(\.key)        XCTAssertEqual(            found,            ["title", "body", "count", "sortOrder", "enabled", "items", "emails", "person", "fullName", "written", "lines", "kind"]        )        let lines = ReadKeySweep.literals(in: source, file: "Synthetic.swift").map(\.line)        XCTAssertEqual(lines.first, 2)        XCTAssertEqual(lines[9], 9, "the `==` comparison on line 9 is a read and the `=` on line 8 is not")        XCTAssertEqual(lines.last, 15, "an array literal (`= [\"ready\"]`, lines 13–14) is not a subscript; a chained one (line 15) is")    }    /// RULE: A contextual RecordValue factory is a value, not a JSON answer accessor; a real receiver's read remains checked.    func testValueFactoriesAreNotReadKeys() {        let text = #"let values: [String: RecordValue] = ["label": .text("Unavailable"), "count": .number(3)]; let name = row.text("name"); put(.text("done"))"#        XCTAssertEqual(ReadKeySweep.literals(in: text, file: "Synthetic.swift").map(\.key), ["name"])        XCTAssertEqual(ReadKeySweep.literals(in: "row\n .text(\"title\")", file: "Synthetic.swift").map(\.key), ["title"])        XCTAssertTrue(ReadKeySweep.literals(in: #"return .text("Unavailable")"#, file: "Synthetic.swift").isEmpty)    }    func testTheRustExtractorReadsEveryShapeAndNothingElse() {        let rust = """            // "commentKey": 1            fn out(row: &Row) -> Value {                json!({                    "id": row.text("id"),                    "dueAt": row.text("due_at"),                    "nested": { "inner": 1 },                })            }            fn more() {                let mut m = Map::new();                m.insert("inserted".to_string(), Value::Null);                answer["assigned"] = json!(1);                if answer["compared"] == json!(1) {}                let s = "not: a key";                let cols = [("storyCount", "story_count"), ("x", y)];                put_text(&mut out, "saidBy", text(row, "author_label"));                put("serving_place", serving_place(device, order));                output("notAPut", 1);                const KEYS: &[&str] = &[                    "resolvedBy",                    "other", "notAlone",                ];            }            """        XCTAssertEqual(            ReadKeyUniverse.keys(in: rust),            ["id", "dueAt", "nested", "inner", "inserted", "assigned", "storyCount", "saidBy", "serving_place", "resolvedBy"]        )        let shape = """            #[derive(Serialize)]            #[serde(rename_all = "camelCase")]            pub struct SummaryRead {                pub summary: ISummary,                pub staleness: Option<SummaryStaleness>,                #[serde(rename = "sinceIso")]                pub since: String,                pub read_minutes: i64,                not_pub: i64,            }            pub enum Element {                Cue {                    character: String,                    extension: Option<String>,                },            }            fn answer(replica: &ReadFile, args: &Map) -> Value {}            """        XCTAssertEqual(            ReadKeyUniverse.shapeKeys(in: shape),            ["summary", "staleness", "sinceIso", "since", "read_minutes", "readMinutes"]        )        XCTAssertEqual(            ReadKeyUniverse.shapeKeys(in: shape, variants: true),            ["summary", "staleness", "sinceIso", "since", "read_minutes", "readMinutes", "not_pub", "notPub", "character", "extension"],            "a variant's fields and a private field are keys of a shape; a function's parameters are not"        )    }}