// The person's own dictation language model, compiled ON THIS DEVICE from// their names and their own phrasing, so the recogniser expects the words they// actually say — "Anvika Rathore", "Koramangala", "the Kestrel invoice" — and// not the English words that sound nearest.//// The source is `read.voiceCorpus` (the Rust core: every name the device's kept// voice pass holds, tagged as the hints are — words and names only, never a// whole text). From it this file builds the system's custom language model// data — the names in short spoken frames ("call <person>", "in <place>") and a// phonetic spelling for each name that reads as romanized Indic// (`NamePhonetics`) — and has the system compile// it (`SFSpeechLanguageModel.prepareCustomLanguageModel`). Dictation then hands// the compiled model to `DictationTranscriber` as// `.customizedLanguage(modelConfiguration:)`, beside the screen's ranked// hundred contextual strings, which stay.//// THE MODEL NEVER LEAVES THE DEVICE. It is written under the app's own// Application Support (never a database file, never a synced folder), marked// excluded from backup, never attached to a report; compiling calls no network// and no model — the system's compiler runs on device over the files written// here. Guards: `VoiceModelTests`.//// TWO PREPARES, MEASURED 14 Oct 2026 (macOS 27, en-IN): a model is heard only// in a process that ran `prepareCustomLanguageModel(ignoresCache: true)` over an// ALREADY-COMPILED model. The first prepare writes the files and is silently// ignored by every session after it, in this process and the next; a second// prepare over the written files is what the recogniser then uses. So// `compile` writes, and `load` — run once per process for every model it// will dictate with — prepares again.//// A CORE OF THE SERVING MAC, MEASURED 19 Oct 2026: the corpus then carried the// person's own lines and a name-pair frame, 237 MB per build, rebuilt on every// change, never cleaned — 83 builds and 18 GB in five days, and the system's// compiler at 99% of a core for 23 hours. So the corpus is names only, a build// runs at most once a day and only when the names moved, at background// priority, and a ready build deletes every other one.importCottonKitimportCottonSpeechimportCryptoKitimportFoundationimportSpeech#if os(iOS)import UIKit#elseif os(macOS)import IOKit.ps#endif/// What the model is compiled from.publicstructVoiceCorpus: Sendable, Equatable {/// Every name, grouped by why it is there (manual, people, places,/// projects, screen) — the hints' own tags.publiclet names: [DictationHints.Group]/// The person's language (BCP-47), when their setting names one.publiclet language: String?publicinit(names: [DictationHints.Group], language: String? = nil) {self.names = namesself.language = language }/// `read.voiceCorpus`'s answer: `{names: [{tag, terms}], language?}`.publicinit(_ read: JSONValue) { names = (read["names"]?.array ?? []).compactMap { group inguardlet tag = group["tag"]?.string else { returnnil }returnDictationHints.Group(tag: tag, terms: group["terms"]?.strings ?? []) } language = read["language"]?.string }/// Which model this corpus compiles to, for `locale`: equal corpora answer/// the same fingerprint on every device, and a changed name changes it.publicfunc fingerprint(locale: String) -> String {var canonical = "v\(VoiceModelCompiler.version)\n\(locale)\n"for group in names { canonical += "#\(group.tag)\n" + group.terms.joined(separator: "\n") + "\n" }return SHA256.hash(data: Data(canonical.utf8)).map { String(format: "%02x", $0) }.joined() }func terms(_ tag: String) -> [String] { names.first { $0.tag == tag }?.terms ?? [] }}/// A compiled model on this device, for one locale: what the recogniser is/// handed. Paths only — the model itself stays where it was written.publicstructVoiceModelFiles: Sendable, Equatable {publiclet locale: Stringpubliclet fingerprint: Stringpubliclet languageModel: URLpubliclet vocabulary: URLinit(locale: String, fingerprint: String, folder: URL) {self.locale = localeself.fingerprint = fingerprint languageModel = folder.appendingPathComponent("model") vocabulary = folder.appendingPathComponent("vocabulary") }var folder: URL { languageModel.deletingLastPathComponent() }/// The system's model data the model was compiled from.var source: URL { folder.appendingPathComponent("corpus.bin") }var isWritten: Bool { [languageModel, vocabulary, source].allSatisfy { FileManager.default.fileExists(atPath: $0.path) } }}/// The two steps a model takes, behind a seam so the keeper's timing is/// tested without the system compiler.publicprotocolVoiceModelCompiling: Sendable {/// Write the model for `corpus` into `files`' folder.func compile(_ corpus: VoiceCorpus, locale: Locale, into files: VoiceModelFiles) asyncthrows/// Make a written model the one this process's recogniser hears with.func load(_ files: VoiceModelFiles, locale: Locale) asyncthrows}/// The system's compiler, on device.publicstructVoiceModelCompiler: VoiceModelCompiling {/// Bumped when what is compiled from a corpus changes, so every device/// recompiles once — and, as the folder's layout, clears every model an/// earlier version wrote (`VoiceModelKeeper.clearEarlierLayout`).publicstaticlet version = 2/// How often a name is said in each frame. Short frames — what a person/// says AROUND a name — rather than whole sentences, so the model learns/// the name's company, not a script. One class per frame: a frame naming/// two is every pair of names, the square of the vocabulary (the 237 MB of/// 19 Oct 2026).staticlet templates: [(String, Int)] = [ ("<person>", 40), ("with <person>", 12), ("to <person>", 12), ("call <person>", 12), ("ask <person>", 10), ("tell <person>", 8), ("message <person>", 8), ("<place>", 20), ("in <place>", 12), ("at <place>", 12), ("to <place>", 10), ("from <place>", 6), ("<project>", 20), ("the <project>", 12), ("about <project>", 8), ("for <project>", 8), ("<name>", 10), ]publicinit() {}publicfunc compile(_ corpus: VoiceCorpus, locale: Locale, into files: VoiceModelFiles) asyncthrows {tryFileManager.default.createDirectory(at: files.folder, withIntermediateDirectories: true)tryawaitSelf.data(corpus, locale: locale, version: String(files.fingerprint.prefix(16))).export(to: files.source)tryawait prepare(files) }/// The second prepare, over the same source and the model it wrote — the/// source stays beside the model for exactly this (on this device, in the/// same excluded folder).publicfunc load(_ files: VoiceModelFiles, locale: Locale) asyncthrows {tryawait prepare(files) }privatefunc prepare(_ files: VoiceModelFiles) asyncthrows {let configuration = SFSpeechLanguageModel.Configuration(languageModel: files.languageModel, vocabulary: files.vocabulary)tryawait SFSpeechLanguageModel.prepareCustomLanguageModel(for: files.source, configuration: configuration, ignoresCache: true) }staticlet identifier = (Bundle.main.bundleIdentifier ?? "cotton") + ".dictation"/// The system's model data for a corpus: the names in their frames, each/// name on its own, and the spellings.staticfunc data(_ corpus: VoiceCorpus, locale: Locale, version: String) -> SFCustomLanguageModelData {let data = SFCustomLanguageModelData(locale: locale, identifier: identifier, version: version)let people = corpus.terms("people") + corpus.terms("manual")// A person is called by their first name as often as their whole one.let firstNames = people.compactMap { name -> String? inlet parts = name.split(separator: " ")return parts.count > 1 ? String(parts[0]) : nil }let classes: [String: [String]] = ["person": unique(people + firstNames),"place": unique(corpus.terms("places")),"project": unique(corpus.terms("projects")),"name": unique(corpus.terms("screen")), ]let generator = SFCustomLanguageModelData.TemplatePhraseCountGenerator()for (name, values) in classes where !values.isEmpty { generator.define(className: name, values: values) }for (template, count) in templateswhere classes.allSatisfy({ name, values in !values.isEmpty || !template.contains("<\(name)>") }) { generator.insert(template: template, count: count) } data.insert(phraseCountGenerator: generator)for (grapheme, readings) in pronunciations(people + corpus.terms("places"), locale: locale) { data.insert(term: SFCustomLanguageModelData.CustomPronunciation(grapheme: grapheme, phonemes: readings)) }return data }/// Each name word's spellings that the locale's recogniser accepts: every/// phoneme in a reading must be one the locale names, or the reading goes —/// a spelling is never bent to fit.staticfunc pronunciations(_ names: [String], locale: Locale) -> [(String, [String])] {let accepted = Set(SFCustomLanguageModelData.supportedPhonemes(locale: locale))var seen = Set<String>()var out: [(String, [String])] = []for name in names {for (grapheme, readings) inNamePhonetics.words(of: name) where seen.insert(grapheme.lowercased()).inserted {let fits = readings.filter { reading in reading.split(separator: " ").allSatisfy { accepted.contains(String($0)) } }if !fits.isEmpty { out.append((grapheme, fits)) } } }return out }privatestaticfunc unique(_ terms: [String]) -> [String] {var seen = Set<String>()return terms.filter { !$0.isEmpty && seen.insert($0.lowercased()).inserted } }}/// Keeps the compiled model current: reads the corpus when it may have/// changed, debounced, recompiles when its fingerprint moved — at most once in/// `Timing.interval`, at background priority, on power when it can — and loads/// the model into this process so dictation hears with it.////// On disk, per locale: `VoiceModel/<locale>/<fingerprint>/` (the one model/// in use: `corpus.bin`, `model`, `vocabulary`) and `VoiceModel/<locale>/built`/// (when it was compiled); `VoiceModel/layout` names the version that wrote/// the folder.@MainActorpublicfinalclassVoiceModelKeeper {publicstaticlet shared = VoiceModelKeeper()publicstructTiming: Sendable {/// From the last change to the corpus read: a burst of edits is one/// compile.publicvar debounce: Duration/// On battery, how much longer a compile waits for power before it/// runs anyway — preferred, never required.publicvar batteryGrace: Duration/// At most one compile per locale in this long: a name that moves/// within the day waits for the day to end, while the model already/// written serves.publicvar interval: Durationpublicinit(debounce: Duration = .seconds(30), batteryGrace: Duration = .seconds(600), interval: Duration = .seconds(86_400)) {self.debounce = debounceself.batteryGrace = batteryGraceself.interval = interval } }/// Compiling and loading run at background priority: the system's/// compiler (`localspeechrecognition`) 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). nonisolated staticlet buildPriority: TaskPriority = .backgroundprivatelet compiler: any VoiceModelCompilingprivatelet root: URLprivatelet timing: Timingprivatelet onPower: @MainActor () -> Boolprivatelet resolve: @Sendable (Locale) async -> Locale?privatelet now: @Sendable () -> Dateprivatevar read: (@Sendable () async -> VoiceCorpus?)?/// Loaded in THIS process, by resolved locale.privatevar ready: [String: VoiceModelFiles] = [:]/// The fingerprint being compiled or loaded, by locale.privatevar pending: [String: String] = [:]privatevar debounced: Task<Void, Never>?privatevar work: [String: Task<Void, Never>] = [:]privatevar passed = falsepublicinit( compiler: any VoiceModelCompiling = VoiceModelCompiler(), root: URL = VoiceModelKeeper.defaultRoot(), timing: Timing = Timing(), onPower: @escaping @MainActor () -> Bool = VoiceModelKeeper.isOnPower, resolve: @escaping @Sendable (Locale) async -> Locale? = VoiceModelKeeper.transcriberLocale, now: @escaping @Sendable () -> Date = Date.init ) {self.compiler = compilerself.root = rootself.timing = timingself.onPower = onPowerself.resolve = resolveself.now = now }/// The core to read the corpus from — `read.voiceCorpus`, answered on/// device.publicfunc attach(_ core: any CottonCalling) { attach { try? awaitVoiceCorpus(core.callJSON(CottonMethod.readVoiceCorpus)) } }func attach(_ read: @escaping @Sendable () async -> VoiceCorpus?) {self.read = read }/// A `data` event: names live in records and the vocabulary, phrasing in/// thoughts and sent messages; any of them moving MAY change the corpus.publicfunc receive(_ event: ClientEvent) {guardcase .data(let tables, _, _) = event, tables.contains(where: Self.sources.contains) else { return } changed() }/// The voice pass republishes this table whenever a name it holds moved/// (`voice_words::refresh`), so the records themselves need not be listed.staticlet sources: Set<String> = ["cotton_voice_vocabulary", "cotton_inbox_items", "cotton_msg_messages"]/// Something the corpus is read from moved: read it after the debounce,/// every further change restarting the wait.publicfunc changed() { debounced?.cancel()let wait = timing.debounce debounced = Task { [weakself] intry? awaitTask.sleep(for: wait)guard !Task.isCancelled else { return }awaitself?.pass() } }/// The first microphone of a process reads the corpus at once (a model/// compiled earlier is loaded, not recompiled); later ones read nothing.publicfunc ensure() {guard !passed else { return } passed = trueTask { [weakself] inawaitself?.pass() } }/// The model dictation in `language`'s locale hears with, when this/// process has one loaded.publicfunc model(for requested: Locale) async -> VoiceModelFiles? {guardlet locale = await resolve(requested) else { returnnil }return ready[locale.identifier] }func pass() async { passed = trueguardlet read, let corpus = await read() else { return }let requested = DictationHints(language: corpus.language).localeguardlet locale = await resolve(requested) else { return } observe(corpus, locale: locale) }/// Bring `locale`'s model to `corpus`: nothing when it already is; a model/// already written for exactly this corpus is loaded; otherwise the last/// written one serves while the new one waits out the day and compiles./// Before any of it, the first pass after a layout change clears every/// model an earlier version wrote.func observe(_ corpus: VoiceCorpus, locale: Locale) {let key = locale.identifierlet fingerprint = corpus.fingerprint(locale: key)guard ready[key]?.fingerprint != fingerprint, pending[key] != fingerprint else { return } pending[key] = fingerprint work[key]?.cancel()let folder = folder(key)let files = VoiceModelFiles(locale: key, fingerprint: fingerprint, folder: folder.appendingPathComponent(fingerprint)) work[key] = Task(priority: Self.buildPriority) { [weakself, compiler, timing, root, now] inawaitSelf.clearEarlierLayout(root)if files.isWritten {awaitself?.loaded(files, locale: locale, compiler: compiler)return }ifself?.ready[key] == nil, let earlier = awaitSelf.written(folder).first(where: { $0.fingerprint != fingerprint }) {awaitself?.loaded(earlier, locale: locale, compiler: compiler, keep: true) }iflet built = Self.built(folder) {// A stamp from a clock set back never holds a build past one interval.let wait = min(timing.interval, timing.interval - .seconds(now().timeIntervalSince(built)))if wait > .zero {Log.write("voice model: \(key) changed; compiles once the day is out")try? awaitTask.sleep(for: wait) } }ifletself, !self.onPower() { try? awaitTask.sleep(for: timing.batteryGrace) }guard !Task.isCancelled else { return }do {tryawait compiler.compile(corpus, locale: locale, into: files) } catch {Log.write("voice model: compile failed for \(key): \(error)")self?.pending[key] = nilreturn }Self.stamp(folder, now())guard !Task.isCancelled else { return }awaitself?.loaded(files, locale: locale, compiler: compiler) } }privatefunc loaded(_ files: VoiceModelFiles, locale: Locale, compiler: any VoiceModelCompiling, keep: Bool = false) async {do {tryawait compiler.load(files, locale: locale) } catch {Log.write("voice model: load failed for \(files.locale): \(error)")if !keep { pending[files.locale] = nil }return }guard keep || pending[files.locale] == files.fingerprint else { return } ready[files.locale] = filesguard !keep else { return } pending[files.locale] = nilLog.write("voice model: \(files.locale) \(files.fingerprint.prefix(12)) ready")awaitSelf.keepOnly(files) }privatefunc folder(_ locale: String) -> URL { root.appendingPathComponent(locale, isDirectory: true) }// MARK: - On disk nonisolated staticlet builtName = "built" nonisolated staticlet layoutName = "layout"/// One model per locale stays on disk: the one in use. Everything else in/// the locale's folder — older models, half-written ones — goes. nonisolated staticfunc keepOnly(_ files: VoiceModelFiles) async {let folder = files.folder.deletingLastPathComponent()let entries = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []for entry in entries where entry.lastPathComponent != files.fingerprint && entry.lastPathComponent != builtName {try? FileManager.default.removeItem(at: entry) } }/// The first pass after the folder's layout changed deletes every model/// and every stamp an earlier version wrote, in every locale, before/// anything is loaded or compiled — the version-1 models were 237 MB each/// and never cleaned. nonisolated staticfunc clearEarlierLayout(_ root: URL) async {let layout = root.appendingPathComponent(layoutName)let current = "\(VoiceModelCompiler.version)"if (try? String(contentsOf: layout, encoding: .utf8)) == current { return }let entries = (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []for entry in entries where entry.lastPathComponent != layoutName {try? FileManager.default.removeItem(at: entry) }try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)try? Data(current.utf8).write(to: layout, options: .atomic)Log.write("voice model: cleared \(entries.count) entries an earlier layout wrote") }/// When the locale's last model was compiled. nonisolated staticfunc built(_ folder: URL) -> Date? {guardlet text = try? String(contentsOf: folder.appendingPathComponent(builtName), encoding: .utf8),let seconds = TimeInterval(text) else { returnnil }returnDate(timeIntervalSince1970: seconds) } nonisolated staticfunc stamp(_ folder: URL, _ date: Date) {try? Data("\(date.timeIntervalSince1970)".utf8).write(to: folder.appendingPathComponent(builtName), options: .atomic) }/// Every model written in a locale's folder, newest first. nonisolated staticfunc written(_ folder: URL) async -> [VoiceModelFiles] {let locale = folder.lastPathComponentlet folders = (try? FileManager.default.contentsOfDirectory( at: folder, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []return folders .map { VoiceModelFiles(locale: locale, fingerprint: $0.lastPathComponent, folder: $0) } .filter(\.isWritten) .sorted {let a = (try? $0.folder.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPastlet b = (try? $1.folder.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPastreturn a > b } }// MARK: - Where, and when/// The locale dictation listens in for `requested` — the recogniser's own/// resolution, so the model is compiled for exactly the locale it is/// handed in.public nonisolated staticfunc transcriberLocale(_ requested: Locale) async -> Locale? {awaitSpeechModel.locale(DictationTranscriber.self, for: requested) }/// `Application Support/<this app's bundle id>/VoiceModel` — this app's own/// folder (a development build's is its own), never a database folder,/// and excluded from backup: the model is rebuilt from the records, which/// are what is backed up.public nonisolated staticfunc defaultRoot() -> URL {let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]var root = support .appendingPathComponent(Bundle.main.bundleIdentifier ?? "cotton", isDirectory: true) .appendingPathComponent("VoiceModel", isDirectory: true) excludeFromBackup(&root)return root } nonisolated staticfunc excludeFromBackup(_ root: inout URL) {try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)var values = URLResourceValues() values.isExcludedFromBackup = truetry? root.setResourceValues(values) }/// Plugged in (or charging). Unknown counts as on power: a desktop Mac/// has no battery to spare.publicstaticfunc isOnPower() -> Bool { #if os(iOS) UIDevice.current.isBatteryMonitoringEnabled = trueswitch UIDevice.current.batteryState {case .charging, .full: returntruecase .unplugged: returnfalsecase .unknown: returntrue @unknown default: returntrue } #elseif os(macOS)guardlet info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),let type = IOPSGetProvidingPowerSourceType(info)?.takeUnretainedValue() asString?else { returntrue }return type != kIOPSBatteryPowerValue #elsereturntrue #endif }}