Cotton code
478 lines · 28.4 KB · SwiftRaw
// The Passwords table's source (`PasswordsRecords`): the list, a secret's page,// its columns, the bin, the New acts and the sealed values, each driven// through `ScriptedCore` — so what is asserted is which vault method a verb// calls with which body, and what the surfaces are handed back. These carry// the proofs the old Passwords screens' suites held (`PasswordsTests`,// `SecretPageTests`): search and kind go to the file, the list never holds a// password, the key is published when the file does not know it, Move to bin// is undone by Put back, a new secret is sealed with the value typed under its// button, a shut vault is the kept flow and is tried once more, and a change// to one sealed field keeps the others.//// Every id, name, site and value here is invented — the same nonsense the// crate's own vault suite types.import CottonKitimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class PasswordsRecordsTests: XCTestCase {    static let password = "correct-horse-INVENTED-42"    static let site = "portal.nowhere-invented.test"    /// A scalar counting up, and the public half Rust derives from it — the    /// pair `VaultKeyTests` pins. Not a key anything holds.    static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"    static let publicHalf = "j0DFrbaPJWJK5bIU6nZ6bslNgp09e14a0bpvPiE4KF8"    private nonisolated static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    nonisolated static func definitions() throws -> [TableDefinition] {        let loaded = FixtureDefinitions.load(from: try XCTUnwrap(resources))        XCTAssertEqual(loaded.failures, [])        return loaded.definitions    }    /// A keyring over stores in memory, already holding a key, and a prompt    /// that answers as told — never the Keychain, never a Touch ID sheet in    /// front of a test suite.    static func access(prompt: @escaping @Sendable () async -> DevicePrompt = { .allowed }) -> VaultAccess {        VaultAccess(            keyring: VaultKeyring(                keys: InMemoryVaultKeyStore(seeded: scalar),                cache: InMemorySecretStore([VaultKeyring.publicSlot: publicHalf])),            ask: prompt)    }    static func row(        id: String = "s-1", kind: String = "login", name: String = "Nowhere portal", hint: String? = "D-42",        isSet: Bool = true, legacy: Bool = false, service: String? = nil, trashed: Bool = false    ) -> String {        """        {"id":"\(id)","kind":"\(kind)","name":"\(name)","site":\(kind == "login" ? "\"\(site)\"" : "null"),         "username":\(kind == "login" ? "\"nobody\"" : "null"),"service":\(service.map { "\"\($0)\"" } ?? "null"),         "hint":\(hint.map { "\"\($0)\"" } ?? "null"),"isSet":\(isSet),         "legacy":\(legacy),"lastUsedAt":null,"expiresAt":null,         "trashedAt":\(trashed ? "\"2026-09-08T10:00:00.000Z\"" : "null"),         "createdAt":"2026-09-01T00:00:00.000Z","updatedAt":"2026-09-02T00:00:00.000Z"}        """    }    static func status(hasKey: Bool = true, wrapped: Bool = true, legacyCount: Int = 0) -> String {        #"{"hasKey":\#(hasKey),"wrapped":\#(wrapped),"unlocked":false,"until":null,"legacyCount":\#(legacyCount),"vmkVersion":1}"#    }    static func listAnswer(_ rows: [String], hasKey: Bool = true, wrapped: Bool = true, legacyCount: Int = 0) -> String {        #"{"secrets":[\#(rows.joined(separator: ","))],"status":\#(status(hasKey: hasKey, wrapped: wrapped, legacyCount: legacyCount)),"kinds":{}}"#    }    static func pageAnswer(_ row: String = PasswordsRecordsTests.row(), projects: String = "[]", wrapped: Bool = true) -> String {        #"{"secret":\#(row),"placements":[],"projects":\#(projects),"status":\#(status(wrapped: wrapped))}"#    }    static let payload = #"{"payload":{"kind":"login","password":"\#(password)","notes":"An invented note"}}"#    static func records(        _ replies: [String: ScriptedCore.Reply] = [:], vault: VaultAccess = access()    ) throws -> (PasswordsRecords, ScriptedCore) {        var table: [String: ScriptedCore.Reply] = [            CottonMethod.readSecrets: .ok(listAnswer([row()])),            CottonMethod.readSecret: .ok(pageAnswer()),            CottonMethod.vaultPublishKey: .ok(#"{"id":"vk-1","deviceId":"d","changed":true}"#),            CottonMethod.vaultTrash: .ok(#"{"id":"s-1","trashed":true}"#),            CottonMethod.vaultRestore: .ok(#"{"id":"s-1","trashed":false}"#),            // The core's own bin (4b2351020): a delete it keeps, an undo it takes back.            "records.delete": .ok(#"{"change":{"id":"ch-bin","record_id":"s-1","byline":"user","before":{"name":"Example login"},"after":null,"undoable":true,"receipt":{"kind":"deleted","said":"Moved Example login to the bin","words":[]}},"record":null}"#),            "records.undo": .ok(#"{"change":{"id":"ch-back","record_id":"s-1","byline":"user","before":null,"after":{"name":"Example login"},"undoable":true,"receipt":{"kind":"restored","said":"Put Example login back","words":[]}},"record":null}"#),            CottonMethod.vaultUpdate: .ok(#"{"id":"s-1","changed":true}"#),            CottonMethod.vaultCreate: .ok(#"{"id":"s-new","kind":"login","name":"New login","hint":"D-42"}"#),            CottonMethod.vaultReveal: .ok(payload),            CottonMethod.vaultUnlock: .ok(#"{"until":"2026-09-08T10:05:00.000Z","vmkVersion":1}"#),        ]        for (method, reply) in replies { table[method] = reply }        let core = ScriptedCore(table)        return (PasswordsRecords(core: core, definitions: try definitions(), vault: vault), core)    }    /// The LAST request body for a method, parsed; a `read.*` request's    /// arguments are lifted out of its `{"args": {…}}`.    static func body(_ core: ScriptedCore, of method: String) async -> [String: Any]? {        let calls = await core.calls.filter { $0.method == method }        guard let last = calls.last,            let object = try? JSONSerialization.jsonObject(with: Data(last.requestJSON.utf8)) as? [String: Any]        else { return nil }        return object["args"] as? [String: Any] ?? object    }    static func counted(_ core: ScriptedCore, _ method: String) async -> Int {        await core.methodsCalled().filter { $0 == method }.count    }    private func action(_ id: String, in actions: [RecordAction]) throws -> RecordAction {        try XCTUnwrap(actions.first { $0.id == id }, "no \(id) among \(actions.map(\.id))")    }    // ── The list ───────────────────────────────────────────────────────────    /// RULE: The Passwords list is read.secrets — the search and the kind go to the file, an empty search is not sent, and every row comes in one read.    func testTheListAsksTheFileForTheSearchAndTheKind() async throws {        let (records, core) = try Self.records()        let page = try await records.list(table: "secret", project: nil, query: "  nowhere ", page: 0, where: ["kind": .text("api_key")])        XCTAssertEqual(page.records.map(\.id), ["s-1"])        XCTAssertNil(page.next, "a vault is read whole, so its kind sections count every row")        let sent = await Self.body(core, of: CottonMethod.readSecrets)        XCTAssertEqual(sent?["q"] as? String, "nowhere")        XCTAssertEqual(sent?["kind"] as? String, "api_key")        _ = try await records.list(table: "secret", project: nil, query: "   ", page: 0, where: [:])        let bare = await Self.body(core, of: CottonMethod.readSecrets)        XCTAssertNil(bare?["q"], "an empty search joined the FTS table for nothing")        XCTAssertNil(bare?["kind"])        let later = try await records.list(table: "secret", project: nil, query: nil, page: 1, where: [:])        XCTAssertEqual(later.records, [])    }    /// RULE: A Passwords row carries its plain columns and never a value, a hint or a payload key.    func testNothingTheListHoldsCarriesAPasswordOrItsHint() async throws {        let (records, _) = try Self.records([            CottonMethod.readSecrets: .ok(Self.listAnswer([Self.row(), Self.row(id: "s-2", kind: "api_key", name: "Nowhere key", service: "Nowhere API")])),        ])        let rows = try await records.list(table: "secret", project: nil, query: nil, page: 0, where: [:]).records        XCTAssertEqual(rows.map { $0["kind"] }, [.text("login"), .text("api_key")])        XCTAssertEqual(rows[0]["site"], .text(Self.site))        XCTAssertEqual(rows[1]["service"], .text("Nowhere API"))        let definition = try XCTUnwrap(try Self.definitions().first { $0.id == "secret" })        let columns = Set(definition.columns.map(\.key))        for row in rows {            XCTAssertTrue(Set(row.values.keys).isSubset(of: columns), "\(row.values.keys) carries a column the table lacks")            let drawn = String(describing: row)            XCTAssertFalse(drawn.contains(Self.password))            XCTAssertFalse(drawn.contains("D-42"), "the hint reached a column")        }    }    /// RULE: The list publishes this device's key once when the file does not know it, then reads again.    func testADeviceTheFileDoesNotKnowPublishesItsKeyOnceAndIsToldToWait() async throws {        let (records, core) = try Self.records([            CottonMethod.readSecrets: .ok(Self.listAnswer([], hasKey: false, wrapped: false)),        ])        _ = try await records.list(table: "secret", project: nil, query: nil, page: 0, where: [:])        _ = try await records.list(table: "secret", project: nil, query: "a", page: 0, where: [:])        let published = await Self.counted(core, CottonMethod.vaultPublishKey)        XCTAssertEqual(published, 1, "published once per list opened, not on every read")        let body = await Self.body(core, of: CottonMethod.vaultPublishKey)        XCTAssertEqual(body?["publicKey"] as? String, Self.publicHalf)        let reads = await Self.counted(core, CottonMethod.readSecrets)        XCTAssertEqual(reads, 3, "read, publish, read again — then the search's own read")        let note = await records.listNote(table: "secret")        XCTAssertEqual(note, PasswordFacts.notGivenTheKey)    }    /// RULE: The line over the Passwords list is only the vault's own sentence while this device cannot open what it lists; a device that can says nothing there — no Swift-composed count or "sealed" line — since each secret's page says its sealed state and a view's count is its slip's (architect, 20 Oct 2026).    func testTheLineOverTheListIsOnlyTheVaultsSentence() async throws {        let (records, core) = try Self.records([            CottonMethod.readSecrets: .ok(Self.listAnswer([Self.row(), Self.row(id: "s-2")])),        ])        _ = try await records.list(table: "secret", project: nil, query: nil, page: 0, where: [:])        let open = await records.listNote(table: "secret")        XCTAssertNil(open, "a device that can open them says nothing over the list")        await core.answer(CottonMethod.readSecrets, .ok(Self.listAnswer([Self.row()], legacyCount: 3)))        _ = try await records.list(table: "secret", project: nil, query: nil, page: 0, where: [:])        let old = await records.listNote(table: "secret")        XCTAssertEqual(old, PasswordFacts.statusLine(hasKey: true, wrapped: true, legacyCount: 3))        XCTAssertTrue(old?.contains("3") == true, "the vault's state, counted by the vault")    }    // ── The page ───────────────────────────────────────────────────────────    /// RULE: A secret's page is read.secret, which opens a binned one too, and a gone secret is no record rather than a failure.    func testAPageReadsTheSecretAndAGoneOneIsMissing() async throws {        let (records, core) = try Self.records([            CottonMethod.readSecret: .ok(Self.pageAnswer(Self.row(trashed: true))),        ])        let binned = try await records.get(table: "secret", id: "s-1")        XCTAssertEqual(binned?["trashed_at"], .text("2026-09-08T10:00:00.000Z"))        XCTAssertEqual(binned?["updated_at"], .text("2026-09-02T00:00:00.000Z"))        let sent = await Self.body(core, of: CottonMethod.readSecret)        XCTAssertEqual(sent?["id"] as? String, "s-1")        await core.answer(CottonMethod.readSecret, .ok(#"{"secret":null,"status":{}}"#))        let gone = try await records.get(table: "secret", id: "gone")        XCTAssertNil(gone)    }    /// RULE: A plain column is written with vault.update and no fields, so it needs no unlock, and an emptied one is refused.    func testAPlainColumnIsWrittenWithoutThePayload() async throws {        let (records, core) = try Self.records()        let change = try await records.update(table: "secret", id: "s-1", patch: ["username": .text("somebody")])        XCTAssertEqual(change.after?["username"], .text("somebody"))        let found1 = await Self.body(core, of: CottonMethod.vaultUpdate)        let sent = try XCTUnwrap(found1)        XCTAssertEqual(sent["id"] as? String, "s-1")        XCTAssertEqual(sent["username"] as? String, "somebody")        XCTAssertNil(sent["fields"], "a metadata edit sent a payload, and would have wiped it")        XCTAssertNil(sent["name"], "a column the page did not write was sent")        let unlocks = await Self.counted(core, CottonMethod.vaultUnlock)        XCTAssertEqual(unlocks, 0)        // Undo writes the old value back.        let found2 = await records.canUndo(change: change.id)        XCTAssertTrue(found2)        _ = try await records.undo(change: change.id)        let undone = await Self.body(core, of: CottonMethod.vaultUpdate)        XCTAssertEqual(undone?["username"] as? String, "nobody")        do {            _ = try await records.update(table: "secret", id: "s-1", patch: ["site": .null])            XCTFail("an emptied column looked saved")        } catch {            XCTAssertEqual(error as? SettingsRecordsError, .refusedValue(table: "secret", column: "site"))        }        do {            _ = try await records.update(table: "secret", id: "s-1", patch: ["kind": .text("card")])            XCTFail("the kind was written")        } catch {            XCTAssertEqual(error as? SettingsRecordsError, .refusedColumn(table: "secret", column: "kind"))        }    }    /// RULE: Move to bin asks first and is a change the CORE keeps — records.delete answers "Moved <name> to the bin", records.undo takes it back, never "Couldn't undo that" — and a binned secret offers Put back and no second bin (R10, 4b2351020).    func testTheBinIsAskedFirstUndoneAndPutBack() async throws {        let (records, core) = try Self.records()        let found3 = try await records.get(table: "secret", id: "s-1")        let record = try XCTUnwrap(found3)        XCTAssertNotNil(records.deletion(table: "secret", record: record), "the delete asks first")        let binned = try await records.delete(table: "secret", id: "s-1")        XCTAssertNil(binned.after, "the list no longer holds it")        XCTAssertEqual(binned.id, "ch-bin", "the change is the core's own")        XCTAssertEqual(binned.said?.said, "Moved Example login to the bin")        let trashed = await Self.body(core, of: "records.delete")        XCTAssertEqual(trashed?["table"] as? String, "secret")        XCTAssertEqual(trashed?["id"] as? String, "s-1")        let trashes = await Self.counted(core, CottonMethod.vaultTrash)        XCTAssertEqual(trashes, 0, "the vault's own trash is not called beside the core's delete")        let found4 = await records.canUndo(change: binned.id)        XCTAssertTrue(found4)        let back = try await records.undo(change: binned.id)        XCTAssertEqual(back.id, "ch-back")        let undone = await Self.body(core, of: "records.undo")        XCTAssertEqual(undone?["change_id"] as? String, "ch-bin", "Undo is the core's undo of that change")        let restores = await Self.counted(core, CottonMethod.vaultRestore)        XCTAssertEqual(restores, 0)        await core.answer(CottonMethod.readSecret, .ok(Self.pageAnswer(Self.row(trashed: true))))        let found5 = try await records.get(table: "secret", id: "s-1")        let inBin = try XCTUnwrap(found5)        XCTAssertNil(records.deletion(table: "secret", record: inBin), "a binned secret is put back, not binned again")        let acts = await records.pageActions(table: "secret", record: inBin)        let outcome = try await records.perform(try action("put-back", in: acts), table: "secret", record: inBin)        guard case .change = outcome else { return XCTFail("Put back answered \(outcome)") }        let putBack = await Self.counted(core, CottonMethod.vaultRestore)        XCTAssertEqual(putBack, 1, "Put back on a binned page is the vault's restore")    }    /// RULE: A secret's page offers each of its projects, which opens that project.    func testASecretsProjectsAreActsThatOpenThem() async throws {        let (records, _) = try Self.records([            CottonMethod.readSecret: .ok(Self.pageAnswer(projects: #"[{"id":"p-1","slug":"nowhere","name":"Nowhere Project"}]"#)),        ])        let found6 = try await records.get(table: "secret", id: "s-1")        let record = try XCTUnwrap(found6)        let acts = await records.pageActions(table: "secret", record: record)        let project = try action("project:nowhere", in: acts)        XCTAssertTrue(project.label.contains("Nowhere Project"), "the act names its project")        let outcome = try await records.perform(project, table: "secret", record: record)        XCTAssertEqual(outcome, .navigate(.projectsSlug(slug: "nowhere")))    }    // ── Making one ─────────────────────────────────────────────────────────    /// RULE: A new login asks what it is for, its website and the user name — each its own answer — before the password, and is kept under that name, never as an unnamed "New login"; a document's password is never made here.    func testANewSecretAsksWhatItIsForBeforeItsValue() async throws {        let (records, core) = try Self.records()        let acts = await records.listActions(table: "secret")        let login = try action("new-login", in: acts)        XCTAssertEqual(login.fields.map(\.key), ["name", "site", "username", "password"])        XCTAssertEqual(login.fields.map(\.required), [true, false, false, true], "the website is not needed to keep a login")        // The password is typed blind; the name and user name are read as typed.        XCTAssertEqual(login.fields.map(\.secure), [false, false, false, true])        XCTAssertEqual(acts.first { $0.id == "new-note" }?.fields.last?.secure, false, "a note's body wraps, so it is never a secure line")        XCTAssertEqual(acts.first { $0.id == "new-note" }?.fields.last?.multiline, true)        // Held back until it is named and has its value.        XCTAssertNil(login.answers(["password": Self.password]))        // The value is not trimmed: a credential's own trailing space is part of it.        let answers = try XCTUnwrap(            login.answers(["name": " Example ", "site": "example.com", "username": "walker@example.com", "password": Self.password + " "]))        let outcome = try await records.perform(login, values: answers, table: "secret", record: nil)        guard case .change(let kept) = outcome else { return XCTFail("Keep it answered \(outcome), not a change") }        XCTAssertEqual(kept.after?.id, "s-new")        let found7 = await Self.body(core, of: CottonMethod.vaultCreate)        let sent = try XCTUnwrap(found7)        XCTAssertEqual(sent["kind"] as? String, "login")        XCTAssertEqual(sent["name"] as? String, "Example")        XCTAssertEqual(sent["site"] as? String, "example.com", "the website is its own answer, never the name again")        XCTAssertEqual(sent["username"] as? String, "walker@example.com")        XCTAssertEqual(sent["fields"] as? [String: String], ["password": Self.password + " "])        do {            _ = try await records.perform(login, values: ["name": "example.com", "password": "   "], table: "secret", record: nil)            XCTFail("a blank password was sealed")        } catch {            XCTAssertNotNil(error as? ActionRefused, "a blank password is refused")        }    }    /// RULE: A new secret the shut vault refused is the vault's kept flow, and the list's act opens it and tries once more.    func testANewSecretTheVaultRefusedOpensTheVaultAndIsTriedOnceMore() async throws {        let (records, core) = try Self.records([            CottonMethod.vaultCreate: .refuse(code: "vault_locked", message: "The vault is locked."),        ])        let typed = try action("new-api_key", in: await records.listActions(table: "secret"))        let values = ["name": "An invented service", "key": "an-invented-key"]        do {            _ = try await records.perform(typed, values: values, table: "secret", record: nil)            XCTFail("a shut vault sealed a key")        } catch {            XCTAssertEqual(error as? KeptFlowNeeded, KeptFlowNeeded(.vaultUnlock))        }        var flows: [KeptFlow] = []        let outcome = try await KeptFlowRetry.once({ flow in            flows.append(flow)            await core.answer(CottonMethod.vaultCreate, .ok(#"{"id":"s-key"}"#))            return true        }) {            try await records.perform(typed, values: values, table: "secret", record: nil)        }        guard case .change(let kept) = outcome else { return XCTFail("Keep it answered \(outcome), not a change") }        XCTAssertEqual(kept.after?.id, "s-key")        XCTAssertEqual(flows, [.vaultUnlock])    }    // ── Sealed values ──────────────────────────────────────────────────────    /// RULE: A secret's sealed block is its kind's fields with the masked hint, offered only when this device can open it, and says why when not.    func testTheSealedBlockIsTheKindsFieldsAndSaysWhyItCannotOpen() async throws {        let (records, core) = try Self.records()        let found8 = try await records.get(table: "secret", id: "s-1")        let record = try XCTUnwrap(found8)        let found9 = await records.sealed(table: "secret", record: record)        let summary = try XCTUnwrap(found9)        XCTAssertEqual(summary.fields.map(\.key), ["password", "totp", "notes"])        XCTAssertEqual(summary.mask, "\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}", "a login's hint is never drawn before Show")        XCTAssertTrue(summary.canOpen)        XCTAssertNil(summary.note, "the controls are there, so there is nothing to explain")        await core.answer(CottonMethod.readSecret, .ok(Self.pageAnswer(Self.row(legacy: true))))        let found10 = try await records.get(table: "secret", id: "s-1")        let old = try XCTUnwrap(found10)        let found11 = await records.sealed(table: "secret", record: old)        let legacy = try XCTUnwrap(found11)        XCTAssertFalse(legacy.canOpen)        XCTAssertEqual(legacy.note, PasswordFacts.sealedUnderTheOldKey)        await core.answer(CottonMethod.readSecret, .ok(Self.pageAnswer(wrapped: false)))        let found12 = try await records.get(table: "secret", id: "s-1")        let waiting = try XCTUnwrap(found12)        let found13 = await records.sealed(table: "secret", record: waiting)        let unwrapped = try XCTUnwrap(found13)        XCTAssertFalse(unwrapped.canOpen)        XCTAssertEqual(unwrapped.note, PasswordFacts.waitingForTheKey)    }    /// RULE: Opening a secret is vault.reveal, a shut vault is the kept flow, and any other refusal is the vault's own sentence.    func testOpeningIsTheRevealAndAShutVaultIsTheKeptFlow() async throws {        let (records, core) = try Self.records()        let opened = try await records.open(table: "secret", id: "s-1")        XCTAssertEqual(opened, ["password": Self.password, "notes": "An invented note"])        let sent = await Self.body(core, of: CottonMethod.vaultReveal)        XCTAssertEqual(sent?["id"] as? String, "s-1")        await core.answer(CottonMethod.vaultReveal, .refuse(code: "vault_locked", message: "locked"))        do {            _ = try await records.open(table: "secret", id: "s-1")            XCTFail("a shut vault opened")        } catch {            XCTAssertEqual(error as? KeptFlowNeeded, KeptFlowNeeded(.vaultUnlock))        }        await core.answer(            CottonMethod.vaultReveal,            .refuse(code: "vault_sealed_under_the_old_key", message: "This one is still sealed under the old key."))        do {            _ = try await records.open(table: "secret", id: "s-1")            XCTFail("a row under the old key opened")        } catch {            XCTAssertEqual(error as? ActionRefused, ActionRefused("This one is still sealed under the old key."))        }    }    /// RULE: Changing one sealed field sends the whole payload with that field changed — the notes changed keep the password and the one-time code.    func testChangingOneSealedFieldKeepsEveryOther() async throws {        let (records, core) = try Self.records([            CottonMethod.vaultReveal: .ok(#"{"payload":{"kind":"login","password":"\#(Self.password)","totp":"INVENTEDTOTP","notes":"old"}}"#),        ])        _ = try await records.get(table: "secret", id: "s-1")        try await records.seal(table: "secret", id: "s-1", field: "notes", value: "A new invented note")        let found14 = await Self.body(core, of: CottonMethod.vaultUpdate)        let sent = try XCTUnwrap(found14)        XCTAssertEqual(            sent["fields"] as? [String: String],            ["password": Self.password, "totp": "INVENTEDTOTP", "notes": "A new invented note"])        XCTAssertNil(sent["name"], "a sealed change rewrote a plain column")        do {            try await records.seal(table: "secret", id: "s-1", field: "cvv", value: "123")            XCTFail("a field the login does not have was sealed")        } catch {            XCTAssertEqual(error as? SettingsRecordsError, .refusedColumn(table: "secret", column: "cvv"))        }        // A shut vault refuses before anything is written.        await core.answer(CottonMethod.vaultReveal, .refuse(code: "vault_locked", message: "locked"))        let before = await Self.counted(core, CottonMethod.vaultUpdate)        do {            try await records.seal(table: "secret", id: "s-1", field: "notes", value: "x")            XCTFail("a shut vault was written")        } catch {            XCTAssertEqual(error as? KeptFlowNeeded, KeptFlowNeeded(.vaultUnlock))        }        let after = await Self.counted(core, CottonMethod.vaultUpdate)        XCTAssertEqual(after, before, "a payload was sent without the fields it keeps")    }    /// RULE: A secret with nothing stored offers its primary value to be added, sealed without opening anything first.    func testASecretWithNothingStoredIsGivenItsValueWithoutAReveal() async throws {        let (records, core) = try Self.records([            CottonMethod.readSecret: .ok(Self.pageAnswer(Self.row(hint: nil, isSet: false))),        ])        let found = try await records.get(table: "secret", id: "s-1")        let record = try XCTUnwrap(found)        let summary = await records.sealed(table: "secret", record: record)        XCTAssertEqual(summary?.isEmpty, true)        XCTAssertEqual(summary?.canOpen, false)        try await records.seal(table: "secret", id: "s-1", field: "password", value: Self.password)        let reveals = await Self.counted(core, CottonMethod.vaultReveal)        XCTAssertEqual(reveals, 0, "there was nothing to open")        let sent = await Self.body(core, of: CottonMethod.vaultUpdate)        XCTAssertEqual(sent?["fields"] as? [String: String], ["password": Self.password])    }    /// RULE: The Passwords table answers only its own table; a document's password and every other table are not its list.    func testOnlyTheSecretTableIsAnswered() async throws {        let (records, _) = try Self.records()        let found15 = try await records.tableDefinitions()        XCTAssertEqual(found15.map(\.id), ["secret"])        do {            _ = try await records.list(table: "todo", project: nil, query: nil, page: 0, where: [:])            XCTFail("a todo list was answered by the vault")        } catch {            XCTAssertEqual(error as? RecordsError, .unknownTable("todo"))        }        let acts = await records.listActions(table: "secret")        XCTAssertFalse(acts.contains { $0.id == "new-document" })    }}