Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/KeyboardCore/Metrics.swift10// Description : Numbers the keyboard measures about itself (appearance11// time, key latency, memory) and reports to the app's12// Diagnostics screen. Durations and counts only: never any13// typed text.14// Module : KeyboardCore15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import SecureStorage9394public struct KeyboardMetrics: VersionedSettings, Hashable {95 public static let currentSchemaVersion = 196 public static let storageKey = "keyboard.metrics"97 public static var fallback: KeyboardMetrics { KeyboardMetrics() }9899 public var schemaVersion = KeyboardMetrics.currentSchemaVersion100 /// First appearance of a freshly launched extension process, in milliseconds.101 public var coldAppearanceMs: Double?102 /// Later appearances of the same process.103 public var warmAppearanceMs: Double?104 public var keyLatencyP50Ms: Double?105 public var keyLatencyP95Ms: Double?106 public var keySamples = 0107 public var memoryFootprintMB: Double?108 public var hadFullAccess: Bool?109 public var sharedContainerReachable: Bool?110 public var keychainStatus: String?111 public var settingsOutcome: String?112 public var updatedAt: Date?113114 public init() {}115116 public func migrated() -> KeyboardMetrics { self }117}118119/// Rolling window of key-handling durations.120public struct LatencyWindow: Sendable {121 public private(set) var samples: [Double] = []122 public let capacity: Int123124 public init(capacity: Int = 300) { self.capacity = capacity }125126 public mutating func record(milliseconds: Double) {127 guard milliseconds.isFinite, milliseconds >= 0 else { return }128 samples.append(milliseconds)129 if samples.count > capacity { samples.removeFirst(samples.count - capacity) }130 }131132 public mutating func reset() { samples.removeAll() }133134 public func percentile(_ p: Double) -> Double? {135 guard !samples.isEmpty else { return nil }136 let sorted = samples.sorted()137 let rank = Int((Double(sorted.count - 1) * min(max(p, 0), 1)).rounded())138 return sorted[rank]139 }140141 public var count: Int { samples.count }142}143144public enum ProcessMemory {145 /// Physical footprint of the current process in megabytes (what iOS counts against an extension).146 public static func footprintMB() -> Double? {147 var info = task_vm_info_data_t()148 var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)149 let result = withUnsafeMutablePointer(to: &info) { pointer in150 pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {151 task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)152 }153 }154 guard result == KERN_SUCCESS else { return nil }155 return Double(info.phys_footprint) / 1_048_576156 }157}158