// The alarm reconciler's BRAIN — pure, so the interesting rules are provable // without a device. // // The device is the scheduler: `cotton_alarms` is a durable list, and whatever // OS-level alarms exist must be made to match it. That is a desired-set diff, // with five wrinkles worth writing down: // // 1. **Two backends, one truth.** An alarm is either a real AlarmKit alarm or a // fallback notification, never both — so a pass that runs on one backend // must also sweep the OTHER's leftovers. Granting permission mid-life flips // the backend, and without that sweep the person gets a ring AND a buzz. // 2. **A signature, not just an id.** Neither backend says what a scheduled // alarm SAYS, so "7:30 Wake up" edited to "7:45 Wake up" looks identical by // id. The ledger remembers a signature per alarm; a changed signature is a // re-schedule (both backends overwrite by identifier, so that is safe). // 3. **Only our own keys are ever cancelled.** The tray also carries todos, // events and birthdays. Everything here is namespaced `cotton:alarm:` and // the sweep filters on that prefix — a reconciler that cancelled by // "everything not in my desired set" would delete every reminder in the app. // 4. **A pass that is not ALLOWED to schedule desires nothing** (`canSchedule`). // This is the alarm-that-did-not-ring: for its first year the // reconciler never asked whether it was permitted to schedule. It handed a // request to the notification centre with the permission still undetermined, // iOS filed it in a queue it would never present, the pass recorded the // signature as DONE — and because the signature then matched for ever, no // later pass repaired it, not even after the person granted permission. // 5. **A ONE-SHOT that is gone has usually FIRED, not been wiped**, and the // ledger's `firesAt` is what tells those apart. See `reconcileAlarms`. import CottonKit import Foundation /// Namespace for every fallback notification this feature owns. public let alarmKeyPrefix = "cotton:alarm:" /// Does this scheduled-notification identifier belong to the alarms feature? public func isAlarmKey(_ identifier: String) -> Bool { identifier.hasPrefix(alarmKeyPrefix) } /// What the device will actually do when an alarm fires. public enum AlarmBackend: String, Equatable, Sendable { /// A real alarm: rings through silent and Focus. case alarmkit /// The fallback: a time-sensitive notification, silenced by the silent /// switch. Honest copy is mandatory wherever this is live. case notification } /// One enabled alarm, resolved to what the scheduler needs. public struct PlannedAlarm: Equatable, Identifiable, Sendable { /// The `cotton_alarms` row id — also the AlarmKit alarm id. public let id: String /// The person's own label, empty when unnamed. public let label: String public let hour: Int public let minute: Int /// ISO weekdays 1–7, ascending and deduped. Empty = one-shot. public let repeatDays: [Int] public let sound: Bool /// Changes whenever anything the scheduler cares about changes. public let signature: String } /// The fallback needs ONE notification per repeating weekday (an iOS calendar /// trigger repeats on a single weekday each), so a Mon/Wed alarm is two /// requests. A one-shot is a single bare key. public func fallbackKeys(_ planned: PlannedAlarm) -> [String] { if planned.repeatDays.isEmpty { return ["\(alarmKeyPrefix)\(planned.id)"] } return planned.repeatDays.map { "\(alarmKeyPrefix)\(planned.id):\($0)" } } /// What the scheduler must be told. /// /// The BACKEND is part of it on purpose: when permission is granted and the /// backend flips, every alarm's signature changes and the whole set is /// re-scheduled onto the louder path. `sound` is in here for the same reason — /// it changes what the device DOES, and neither backend will say what an /// already-scheduled alarm sounds like. Left out, silencing an alarm would be a /// row edit the phone never heard about until the person also moved the time. func alarmSignature(_ alarm: Alarm, backend: AlarmBackend) -> String { let days = normalizeDays(alarm.repeatDays).map(String.init).joined(separator: ",") return [ backend.rawValue, String(alarm.hour), String(alarm.minute), days, alarm.sound ? "sound" : "silent", alarm.label, ].joined(separator: "|") } /// Enabled alarms only, in a stable shape. A disabled row is simply not desired. func planAlarms(_ alarms: [Alarm], backend: AlarmBackend) -> [PlannedAlarm] { alarms.filter(\.enabled).map { alarm in PlannedAlarm( id: alarm.id, label: alarm.label, hour: alarm.hour, minute: alarm.minute, repeatDays: normalizeDays(alarm.repeatDays), sound: alarm.sound, signature: alarmSignature(alarm, backend: backend) ) } } /// What a pass recorded about ONE alarm. /// /// The previous app's ledger also had to read a BARE STRING — the original /// form, still sitting in the storage of every installed copy. There is no such /// entry here and there never can be: this app has its own store and does not /// read that one, so a ledger written by that app is unreachable rather than /// legacy. The `firesAt`-less reading it produced is therefore gone with it, /// and every entry this app writes can answer the one-shot question. public struct AlarmLedgerEntry: Codable, Equatable, Sendable { public var signature: String /// For a ONE-SHOT: the instant it was scheduled to go off, epoch /// milliseconds. Absent on a repeating alarm — a weekly trigger has no last /// occurrence. public var firesAt: Int? public init(signature: String, firesAt: Int? = nil) { self.signature = signature self.firesAt = firesAt } } /// alarm id → what the last successful pass recorded. public typealias AlarmLedger = [String: AlarmLedgerEntry] public struct ReconcileInput { /// Every alarm in the workspace, enabled and not. var alarms: [Alarm] public var backend: AlarmBackend /// The ids AlarmKit currently holds, or `nil` for UNKNOWN (no framework, or /// the read threw). Unknown is not empty: with `nil` we neither schedule /// onto it nor claim its leftovers are gone. public var actualAlarmKitIds: [String]? /// Every pending local-notification identifier, ours and the rest of the /// app's. `nil` = unknown, same rule. public var actualNotificationKeys: [String]? public var ledger: AlarmLedger /// May this pass hand anything to the device AT ALL? /// /// Required, and deliberately not defaulted: the bug this flag names is /// that for a year nobody asked the question, and a parameter with a `true` /// default is a question nobody has to ask either. /// /// `false` is every reason the device will not ring. The desired set is /// then EMPTY on both backends: nothing is scheduled, the ledger records /// nothing, and everything of ours already on the device is swept. One /// statement doing two jobs, and both are wanted — switching alarms off has /// to actually stop them, and recording nothing is what makes the whole set /// re-plan the moment the gate opens again. public var canSchedule: Bool /// Now, passed rather than read: a one-shot's "has it fired yet" is a /// comparison against the clock, and a reconciler that read the clock /// itself could not be tested at 7:29 and 7:31. public var now: Date /// The zone the wall clock is read in. An alarm is a wall clock, not an /// instant. public var calendar: Calendar init( alarms: [Alarm], backend: AlarmBackend, actualAlarmKitIds: [String]?, actualNotificationKeys: [String]?, ledger: AlarmLedger, canSchedule: Bool, now: Date, calendar: Calendar = .current ) { self.alarms = alarms self.backend = backend self.actualAlarmKitIds = actualAlarmKitIds self.actualNotificationKeys = actualNotificationKeys self.ledger = ledger self.canSchedule = canSchedule self.now = now self.calendar = calendar } } public struct ReconcilePlan: Equatable, Sendable { /// Schedule these into AlarmKit (empty unless the backend is `alarmkit`). public var scheduleAlarmKit: [PlannedAlarm] = [] /// Schedule these as fallback notifications. public var scheduleNotifications: [PlannedAlarm] = [] /// AlarmKit ids to cancel — ours only; AlarmKit is app-scoped. public var cancelAlarmKit: [String] = [] /// Notification identifiers to cancel — `cotton:alarm:` keys ONLY. public var cancelNotifications: [String] = [] /// One-shot alarms whose single scheduled request is GONE and whose fire /// time has passed — they rang, and the caller must switch the row OFF. /// /// The other half of not re-arming them: an alarm that has done its job but /// still shows a lit switch is a promise the device is no longer keeping. /// Reported rather than written here, because this is pure and the write is /// a row the person owns. public var firedOnce: [String] = [] /// The ledger to persist once the plan has been executed. public var nextLedger: AlarmLedger = [:] } /// Diff the desired set against what the device actually holds. /// /// A planned alarm is re-scheduled when its signature moved OR when any key it /// needs is missing from the actual set — the second clause is what heals a /// device whose alarms were wiped (a restore, a permission reset) while the /// ledger still claimed they were live. /// /// **The one-shot exception to healing.** A repeating alarm's trigger never /// leaves the queue on its own, so "absent" really does mean "wiped". A /// ONE-SHOT's does: firing is precisely how a dated request disappears. Read as /// "missing", every one-shot the person ever set gets re-armed on the next /// foreground — for the next day, and the day after that, for ever — which /// turns "wake me once" into a daily alarm nobody asked for. So the two are /// told apart by the ledger's `firesAt`: a fire time that has PASSED means it /// rang (reported in `firedOnce`, so the row gets switched off), a fire time /// still AHEAD means the device really was wiped and it is re-scheduled. public func reconcileAlarms(_ input: ReconcileInput) -> ReconcilePlan { let planned = planAlarms(input.alarms, backend: input.backend) let usingAlarmKit = input.backend == .alarmkit let liveAlarmKit = Set(input.actualAlarmKitIds ?? []) let liveNotifications = Set(input.actualNotificationKeys ?? []) // What SHOULD exist on each backend. Only the active one gets anything; the // other's entries are leftovers to sweep. A pass that may not schedule // wants NOTHING anywhere — which is what takes every alarm of ours off the // device when the gate closes. let wantedAlarmKit = Set( input.canSchedule && usingAlarmKit ? planned.map(\.id) : [] ) let wantedNotifications = Set( input.canSchedule && !usingAlarmKit ? planned.flatMap(fallbackKeys) : [] ) var plan = ReconcilePlan() for entry in planned { // The gate. Nothing is planned and — the load-bearing half — NOTHING is // recorded, so every alarm re-plans the moment it opens again. if !input.canSchedule { continue } let previous = input.ledger[entry.id] let signatureMoved = previous?.signature != entry.signature let oneShot = entry.repeatDays.isEmpty // `nil` is UNKNOWN, not empty: with a set we could not read, nothing is // provably absent, so only a signature change acts. Re-scheduling // blindly every pass would rewrite the person's alarms on every // foreground. let known = usingAlarmKit ? input.actualAlarmKitIds != nil : input.actualNotificationKeys != nil let live = usingAlarmKit ? liveAlarmKit.contains(entry.id) : fallbackKeys(entry).allSatisfy(liveNotifications.contains) let absent = known && !live if absent, !signatureMoved, oneShot, let firesAt = previous?.firesAt, firesAt <= epochMilliseconds(input.now) { // It rang. Keep the entry — so a failed switch-off is retried next // pass rather than re-arming the alarm — and tell the caller. plan.firedOnce.append(entry.id) plan.nextLedger[entry.id] = AlarmLedgerEntry(signature: entry.signature, firesAt: firesAt) continue } if signatureMoved || absent { if usingAlarmKit { plan.scheduleAlarmKit.append(entry) } else { plan.scheduleNotifications.append(entry) } plan.nextLedger[entry.id] = oneShot ? AlarmLedgerEntry( signature: entry.signature, // The same instant the scheduler will compute from the same // `now` — `nextOneShotAt` is the ONE rule for when a // one-shot goes off, and both callers read it rather than // each doing the arithmetic. firesAt: epochMilliseconds( nextOneShotAt( hour: entry.hour, minute: entry.minute, now: input.now, calendar: input.calendar ) ) ) : AlarmLedgerEntry(signature: entry.signature) continue } // Unchanged and present: carry the entry forward AS IT WAS. Recomputing // `firesAt` here would push a one-shot's fire time forward on every // single pass, so it would never be in the past and the rule above // would never fire — the bug that rule exists to fix, reintroduced by a // stale-looking line of housekeeping. plan.nextLedger[entry.id] = AlarmLedgerEntry( signature: entry.signature, firesAt: previous?.firesAt ) } // Sweep: anything of OURS the device holds that the desired set no longer // wants — a deleted alarm, a disabled one, the other backend's leftovers, // or every one of them because the gate is shut. plan.cancelAlarmKit = (input.actualAlarmKitIds ?? []).filter { !wantedAlarmKit.contains($0) } plan.cancelNotifications = (input.actualNotificationKeys ?? []) .filter(isAlarmKey) .filter { !wantedNotifications.contains($0) } return plan } /// Ascending, deduped — so a reordered `repeat_days` is not a "change". func normalizeDays(_ days: [Int]) -> [Int] { Array(Set(days)).sorted() } /// ISO weekday (1 = Monday … 7 = Sunday) → Apple's (1 = Sunday … 7 = Saturday), /// which is what a `DateComponents` weekday takes. /// /// The two conventions differ by exactly one rotation, and getting it wrong /// fires Monday's alarm on Sunday — a silent, once-a-week bug. It lives here, /// named and tested, rather than inline at the call site. public func isoToAppleWeekday(_ iso: Int) -> Int { (iso % 7) + 1 } /// When a one-shot alarm should fire: the next wall-clock occurrence of /// `hour:minute`, today if it is still ahead, otherwise tomorrow. Local time /// throughout — an alarm is a wall clock, not an instant. public func nextOneShotAt( hour: Int, minute: Int, now: Date, calendar: Calendar = .current ) -> Date { var parts = calendar.dateComponents([.year, .month, .day], from: now) parts.hour = hour parts.minute = minute parts.second = 0 parts.nanosecond = 0 // WHAT FOUNDATION REALLY DOES with a wall-clock time daylight saving // skipped, because the comment that used to stand here said the opposite // and its fallback was dead code: `Calendar.date(from:)` RESOLVES a skipped // time forward to the first instant that exists (02:30 on a spring-forward // Sunday answers 03:00), it does not return nil. So an alarm set inside the // lost hour rings at the moment the clock reaches it, which is the right // answer and the one the tests pin. // // The optional is Foundation's signature, not a state this arithmetic can // reach — `parts` is a whole y/m/d/h/m taken from a real date — so the // branch stays only because the type demands a total function, and it // answers with the same reading one day on rather than inventing one. guard let today = calendar.date(from: parts) else { return calendar.date(byAdding: .day, value: 1, to: now) ?? now } if today > now { return today } return calendar.date(byAdding: .day, value: 1, to: today) ?? today } func epochMilliseconds(_ date: Date) -> Int { Int((date.timeIntervalSince1970 * 1000).rounded()) } // ── When the next alarm goes off ──────────────────────────────────────────── // // The one number // the Alarms screen leads with, pure so it is provable without a device or a // clock. // // **An alarm is a WALL CLOCK, not an instant.** 7:30 means 7:30 wherever the // phone is standing: fly somewhere else and the alarm follows the wall, not the // instant it was set at. That is why `cotton_alarms` stores an hour and a // minute rather than a timestamp, and it is the rule every line here obeys — // every date is built through the CALENDAR, and there is deliberately not one // UTC offset in the file. Reaching for UTC arithmetic is how a repeat alarm // comes to fire an hour early for half the year, and how a person east of // Greenwich gets Monday's alarm on Sunday. // // The two clock discontinuities are both handled by the same choice — build the // components and let the platform resolve them. On a spring-forward day 2:30 // does not exist and the alarm lands where every clock in the house lands; on a // fall-back day 1:30 happens twice and the first one wins. The end of a month // or a year rolls over for free, which a hand-written day + 1 does not. /// One alarm and the instant it will next go off. struct NextAlarm: Equatable, Sendable { let alarm: Alarm public let at: Date } /// Enough days to find any weekday again, including today's a week from now. /// Eight rather than seven is not slack: a repeating alarm due TODAY whose time /// has already passed has to be found again NEXT week on the same weekday, /// which is day 7 counting from zero. private let alarmScanDays = 8 /// ISO weekday (1 = Monday … 7 = Sunday) for a local date. /// /// A `Calendar`'s own weekday is Sunday-first (1–7) and the store speaks ISO. /// The two differ by one rotation, and getting it wrong fires Monday's alarm on /// Sunday — a silent, once-a-week bug, which is why it is a named function with /// its own test rather than an inline adjustment. public func isoWeekday(of date: Date, calendar: Calendar = .current) -> Int { let day = calendar.component(.weekday, from: date) return day == 1 ? 7 : day - 1 } /// When this alarm next goes off, or `nil` if it never will. /// /// `nil` means the alarm is switched OFF — the only way an alarm has no next /// occurrence, since a one-shot always has a next wall time and a repeating one /// always comes round again. /// /// Strictly AFTER `now`: an alarm whose minute is the current minute has /// already had its moment, and answering "in 0 m" for it would be a countdown /// to something that is not going to happen. func nextOccurrence( of alarm: Alarm, now: Date, calendar: Calendar = .current ) -> Date? { guard alarm.enabled else { return nil } let days = Set(alarm.repeatDays) for offset in 0.. NextAlarm? { var best: NextAlarm? for alarm in alarms { guard let at = nextOccurrence(of: alarm, now: now, calendar: calendar) else { continue } guard let current = best else { best = NextAlarm(alarm: alarm, at: at) continue } if at < current.at || (at == current.at && alarm.id < current.alarm.id) { best = NextAlarm(alarm: alarm, at: at) } } return best }