Cotton code
202 lines · 11.6 KB · SwiftRaw
import CottonKitimport Foundationimport Speechimport XCTest@testable import CottonUI/// The person's dictation language model (`Capture/VoiceModel.swift`,/// `Capture/NamePhonetics.swift`): spelled by rule, compiled on device, kept/// on device, recompiled when the names move — at most once a day, at/// background priority, keeping only the model in use.@MainActorfinal class VoiceModelTests: XCTestCase {    // MARK: - Spellings    // MARK: - The corpus    /// RULE: the model is compiled from words and names only, never a whole text, and its data stays under a few MB even for a large vocabulary — whole texts and a name-pair frame made a 237 MB corpus per build that held a core of the serving Mac for 23 hours (item 29, 19 Oct 2026).    func testTheCorpusIsNamesOnlyAndSmall() async throws {        let note = (0..<130).map { "Sentence \($0) of the invented ledger walks past the quiet orchard toward Velmora Ridge" }        XCTAssertGreaterThanOrEqual(note.joined(separator: ". ").utf8.count, 10 * 1024, "a 10 KB note")        let names: [String: [String]] = [            "people": (0..<2000).map { "Invented\($0) Person\($0 % 97)" },            "places": (0..<600).map { "Quokkaloom\($0)" },            "projects": (0..<300).map { "Kestrel\($0)" },            "screen": (0..<1000).map { "Zephyr\($0)" },        ]        var json = #"{"names":["#        json += names.map { tag, terms in #"{"tag":"\#(tag)","terms":["\#(terms.joined(separator: "\",\""))"]}"# }.joined(separator: ",")        json += #"],"phrases":[""# + note.joined(separator: "\",\"") + #""]}"#        let corpus = VoiceCorpus(try JSONDecoder().decode(JSONValue.self, from: Data(json.utf8)))        XCTAssertEqual(corpus.names.flatMap(\.terms).count, 3900)        let out = try scratch().appendingPathComponent("corpus.bin")        let locale = Locale(identifier: "en-IN")        try await VoiceModelCompiler.data(corpus, locale: locale, version: "test").export(to: out)        let bytes = try Data(contentsOf: out)        XCTAssertLessThan(bytes.count, 4 * 1024 * 1024, "a vocabulary is kilobytes to a few MB, not \(bytes.count) bytes")        print("voice model corpus: \(bytes.count) bytes for 3900 names")        let text = String(decoding: bytes, as: UTF8.self)        for line in note { XCTAssertFalse(text.contains(line), "a whole text reached the model: \(line)") }        XCTAssertFalse(VoiceModelCompiler.templates.contains { $0.0.components(separatedBy: "<").count > 2 },                       "a frame naming two classes is the square of the vocabulary")    }    // MARK: - The keeper    private final class Counting: VoiceModelCompiling, @unchecked Sendable {        var compiled: [String] = []        var loaded: [String] = []        var priorities: [TaskPriority] = []        func compile(_ corpus: VoiceCorpus, locale: Locale, into files: VoiceModelFiles) async throws {            priorities.append(Task.currentPriority)            try FileManager.default.createDirectory(at: files.folder, withIntermediateDirectories: true)            for url in [files.languageModel, files.vocabulary, files.folder.appendingPathComponent("corpus.bin")] {                try Data("m".utf8).write(to: url)            }            compiled.append(corpus.terms("people").joined(separator: ","))        }        func load(_ files: VoiceModelFiles, locale: Locale) async throws {            priorities.append(Task.currentPriority)            loaded.append(files.fingerprint)        }    }    private final class Box: @unchecked Sendable {        var corpus: VoiceCorpus        var now = Date(timeIntervalSince1970: 1_792_000_000)        init(_ c: VoiceCorpus) { corpus = c }    }    private func corpus(_ people: String...) -> VoiceCorpus {        VoiceCorpus(names: [DictationHints.Group(tag: "people", terms: people)])    }    private func keeper(_ compiler: Counting, root: URL, box: Box, onPower: Bool = true) -> VoiceModelKeeper {        let keeper = VoiceModelKeeper(            compiler: compiler, root: root,            timing: .init(debounce: .milliseconds(60), batteryGrace: .milliseconds(300)),            onPower: { onPower }, resolve: { _ in Locale(identifier: "en-IN") }, now: { box.now })        keeper.attach { box.corpus }        return keeper    }    private func settle(_ until: @escaping @MainActor () -> Bool, within: Duration = .seconds(3)) async throws {        let clock = ContinuousClock()        let deadline = clock.now + within        while !until(), clock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }    }    private func scratch() throws -> URL {        let url = FileManager.default.temporaryDirectory.appendingPathComponent("voicemodel-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)        addTeardownBlock { try? FileManager.default.removeItem(at: url) }        return url    }    /// RULE: a model is compiled at most once a day per locale and only when the names moved: the same names an hour later (or in the next process) compile nothing, and names that move within the day wait for it to end while the written model serves — 83 builds in five days held a core of the serving Mac (item 29, 19 Oct 2026).    func testOneBuildADayAndOnlyWhenTheNamesMoved() async throws {        let root = try scratch()        let compiler = Counting()        let box = Box(corpus("Anvika Rathore"))        let first = keeper(compiler, root: root, box: box)        await first.pass()        try await settle { compiler.loaded.count == 1 }        XCTAssertEqual(compiler.compiled, ["Anvika Rathore"], "the first launch after the cut builds once")        box.now += 3600        await first.pass()        let next = keeper(compiler, root: root, box: box)        await next.pass()        try await settle { compiler.loaded.count == 2 }        XCTAssertEqual(compiler.compiled.count, 1, "the same names an hour later, in this process or the next, compile nothing")        box.corpus = corpus("Anvika Rathore", "Koramangala Iyer")        await next.pass()        try await Task.sleep(for: .milliseconds(400))        XCTAssertEqual(compiler.compiled.count, 1, "names that move within the day wait for it to end")        box.now += 86_400        box.corpus = corpus("Anvika Rathore", "Koramangala Iyer", "Velmora Shah")        await next.pass()        try await settle { compiler.compiled.count == 2 }        XCTAssertEqual(compiler.compiled.last, "Anvika Rathore,Koramangala Iyer,Velmora Shah")    }    /// RULE: the first pass after this layout deletes every corpus an earlier version wrote, in every locale, before anything loads or compiles, and a ready model deletes every other build in its locale — 18 GB of never-cleaned builds sat on the serving Mac (item 29, 19 Oct 2026).    func testOldCorporaGo() async throws {        let root = try scratch()        let fm = FileManager.default        for old in ["en-IN/aaaa", "en-IN/bbbb", "hi-IN/cccc"] {            let folder = root.appendingPathComponent(old)            try fm.createDirectory(at: folder, withIntermediateDirectories: true)            for file in ["model", "vocabulary", "corpus.bin"] { try Data(count: 4096).write(to: folder.appendingPathComponent(file)) }        }        try fm.createDirectory(at: root.appendingPathComponent("en-IN/half-written"), withIntermediateDirectories: true)        let compiler = Counting()        let box = Box(corpus("Anvika Rathore"))        let keeper = keeper(compiler, root: root, box: box)        await keeper.pass()        try await settle { compiler.loaded.count == 1 }        XCTAssertEqual(compiler.loaded.count, 1, "no earlier model is loaded: it is gone before anything else")        let fingerprint = box.corpus.fingerprint(locale: "en-IN")        XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path).sorted(), ["en-IN", "layout"])        XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.appendingPathComponent("en-IN").path).sorted(), ["built", fingerprint].sorted())        try fm.createDirectory(at: root.appendingPathComponent("en-IN/half-written"), withIntermediateDirectories: true)        box.now += 86_400        box.corpus = corpus("Anvika Rathore", "Koramangala Iyer")        await keeper.pass()        let next = box.corpus.fingerprint(locale: "en-IN")        try await settle { compiler.loaded.last == next }        try await settle { (try? fm.contentsOfDirectory(atPath: root.appendingPathComponent("en-IN").path).count) == 2 }        XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.appendingPathComponent("en-IN").path).sorted(), ["built", next].sorted(),                       "a ready model deletes every other build in its locale")    }    /// RULE: compiling and loading run at background priority: the system's compiler works at the priority it is asked at, and on the serving Mac it must never take a core from the app that serves (item 29, 19 Oct 2026).    func testBuildsRunAtBackgroundPriority() async throws {        XCTAssertEqual(VoiceModelKeeper.buildPriority, .background)        let compiler = Counting()        let keeper = keeper(compiler, root: try scratch(), box: Box(corpus("Anvika Rathore")))        await keeper.pass()        try await settle { compiler.loaded.count == 1 }        XCTAssertEqual(compiler.priorities, [.background, .background])    }    // MARK: - On device    /// RULE: the compiled model lives in the app's own folder, excluded from backup, never in a database's folder — it is rebuilt from the records, which are what is backed up and synced.    func testTheModelFolderIsExcludedFromBackupAndIsTheAppsOwn() throws {        var root = try scratch().appendingPathComponent("VoiceModel", isDirectory: true)        VoiceModelKeeper.excludeFromBackup(&root)        let values = try root.resourceValues(forKeys: [.isExcludedFromBackupKey])        XCTAssertEqual(values.isExcludedFromBackup, true)        let real = VoiceModelKeeper.defaultRoot()        XCTAssertEqual(real.lastPathComponent, "VoiceModel")        XCTAssertTrue(real.path.contains("/Application Support/"), real.path)        XCTAssertFalse(real.path.contains("CottonDB"), "never the person's database folder")    }    /// RULE: compiling the person's model calls no network and no model: the corpus is read from this device's core and compiled by the system on device — nothing in it leaves.    func testCompilingCallsNoNetworkAndNoModel() throws {        let banned = ["URLSession", "URLRequest", "NWConnection", "import Network", "FoundationModels",                      "LanguageModelSession", "callRaw(", "feedbackSend", "Reporting.report", "upload"]        for path in ["apps/cotton/Sources/CottonUI/Capture/VoiceModel.swift", "apps/cotton/Sources/CottonUI/Capture/NamePhonetics.swift"] {            let code = SourceSweep.withoutComments(try SourceSweep.mustRead(path, ownedBy: "voicemodel"))            for word in banned {                XCTAssertFalse(code.contains(word), "\(path) reaches for \(word)")            }        }    }    /// RULE: the compiled model never rides in a report, a sync or a backup: no source that builds a report or syncs or backs up names it.    func testNoReportOrSyncCarriesTheModel() throws {        let leaks = try SourceSweep.swiftSources().filter { file in            let code = SourceSweep.withoutComments(file.text)            let carries = file.name.hasPrefix("CottonUI/Feedback/") || code.contains("FeedbackSendRequest(")                || file.name.contains("Sync") || file.name.contains("Backup")            return carries && (code.contains("VoiceModelFiles") || code.contains("VoiceModelKeeper") || code.contains("VoiceCorpus"))        }        XCTAssertEqual(leaks.map(\.name), [])    }}