// 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`.importCottonKitimportFoundation/// Namespace for every fallback notification this feature owns.publiclet alarmKeyPrefix = "cotton:alarm:"/// Does this scheduled-notification identifier belong to the alarms feature?publicfunc isAlarmKey(_ identifier: String) -> Bool { identifier.hasPrefix(alarmKeyPrefix)}/// What the device will actually do when an alarm fires.publicenumAlarmBackend: 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.publicstructPlannedAlarm: Equatable, Identifiable, Sendable {/// The `cotton_alarms` row id — also the AlarmKit alarm id.publiclet id: String/// The person's own label, empty when unnamed.publiclet label: Stringpubliclet hour: Intpubliclet minute: Int/// ISO weekdays 1–7, ascending and deduped. Empty = one-shot.publiclet repeatDays: [Int]publiclet sound: Bool/// Changes whenever anything the scheduler cares about changes.publiclet 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.publicfunc 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 inPlannedAlarm( 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.publicstructAlarmLedgerEntry: Codable, Equatable, Sendable {publicvar 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.publicvar firesAt: Int?publicinit(signature: String, firesAt: Int? = nil) {self.signature = signatureself.firesAt = firesAt }}/// alarm id → what the last successful pass recorded.publictypealiasAlarmLedger = [String: AlarmLedgerEntry]publicstructReconcileInput {/// Every alarm in the workspace, enabled and not.var alarms: [Alarm]publicvar 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.publicvar actualAlarmKitIds: [String]?/// Every pending local-notification identifier, ours and the rest of the/// app's. `nil` = unknown, same rule.publicvar actualNotificationKeys: [String]?publicvar 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.publicvar 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.publicvar now: Date/// The zone the wall clock is read in. An alarm is a wall clock, not an/// instant.publicvar calendar: Calendarinit( alarms: [Alarm], backend: AlarmBackend, actualAlarmKitIds: [String]?, actualNotificationKeys: [String]?, ledger: AlarmLedger, canSchedule: Bool, now: Date, calendar: Calendar = .current ) {self.alarms = alarmsself.backend = backendself.actualAlarmKitIds = actualAlarmKitIdsself.actualNotificationKeys = actualNotificationKeysself.ledger = ledgerself.canSchedule = canScheduleself.now = nowself.calendar = calendar }}publicstructReconcilePlan: Equatable, Sendable {/// Schedule these into AlarmKit (empty unless the backend is `alarmkit`).publicvar scheduleAlarmKit: [PlannedAlarm] = []/// Schedule these as fallback notifications.publicvar scheduleNotifications: [PlannedAlarm] = []/// AlarmKit ids to cancel — ours only; AlarmKit is app-scoped.publicvar cancelAlarmKit: [String] = []/// Notification identifiers to cancel — `cotton:alarm:` keys ONLY.publicvar 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.publicvar firedOnce: [String] = []/// The ledger to persist once the plan has been executed.publicvar 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.publicfunc reconcileAlarms(_ input: ReconcileInput) -> ReconcilePlan {let planned = planAlarms(input.alarms, backend: input.backend)let usingAlarmKit = input.backend == .alarmkitlet 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.signaturelet 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 != nillet live = usingAlarmKit ? liveAlarmKit.contains(entry.id) : fallbackKeys(entry).allSatisfy(liveNotifications.contains)let absent = known && !liveif 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.publicfunc 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.publicfunc 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.guardlet 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.structNextAlarm: Equatable, Sendable {let alarm: Alarmpubliclet 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.privatelet 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.publicfunc 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 { returnnil }let days = Set(alarm.repeatDays)for offset in0..<alarmScanDays {// Set the DAY before the TIME. The other order can walk off the end of// a short month.guardlet day = calendar.date(byAdding: .day, value: offset, to: now) else { continue }var parts = calendar.dateComponents([.year, .month, .day], from: day) parts.hour = alarm.hour parts.minute = alarm.minute parts.second = 0 parts.nanosecond = 0guardlet at = calendar.date(from: parts) else { continue }if at <= now { continue }// A one-shot takes the first day that works; a repeating alarm takes// the first day that works AND is one of its own.if days.isEmpty || days.contains(isoWeekday(of: at, calendar: calendar)) { return at } }// Unreachable for a well-formed alarm: an eight-day scan always finds a// weekday. Answering `nil` rather than trapping keeps a corrupted// `repeat_days` — a day outside 1–7 that somehow got past the tool's guard// — from taking the whole screen down: the header simply says nothing, and// the list still renders.returnnil}/// The soonest alarm across the whole list, or `nil` when none is switched on.////// Ties break on the alarm's own id rather than on list order, so two alarms/// set to the same minute name the same winner on every redraw and the header/// does not flicker between them.func nextAlarm(in alarms: [Alarm], now: Date, calendar: Calendar = .current) -> NextAlarm? {var best: NextAlarm?for alarm in alarms {guardlet at = nextOccurrence(of: alarm, now: now, calendar: calendar) else { continue }guardlet 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}