Cook the frog: lower the wake baseline a minute a day from 08:00 to 07:00

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-09-25 13:15:44 +02:00
parent 8be972c31a
commit d8b07b2be4
25 changed files with 608 additions and 170 deletions

View File

@ -4,13 +4,13 @@
**The phone is the alarm.** `phone_app/` arms and rings it and gates the
dismissal; this repo's Python half only reads the alarm time the phone
published and starts the morning routine at that time.
published and starts the morning routine at that time. The time is a ramp:
08:00 down a minute a day to 07:00, in three copies — **`DOCS-ramp.md`**.
The PC's waking role was deleted on 2026-08-30: no alarm window, no audio
escalation, no smart plug, no curtains, no `rtcwake`, no `shutdown` wrapper,
no sleep hook. Making the PC wake someone reliably cost more than it returned.
Everything about it is in git history; do not reintroduce a piece of it
without saying why the phone cannot do that job.
no sleep hook: waking someone reliably cost more than it returned. It is in
git history; do not reintroduce any of it without saying why the phone can't.
## The dismiss sequence (phone)
@ -101,7 +101,7 @@ systemd-sleep hook: a suspended or just-booted machine still fires.
- **The Firebase reader discovers device directories; it is not pinned to
`devices/phone/`.** The phone's device id is migrating from the fixed
constant `phone` to a per-install uuid, and a pinned reader would silently
stop seeing the alarm and fall back to `FALLBACK_ALARM_HOUR` — i.e. the wrong
stop seeing the alarm and fall back to the ramp baseline — i.e. the wrong
time. `_fetch_firebase_alarm()` lists `SYNC_DEVICES_PREFIX`, reads every
device's `alarm.json`, and picks the newest by the hour field's **HLC**, with
`device_id` breaking exact ties. A payload that does not parse is skipped
@ -127,7 +127,7 @@ systemd-sleep hook: a suspended or just-booted machine still fires.
for that reason. Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the
dev venv.
- Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale
cache → `FALLBACK_ALARM_HOUR`. The cache bounds remote reads to ~288/day
cache → today's ramp baseline. The cache bounds remote reads to ~288/day
despite the per-minute tick.
- **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped
at every step, including the cache.** The check is on when the *phone
@ -136,7 +136,7 @@ systemd-sleep hook: a suspended or just-booted machine still fires.
minutes, so `fetched_at` is always fresh however old the record behind it is.
That is why the winning HLC's instant is carried through `_alarm_payload` →
`_sync_transport` → the cache's `published_at`. Expiring is safe because
`FALLBACK_ALARM_HOUR` *is* the phone's baseline. An **undated** record is
the ramp baseline *is* the phone's baseline. An **undated** record is
trusted, not expired: the GitHub mirror has no per-field HLC, so treating
"cannot tell" as "too old" would break that backend entirely.
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute;

View File

@ -26,7 +26,7 @@ got up at 07:00, the opposite of the point):
| the phone says | `exempt_until` | meaning |
|---|---|---|
| nothing started today (`none`) | **alarm + 15 min** (`SESSION_NONE_GRACE`; alarm = the phone's, clamped to ≤ 08:00 like the trigger) | up early is fine; the phone rings at the alarm, and a dismiss that has not produced a session by then means "not up" |
| nothing started today (`none`) | **alarm + 15 min** (`SESSION_NONE_GRACE`; alarm = the phone's, clamped to ≤ today's ramp baseline like the trigger) | up early is fine; the phone rings at the alarm, and a dismiss that has not produced a session by then means "not up" |
| started, not finished (`in_progress`) | `min(started_at + 90 min, 09:30)` | provisional — the legs take ~40 min; relative to the start because an alarm earlier than 08:00 is legal and a fixed 09:30 would hand an aborted 06:15 session three hours |
| `completed`, finished inside that same cutoff | **11:00** | the carrot |
| `completed` *after* the cutoff | none | a phone switched back on at noon completes the legs then; that un-locks nothing |

20
DOCS-ramp.md Normal file
View File

@ -0,0 +1,20 @@
# The wake-time ramp ("cooking the frog")
The baseline is not a constant: 08:00 through 2026-09-25, then one minute
earlier per **calendar** day (free days count) to 07:00 on 2026-11-24, which
is permanent. A pure function of the date the alarm **fires** on — no counter,
no stored start — so a reinstall cannot reset it. Three copies must agree:
`wake_alarm/_ramp.py` (PC fallback + clamp), `phone_app/lib/services/alarm_ramp.dart`
(`AlarmPolicy`) and `AlarmRamp.kt` (every native arm path funnels through
`AlarmScheduler.nextOccurrence`, so the dismiss/boot/free-day/watchdog re-arms
keep stepping without Dart). `tests/test_ramp.py` parses the other two.
- **Evaluate the fire day, never the arm day.** The phone arms the evening
before; "today's" ramp there is tomorrow's time plus a minute, every day.
- The PC clamps any synced time to *today's* ramp. A record up to 08:00 is
expected lag (the phone publishes when the app runs) and logs INFO; only a
time later than 08:00 is a WARNING.
- The one-shot earlier override lapses once the ramp catches up with it, and
the ring screen re-arms the policy after `resetAfterFire` — `dismiss()`
natively re-arms the *stored* time, i.e. the override just spent.

View File

@ -0,0 +1,50 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDate
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
/**
* The baseline wake time, lowered one minute per calendar day to 07:00.
*
* Native copy of `lib/services/alarm_ramp.dart`: the daily re-arm after a
* dismiss, a free day, a boot or the watchdog runs here with no Dart at all,
* so without this copy it would re-arm the stored time and the ramp would
* stall until the app was next opened. `wake_alarm/tests/test_ramp.py` parses
* these constants and fails when they drift from the Dart and Python copies.
*/
object AlarmRamp {
/** The last day at the old 08:00 baseline; each day after is a minute earlier. */
val ANCHOR: LocalDate = LocalDate.of(2026, 9, 25)
/** Minutes of day on the anchor date (08:00). */
const val START_MINUTES = 8 * 60
/** The floor the ramp stops at, for good (07:00). */
const val FLOOR_MINUTES = 7 * 60
/** Baseline on [day], in minutes of day. Calendar days, so DST cannot skew it. */
fun minutesOn(day: LocalDate): Int {
val elapsed = maxOf(0L, ChronoUnit.DAYS.between(ANCHOR, day))
return maxOf(FLOOR_MINUTES.toLong(), START_MINUTES - elapsed).toInt()
}
/**
* Next fire instant after [now] for a requested time of [requested] minutes.
*
* The ramp is evaluated for the day the alarm fires on, and wins whenever
* it is earlier than the request; tomorrow always qualifies because the
* ramp never moves later.
*/
fun nextFire(requested: Int, now: ZonedDateTime): ZonedDateTime {
val today = now.toLocalDate()
val first = at(today, requested, now)
return if (first.isAfter(now)) first else at(today.plusDays(1), requested, now)
}
private fun at(day: LocalDate, requested: Int, now: ZonedDateTime): ZonedDateTime {
val minutes = minOf(requested, minutesOn(day))
return day.atTime(minutes / 60, minutes % 60).atZone(now.zone)
}
}

View File

@ -6,7 +6,7 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.Calendar
import java.time.ZonedDateTime
/**
* Arms and cancels the one exact alarm this app owns.
@ -162,18 +162,15 @@ object AlarmScheduler {
.putInt(KEY_HOUR, hour).putInt(KEY_MINUTE, minute).apply()
}
/** Next local-time instant matching [hour]:[minute]; tomorrow if today has passed. */
private fun nextOccurrence(hour: Int, minute: Int): Long {
val now = Calendar.getInstance()
val at = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
if (!at.after(now)) at.add(Calendar.DAY_OF_YEAR, 1)
return at.timeInMillis
}
/**
* Next local-time instant for [hour]:[minute], never later than that day's ramp.
*
* Every arm path funnels through here, so the stored time is only an upper
* bound: the dismiss/boot/free-day re-arms still move a minute earlier a day.
*/
private fun nextOccurrence(hour: Int, minute: Int): Long =
AlarmRamp.nextFire(hour * 60 + minute, ZonedDateTime.now())
.toInstant().toEpochMilli()
/** FLAG_IMMUTABLE is mandatory from API 31; without it this throws at arm time. */
private fun firePendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(

View File

@ -22,7 +22,8 @@ Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// The alarm is not opt-in: launching the app is enough to arm it. There is
// no "set alarm" button to forget, and no cancel to reach for at 02:00 —
// AlarmPolicy fixes the time at 08:00 and only ever lets it move earlier.
// AlarmPolicy fixes the time (the daily ramp, 08:00 down to 07:00) and
// only ever lets it move earlier.
final policy = await AlarmPolicy.load();
await AlarmScheduler().armSchedule(policy.hour, policy.minute);
runApp(const WakeAlarmSyncApp());

View File

@ -26,11 +26,10 @@ class HomeScreen extends StatefulWidget {
}
class _HomeScreenState extends State<HomeScreen> {
int _hour = AlarmPolicy.baselineHour;
int _minute = AlarmPolicy.baselineMinute;
/// True while a one-shot earlier start is in force for the next alarm.
bool _isOverridden = false;
/// The next alarm: the day's ramp baseline, or a one-shot earlier start.
AlarmPolicy _policy = AlarmPolicy.resolve(DateTime.now(), null);
int get _hour => _policy.hour;
int get _minute => _policy.minute;
bool _busy = false;
String _status = '';
bool _configured = false;
@ -148,7 +147,7 @@ class _HomeScreenState extends State<HomeScreen> {
}
await _applyPolicy();
if (!mounted) return;
setState(() => _status = 'Armed for ${_fmt(_hour, _minute)} tomorrow.');
setState(() => _status = 'Armed for ${_fmt(_hour, _minute)}.');
// The PC has to learn about the new time too. Without this the only
// publish attempt was the one at startup, so an alarm moved earlier here
// never reached the PC at all.
@ -160,11 +159,7 @@ class _HomeScreenState extends State<HomeScreen> {
final policy = await AlarmPolicy.load();
await _scheduler.armSchedule(policy.hour, policy.minute);
if (!mounted) return;
setState(() {
_hour = policy.hour;
_minute = policy.minute;
_isOverridden = policy.isOverridden;
});
setState(() => _policy = policy);
}
Future<void> _syncToPc() async {
@ -186,8 +181,7 @@ class _HomeScreenState extends State<HomeScreen> {
}
/// The baseline time, shown when a one-shot override is active.
String get _baseline =>
_fmt(AlarmPolicy.baselineHour, AlarmPolicy.baselineMinute);
String get _baseline => _fmt(_policy.baselineHour, _policy.baselineMinute);
String _fmt(int h, int m) =>
'${h.toString().padLeft(2, '0')}:${m.toString().padLeft(2, '0')}';
@ -236,7 +230,7 @@ class _HomeScreenState extends State<HomeScreen> {
body: HomeBody(
time: _fmt(_hour, _minute),
baseline: _baseline,
isOverridden: _isOverridden,
isOverridden: _policy.isOverridden,
busy: _busy,
status: _status,
configured: _configured,

View File

@ -214,9 +214,13 @@ class _RingScreenState extends State<RingScreen> {
await _scheduler.dismiss();
// A one-shot earlier start applies to this alarm only. Without the reset
// the first early morning would become permanent, with no way back to the
// 08:00 baseline short of reinstalling — a ratchet with no reset is a
// ramp baseline short of reinstalling — a ratchet with no reset is a
// trap, not a defence.
await AlarmPolicy.resetAfterFire();
// dismiss() re-armed the *stored* time, i.e. the override just spent;
// without re-arming the policy it rang again every day until home opened.
final next = await AlarmPolicy.load();
await _scheduler.armSchedule(next.hour, next.minute);
final handoff = widget.handoff ?? SessionHandoff(scheduler: _scheduler);
final session = await handoff.afterDismiss(away: _gate.awayActive);
if (session && mounted) {

View File

@ -1,28 +1,76 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wake_alarm_sync/services/alarm_ramp.dart';
/// The alarm schedule, which the user cannot weaken.
///
/// The alarm is deliberately **not** opt-in: there is no "set alarm" button to
/// forget and no cancel to reach for at 02:00. The time is baked in, and the
/// only edit the UI offers is moving the *next* alarm **earlier**.
/// forget and no cancel to reach for at 02:00. The time is baked in — the
/// daily ramp in `alarm_ramp.dart`, 08:00 down to 07:00 a minute a day — and
/// the only edit the UI offers is moving the *next* alarm **earlier**.
///
/// Earlier-only is what makes this tamper-resistant: every change the user can
/// make costs them sleep, so a half-asleep user has no lever that helps them
/// stay in bed. Moving it later, disabling it, or skipping a day are simply
/// not expressible.
class AlarmPolicy {
/// Creates a policy for a given override, if one is active.
const AlarmPolicy({this.overrideHour, this.overrideMinute});
/// Creates a policy for the next alarm's baseline and optional override.
const AlarmPolicy({
required this.baselineHour,
required this.baselineMinute,
this.overrideHour,
this.overrideMinute,
});
/// The baseline wake hour. Everything else ratchets down from here.
static const int baselineHour = 8;
/// Resolves the next alarm after [now], given a [stored] one-shot override.
///
/// The ramp is evaluated for the day the alarm will actually **fire** on,
/// not the day it is armed: `main()` and the home screen usually arm the
/// evening before, and evaluating "today" there would arm tomorrow at
/// today's (one minute later) time, every single day. Today is tried
/// first; tomorrow always qualifies because the ramp never moves later.
factory AlarmPolicy.resolve(DateTime now, int? stored) {
final today = DateTime(now.year, now.month, now.day);
var policy = AlarmPolicy._forDay(today, stored);
// Built from fields, not today + Duration: on a DST day local midnight
// plus N minutes is not N minutes past midnight on the wall clock.
final at = DateTime(
now.year,
now.month,
now.day,
policy.hour,
policy.minute,
);
if (!at.isAfter(now)) {
policy = AlarmPolicy._forDay(
DateTime(now.year, now.month, now.day + 1),
stored,
);
}
return policy;
}
/// The baseline wake minute.
static const int baselineMinute = 0;
factory AlarmPolicy._forDay(DateTime day, int? stored) {
final base = rampMinutesOn(day);
// A stored value at or after the baseline would be a weakening, so it is
// ignored rather than trusted — the store is not a trust boundary.
final override = stored != null && stored < base ? stored : null;
return AlarmPolicy(
baselineHour: base ~/ 60,
baselineMinute: base % 60,
overrideHour: override == null ? null : override ~/ 60,
overrideMinute: override == null ? null : override % 60,
);
}
/// SharedPreferences key for a one-shot earlier override (minutes of day).
static const String kOverrideKey = 'alarmPolicy.overrideMinutes';
/// Hour of the ramp baseline on the day the next alarm fires.
final int baselineHour;
/// Minute of the ramp baseline on the day the next alarm fires.
final int baselineMinute;
/// Hour of the active override, or null when running at the baseline.
final int? overrideHour;
@ -38,36 +86,26 @@ class AlarmPolicy {
/// Whether an earlier-than-baseline override is currently in force.
bool get isOverridden => overrideHour != null;
/// Minutes-of-day for the baseline, used to reject non-earlier edits.
static const int _baselineMinutes = baselineHour * 60 + baselineMinute;
/// Loads the policy, applying any active one-shot override.
static Future<AlarmPolicy> load() async {
/// Loads the policy for the next alarm after [now] (default: the clock).
static Future<AlarmPolicy> load({DateTime? now}) async {
final prefs = await SharedPreferences.getInstance();
final stored = prefs.getInt(kOverrideKey);
if (stored == null || stored >= _baselineMinutes) {
// A stored value at or after the baseline would be a weakening, so it is
// ignored rather than trusted — the store is not a trust boundary.
return const AlarmPolicy();
}
return AlarmPolicy(
overrideHour: stored ~/ 60,
overrideMinute: stored % 60,
return AlarmPolicy.resolve(
now ?? DateTime.now(),
prefs.getInt(kOverrideKey),
);
}
/// Records a one-shot earlier alarm, returning false if it is not earlier.
///
/// Rejecting a later time is the whole point: this is the only write the UI
/// exposes, so it must be incapable of buying the user extra sleep.
static Future<bool> setEarlier(int hour, int minute) async {
/// exposes, so it must be incapable of buying the user extra sleep. The bar
/// is the next alarm as it stands — the ramp baseline, or an active
/// override, which can only be moved earlier still.
static Future<bool> setEarlier(int hour, int minute, {DateTime? now}) async {
final minutes = hour * 60 + minute;
if (minutes >= _baselineMinutes) return false;
final current = await load(now: now);
if (minutes >= current.hour * 60 + current.minute) return false;
final prefs = await SharedPreferences.getInstance();
final existing = prefs.getInt(kOverrideKey);
// Ratchet: an active override can only be moved earlier still, never
// relaxed back towards the baseline.
if (existing != null && minutes >= existing) return false;
await prefs.setInt(kOverrideKey, minutes);
return true;
}
@ -75,8 +113,9 @@ class AlarmPolicy {
/// Clears the one-shot override, returning to the baseline.
///
/// Called after the alarm fires. Without this the first early start would
/// become permanent, and the user would have no way back to 08:00 short of
/// reinstalling — a one-way ratchet with no reset is a trap, not a defence.
/// become permanent, and the user would have no way back to the ramp short
/// of reinstalling — a one-way ratchet with no reset is a trap, not a
/// defence.
static Future<void> resetAfterFire() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(kOverrideKey);

View File

@ -0,0 +1,36 @@
import 'dart:math' as math;
// The baseline wake time, lowered one minute per calendar day to 07:00.
//
// "Cooking the frog": 2026-09-25 is the last 08:00 morning, 2026-09-26 rings
// at 07:59, and so on until 2026-11-24 reaches the 07:00 floor, which is then
// permanent. The time is a pure function of the date the alarm *fires* on —
// no counter, no stored start date — so neither a reinstall nor wiped app
// data can reset the ramp. Every calendar day counts, free days included, so
// free days cannot stall it.
//
// Mirrored by `AlarmRamp.kt` (native re-arm) and `wake_alarm/_ramp.py` (PC
// fallback and clamp); `wake_alarm/tests/test_ramp.py` parses both copies
// and fails when the constants drift.
/// The last day at the old 08:00 baseline; each day after it is a minute
/// earlier.
final DateTime rampAnchor = DateTime.utc(2026, 9, 25);
/// Minutes of day on the anchor date (08:00).
const int rampStartMinutes = 8 * 60;
/// The floor the ramp stops at, for good (07:00).
const int rampFloorMinutes = 7 * 60;
/// Baseline wake time on [day]'s local calendar date, in minutes of day.
///
/// Only the date of [day] matters. Days are counted between UTC midnights
/// built from the local y/m/d, so a DST change (2026-10-25 is inside the
/// ramp) cannot turn a 23- or 25-hour day into a skipped or doubled minute.
/// Days before the anchor stay at 08:00 rather than extrapolating later.
int rampMinutesOn(DateTime day) {
final date = DateTime.utc(day.year, day.month, day.day);
final elapsed = math.max(0, date.difference(rampAnchor).inDays);
return math.max(rampFloorMinutes, rampStartMinutes - elapsed);
}

View File

@ -28,7 +28,7 @@ class AlarmScheduler {
///
/// The phone rings **daily**, matching the PC's `ALARM_DAYS` (all seven
/// days) and its baked-in fallback hour. Callers pass a time resolved by
/// `AlarmPolicy`, never a user-chosen one: the schedule is fixed at 08:00
/// `AlarmPolicy`, never a user-chosen one: the schedule is the daily ramp
/// and only ever ratchets earlier.
Future<void> schedule(int hour, int minute) => _channel.invokeMethod<void>(
'schedule',

View File

@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wake_alarm_sync/screens/ring_screen.dart';
import 'package:wake_alarm_sync/screens/session_screen.dart';
import 'package:wake_alarm_sync/services/alarm_policy.dart';
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
import 'package:wake_alarm_sync/services/challenge.dart';
import 'package:wake_alarm_sync/services/home_location_settings.dart';
@ -22,10 +23,12 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late List<String> calls;
late List<Object?> armed;
Map<String, Object?>? presence;
setUp(() async {
calls = <String>[];
armed = <Object?>[];
presence = null;
SharedPreferences.setMockInitialValues(<String, Object>{});
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
@ -33,6 +36,7 @@ void main() {
const MethodChannel(AlarmScheduler.channelName),
(call) async {
calls.add(call.method);
if (call.method == 'armSchedule') armed.add(call.arguments);
if (call.method == 'stepCount') return 500;
if (call.method == 'hasNfc') return true;
if (call.method == 'readPresence') return presence;
@ -100,6 +104,24 @@ void main() {
expect((await SessionStore().loadCurrent())?.reRings, 0);
});
testWidgets('the dismiss re-arms the ramp, not the spent override', (
tester,
) async {
// dismiss() natively re-arms the *stored* time, which is the one-shot
// override just spent; without an explicit re-arm it rang at 05:00 every
// day until the home screen was next opened.
await AlarmPolicy.setEarlier(5, 0);
final answers = await pumpApp(tester);
await dismiss(tester, answers);
final next = AlarmPolicy.resolve(DateTime.now(), null);
expect(
calls.lastIndexOf('armSchedule'),
greaterThan(calls.indexOf('dismiss')),
);
expect(armed.last, <String, int>{'hour': next.hour, 'minute': next.minute});
expect(next.isOverridden, isFalse);
});
testWidgets('the session hears tags after the ring screen is gone', (
tester,
) async {

View File

@ -2,56 +2,78 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wake_alarm_sync/services/alarm_policy.dart';
/// Every test pins "now": the baseline is the ramp, so an unpinned test that
/// passes at 08:00 today fails at 07:59 tomorrow.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Evening of the ramp's first day: the next alarm is 2026-09-26, 07:59.
final evening = DateTime(2026, 9, 25, 22);
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
test('a fresh install runs at the baseline', () async {
final policy = await AlarmPolicy.load();
expect(policy.hour, AlarmPolicy.baselineHour);
expect(policy.minute, AlarmPolicy.baselineMinute);
String hm(AlarmPolicy p) =>
'${p.hour.toString().padLeft(2, '0')}:'
'${p.minute.toString().padLeft(2, '0')}';
test('armed the evening before, it uses the day it fires on', () async {
// The whole point of evaluating the fire day: arming at 22:00 on the last
// 08:00 day must already give tomorrow's 07:59, or the phone would ring
// at yesterday's time every single day.
final policy = await AlarmPolicy.load(now: evening);
expect(hm(policy), '07:59');
expect(policy.isOverridden, isFalse);
});
test('before the alarm on its own day, it is still today', () {
final policy = AlarmPolicy.resolve(DateTime(2026, 10, 5, 3), null);
expect(hm(policy), '07:50');
});
test('once today has fired, it is tomorrow', () {
final policy = AlarmPolicy.resolve(DateTime(2026, 10, 5, 7, 50), null);
expect(hm(policy), '07:49');
});
test('past the floor it stays at 07:00', () {
expect(hm(AlarmPolicy.resolve(DateTime(2027, 3, 1, 12), null)), '07:00');
});
test('an earlier time is accepted and applied', () async {
expect(await AlarmPolicy.setEarlier(6, 30), isTrue);
final policy = await AlarmPolicy.load();
expect(policy.hour, 6);
expect(policy.minute, 30);
expect(await AlarmPolicy.setEarlier(6, 30, now: evening), isTrue);
final policy = await AlarmPolicy.load(now: evening);
expect(hm(policy), '06:30');
expect(policy.isOverridden, isTrue);
expect(policy.baselineHour * 60 + policy.baselineMinute, 7 * 60 + 59);
});
test('a later time is refused', () async {
expect(await AlarmPolicy.setEarlier(9, 0), isFalse);
expect((await AlarmPolicy.load()).hour, AlarmPolicy.baselineHour);
expect(await AlarmPolicy.setEarlier(9, 0, now: evening), isFalse);
expect(hm(await AlarmPolicy.load(now: evening)), '07:59');
});
test('the baseline itself is not an "earlier" time', () async {
expect(
await AlarmPolicy.setEarlier(
AlarmPolicy.baselineHour,
AlarmPolicy.baselineMinute,
),
isFalse,
);
test('the ramp baseline itself is not an "earlier" time', () async {
expect(await AlarmPolicy.setEarlier(7, 59, now: evening), isFalse);
// 08:00 was the baseline yesterday; it is a minute late now.
expect(await AlarmPolicy.setEarlier(8, 0, now: evening), isFalse);
expect(await AlarmPolicy.setEarlier(7, 58, now: evening), isTrue);
});
test('an active override can only ratchet further down', () async {
await AlarmPolicy.setEarlier(6, 0);
// 07:00 is earlier than the 08:00 baseline but LATER than the active
await AlarmPolicy.setEarlier(6, 0, now: evening);
// 07:00 is earlier than the 07:59 baseline but LATER than the active
// 06:00 override, so accepting it would buy the user an hour of sleep.
expect(await AlarmPolicy.setEarlier(7, 0), isFalse);
expect((await AlarmPolicy.load()).hour, 6);
expect(await AlarmPolicy.setEarlier(5, 30), isTrue);
expect((await AlarmPolicy.load()).hour, 5);
expect(await AlarmPolicy.setEarlier(7, 0, now: evening), isFalse);
expect(hm(await AlarmPolicy.load(now: evening)), '06:00');
expect(await AlarmPolicy.setEarlier(5, 30, now: evening), isTrue);
expect(hm(await AlarmPolicy.load(now: evening)), '05:30');
});
test('firing resets to the baseline (one-shot)', () async {
await AlarmPolicy.setEarlier(5, 0);
await AlarmPolicy.setEarlier(5, 0, now: evening);
await AlarmPolicy.resetAfterFire();
final policy = await AlarmPolicy.load();
expect(policy.hour, AlarmPolicy.baselineHour);
final policy = await AlarmPolicy.load(now: evening);
expect(hm(policy), '07:59');
expect(policy.isOverridden, isFalse);
});
@ -61,13 +83,21 @@ void main() {
SharedPreferences.setMockInitialValues(<String, Object>{
AlarmPolicy.kOverrideKey: 23 * 60,
});
final policy = await AlarmPolicy.load();
expect(policy.hour, AlarmPolicy.baselineHour);
final policy = await AlarmPolicy.load(now: evening);
expect(hm(policy), '07:59');
expect(policy.isOverridden, isFalse);
});
test('the baseline is 08:00', () async {
expect(AlarmPolicy.baselineHour, 8);
expect(AlarmPolicy.baselineMinute, 0);
test('an override the ramp has caught up with lapses', () {
// 07:45 was an early start in September; by 2026-10-20 the ramp itself
// is 07:35, so the stale override would be a *later* alarm.
final policy = AlarmPolicy.resolve(DateTime(2026, 10, 19, 22), 7 * 60 + 45);
expect(hm(policy), '07:35');
expect(policy.isOverridden, isFalse);
});
test('without a clock it resolves against now', () async {
final policy = await AlarmPolicy.load();
expect(policy.hour * 60 + policy.minute, lessThanOrEqualTo(8 * 60));
});
}

View File

@ -0,0 +1,49 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:wake_alarm_sync/services/alarm_ramp.dart';
String _fmt(int minutes) =>
'${(minutes ~/ 60).toString().padLeft(2, '0')}:'
'${(minutes % 60).toString().padLeft(2, '0')}';
void main() {
test('the ramp: 08:00, a minute a day, then 07:00 for good', () {
final cases = <DateTime, String>{
DateTime(2026): '08:00',
DateTime(2026, 9, 25): '08:00',
DateTime(2026, 9, 26): '07:59',
DateTime(2026, 10, 5): '07:50',
DateTime(2026, 11, 23): '07:01',
DateTime(2026, 11, 24): '07:00',
DateTime(2026, 11, 25): '07:00',
DateTime(2030, 6): '07:00',
};
for (final MapEntry(key: day, value: expected) in cases.entries) {
expect(_fmt(rampMinutesOn(day)), expected, reason: '$day');
}
});
test('only the date matters, not the time of day', () {
expect(
rampMinutesOn(DateTime(2026, 9, 26, 23, 59)),
rampMinutesOn(DateTime(2026, 9, 26)),
);
});
test('the DST change on 2026-10-25 costs exactly one minute a day', () {
// Local midnights either side of the fall-back are 25 hours apart; a
// Duration-based count would see 0 or 2 days somewhere around here.
expect(_fmt(rampMinutesOn(DateTime(2026, 10, 24, 23, 30))), '07:31');
expect(_fmt(rampMinutesOn(DateTime(2026, 10, 25, 0, 30))), '07:30');
expect(_fmt(rampMinutesOn(DateTime(2026, 10, 26, 0, 30))), '07:29');
});
test('never moves later from one day to the next', () {
var previous = rampStartMinutes;
for (var n = -5; n < 90; n++) {
final minutes = rampMinutesOn(DateTime(2026, 9, 25 + n));
expect(minutes, lessThanOrEqualTo(previous));
expect(minutes, greaterThanOrEqualTo(rampFloorMinutes));
previous = minutes;
}
});
}

View File

@ -15,14 +15,12 @@ from pathlib import Path
ALARM_DAYS: frozenset[int] = frozenset({0, 1, 2, 3, 4, 5, 6})
# Hour at which the alarm fires when the phone's alarm cannot be resolved at
# all — no network *and* no cached read ever written. Minute is implicitly 0.
#
# Deliberately the SAME baseline the phone bakes in (AlarmPolicy.baselineHour),
# so the two halves agree even with the network down. It used to be 13:00,
# which meant a Firebase outage silently moved the alarm five hours later —
# the one direction the whole design refuses to allow.
FALLBACK_ALARM_HOUR: int = 8
# The time the alarm fires at when the phone's alarm cannot be resolved at all
# (no network *and* no cached read ever written) is ``_ramp.baseline_time`` —
# deliberately the SAME baseline the phone bakes in (``alarm_ramp.dart``), so
# the two halves agree even with the network down. It used to be a fixed
# 13:00, which meant a Firebase outage silently moved the alarm five hours
# later — the one direction the whole design refuses to allow.
# State file for wake alarm (HMAC-signed)
@ -71,7 +69,7 @@ LOG_DEDUPE_FILE: Path = LOG_STATE_DIR / "last_event.json"
# SYNC_DEVICES_PREFIX and falls back to this path for a phone that has not
# yet published under its uuid. Keep reading it until every install has
# migrated; deleting it early means a stale phone's alarm silently stops
# being seen, and the trigger falls back to FALLBACK_ALARM_HOUR.
# being seen, and the trigger falls back to the ramp baseline.
SYNC_ALARM_PATH: str = "wake-alarm-sync/devices/phone/alarm.json"
# The directory holding one subdirectory per publishing device.
@ -114,8 +112,8 @@ SYNC_HTTP_TIMEOUT_SECONDS: float = 10.0
# phone left one record stamped 2026-08-09, and the PC honoured it faithfully
# for three weeks -- a publish that never happens is indistinguishable from one
# that has not changed, so the last successful publish is authoritative
# forever. Expiring to FALLBACK_ALARM_HOUR is safe precisely because that
# constant is the phone's own baseline, so a lapsed record degrades to the
# forever. Expiring to the ramp baseline is safe precisely because that
# is the phone's own baseline, so a lapsed record degrades to the
# right answer rather than a guess.
PUBLISHED_ALARM_MAX_AGE_SECONDS: float = 14 * 24 * 60 * 60

71
wake_alarm/_ramp.py Normal file
View File

@ -0,0 +1,71 @@
"""The baseline wake time, lowered one minute per calendar day to 07:00.
"Cooking the frog": 2026-09-25 is the last 08:00 morning, 2026-09-26 rings
at 07:59, and so on until 2026-11-24 reaches the 07:00 floor, which is then
permanent. The time is a pure function of the date the alarm fires on — no
counter, no stored start date — so neither a reinstall nor a wiped state file
can reset the ramp, and there is nothing that could run away in either
direction.
Every calendar day counts, free days included: counting only rung days would
let free days stall the ramp and move its finish date.
Three copies of this function exist and must agree: this one (PC fallback
and clamp), ``phone_app/lib/services/alarm_ramp.dart`` (the policy the phone
arms and publishes) and ``AlarmRamp.kt`` (the native re-arm after a dismiss,
a free day, a boot or the watchdog). ``tests/test_ramp.py`` parses the other
two and fails when their constants drift from these.
"""
from __future__ import annotations
from datetime import UTC, date, datetime
# The last day at the old 08:00 baseline; each day after it is a minute earlier.
RAMP_ANCHOR: date = date(2026, 9, 25)
# Minutes of day on the anchor date (08:00).
RAMP_START_MINUTES: int = 8 * 60
# The floor the ramp stops at, for good (07:00).
RAMP_FLOOR_MINUTES: int = 7 * 60
def baseline_minutes(day: date) -> int:
"""Return the baseline wake time on *day*, as minutes after midnight.
Days before the anchor stay at 08:00 rather than extrapolating later:
the ramp only ever moves the alarm earlier.
Args:
day: The local calendar date the alarm fires on.
Returns:
Minutes after local midnight, between the floor and the start.
"""
elapsed = max(0, (day - RAMP_ANCHOR).days)
return max(RAMP_FLOOR_MINUTES, RAMP_START_MINUTES - elapsed)
def baseline_time(day: date) -> tuple[int, int]:
"""Return the baseline wake time on *day* as ``(hour, minute)``.
Args:
day: The local calendar date the alarm fires on.
Returns:
The hour and minute of the baseline.
"""
return divmod(baseline_minutes(day), 60)
def local_today() -> date:
"""Return today's *local* calendar date — the date the phone rings on.
Never ``_state._today_str()``, which is UTC: between local midnight and
02:00 in summer it names yesterday, a minute later than today's ramp.
Returns:
The system-local date. Also the seam tests patch.
"""
return datetime.now(tz=UTC).astimezone().date()

View File

@ -34,8 +34,9 @@ import sys
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
from wake_alarm._constants import FALLBACK_ALARM_HOUR, MORNING_SESSION_FILE
from wake_alarm._constants import MORNING_SESSION_FILE
from wake_alarm._logging_setup import configure_logging
from wake_alarm._ramp import baseline_time
from wake_alarm._session_payload import newest_session
from wake_alarm._session_policy import to_entry
from wake_alarm._sync import get_alarm
@ -99,8 +100,8 @@ def refresh(now: datetime) -> dict[str, object] | None:
today=today,
refreshed_at=now.timestamp(),
# Same clamp as the trigger: the phone may only move the alarm earlier
# than the baseline, so a later synced value never widens the grace.
alarm=min((alarm.hour, alarm.minute), (FALLBACK_ALARM_HOUR, 0)),
# than today's ramp baseline, so a later value never widens the grace.
alarm=min((alarm.hour, alarm.minute), baseline_time(now.date())),
)
if not write_entry(entry):
return None

View File

@ -33,10 +33,10 @@ from wake_alarm._alarm_payload import in_range
from wake_alarm._constants import (
ALARM_CACHE_FILE,
ALARM_CACHE_MAX_AGE_SECONDS,
FALLBACK_ALARM_HOUR,
PUBLISHED_ALARM_MAX_AGE_SECONDS,
)
from wake_alarm._logging_setup import configure_logging
from wake_alarm._ramp import baseline_time, local_today
from wake_alarm._sync_transport import (
_FIREBASE_AVAILABLE,
_fetch_firebase_alarm,
@ -167,7 +167,7 @@ def get_alarm(*, max_cache_age_seconds: float = ALARM_CACHE_MAX_AGE_SECONDS) ->
1. A cache entry younger than *max_cache_age_seconds* (no network).
2. A live fetch, Firebase first (cached on success).
3. Any cache entry, however stale — better an old alarm than none.
4. ``FALLBACK_ALARM_HOUR:00``.
4. Today's ramp baseline (``_ramp.baseline_time``).
A record the phone published longer ago than
``PUBLISHED_ALARM_MAX_AGE_SECONDS`` is skipped at *every* step, including
@ -206,11 +206,9 @@ def get_alarm(*, max_cache_age_seconds: float = ALARM_CACHE_MAX_AGE_SECONDS) ->
_logger.info("Using stale cached alarm — sync read failed")
return Alarm(cached[0], cached[1], "stale-cache")
_logger.info(
"No synced or cached alarm — falling back to %02d:00",
FALLBACK_ALARM_HOUR,
)
return Alarm(FALLBACK_ALARM_HOUR, 0, "fallback")
hour, minute = baseline_time(local_today())
_logger.info("No synced or cached alarm — falling back to %02d:%02d", hour, minute)
return Alarm(hour, minute, "fallback")
def _parse_args(argv: list[str]) -> argparse.Namespace:

View File

@ -109,7 +109,7 @@ def fetch_firebase_logs() -> list[tuple[str, str]] | None:
Discovers device directories rather than reading one fixed path: the
phone's device id is migrating from the constant "phone" to a per-install
uuid, and a reader pinned to the old path would stop seeing the alarm the
moment the phone migrated — falling back to FALLBACK_ALARM_HOUR, i.e.
moment the phone migrated — falling back to the ramp baseline, i.e.
waking the user at the wrong time. Listing covers both ids, and
SYNC_ALARM_PATH remains as a last resort for a backend that cannot list.

View File

@ -21,7 +21,7 @@ must be built in the same timezone the user reads off their phone.
from __future__ import annotations
import argparse
from datetime import UTC, datetime, timedelta
from datetime import UTC, date, datetime, timedelta
import logging
import subprocess
import sys
@ -30,11 +30,11 @@ import freedays
from wake_alarm._constants import (
ALARM_DAYS,
FALLBACK_ALARM_HOUR,
TRIGGER_CATCHUP_MINUTES,
TRIGGER_TARGET_UNIT,
)
from wake_alarm._logging_setup import configure_logging
from wake_alarm._ramp import RAMP_START_MINUTES, baseline_time
from wake_alarm._state import (
save_trigger_fired,
was_trigger_fired_today,
@ -170,37 +170,42 @@ def _parse_args(argv: list[str]) -> argparse.Namespace:
return parser.parse_args(argv)
def _clamp_to_baseline(alarm: Alarm) -> Alarm:
"""Refuse to let any resolved alarm land later than the baseline.
def _clamp_to_baseline(alarm: Alarm, day: date) -> Alarm:
"""Refuse to let any resolved alarm land later than *day*'s ramp baseline.
The phone bakes in ``FALLBACK_ALARM_HOUR`` and only ever ratchets *earlier*,
so a synced value later than the baseline means something is wrong — a
stale record from before the policy landed, a half-written payload, or a
tampered store. Whatever the cause, the safe direction is unambiguous:
honour it if it is earlier, clamp it if it is later.
The phone arms at ``_ramp.baseline_time`` and only ever ratchets earlier,
so honour an earlier value and clamp a later one. This is the PC half of
the watchdog: without it the one thing the design forbids — the alarm
silently moving later — would be reachable through sync.
This is the PC half of the watchdog. Without it the PC would faithfully
reproduce a bad remote value, and the one thing the design forbids —
the alarm silently moving later — would be reachable through sync.
Up to 08:00 a later value is expected lag, not tampering: the phone
publishes when the app runs, so yesterday's record is a minute behind
today's ramp. That logs at INFO (this runs every tick); only a value later
than the old 08:00 baseline — stale or tampered — is worth a WARNING.
Args:
alarm: The alarm as resolved by ``get_alarm``.
day: The local date the alarm fires on.
Returns:
The same alarm, or the baseline when the resolved time is later.
The same alarm, or the ramp baseline when the resolved time is later.
"""
if (alarm.hour, alarm.minute) <= (FALLBACK_ALARM_HOUR, 0):
base = baseline_time(day)
if (alarm.hour, alarm.minute) <= base:
return alarm
_logger.warning(
"Resolved alarm %02d:%02d is later than the %02d:00 baseline "
"(source=%s) — clamping. The phone can only move it earlier, so a "
"later value means a stale or tampered record.",
level = logging.INFO
if alarm.hour * 60 + alarm.minute > RAMP_START_MINUTES:
level = logging.WARNING
_logger.log(
level,
"Resolved alarm %02d:%02d is later than today's %02d:%02d baseline "
"(source=%s) — clamping.",
alarm.hour,
alarm.minute,
FALLBACK_ALARM_HOUR,
*base,
alarm.source,
)
return Alarm(FALLBACK_ALARM_HOUR, 0, f"clamped-{alarm.source}")
return Alarm(*base, f"clamped-{alarm.source}")
def main() -> None:
@ -209,7 +214,7 @@ def main() -> None:
args = _parse_args(sys.argv[1:])
now = _now()
alarm = _clamp_to_baseline(get_alarm())
alarm = _clamp_to_baseline(get_alarm(), now.date())
should_fire, reason = _decide(now, alarm)
if args.dry_run:

View File

@ -0,0 +1,91 @@
"""Tests for the daily ramp — and that its three copies agree."""
from __future__ import annotations
from datetime import date
from pathlib import Path
import re
import pytest
from wake_alarm._ramp import (
RAMP_ANCHOR,
RAMP_FLOOR_MINUTES,
RAMP_START_MINUTES,
baseline_minutes,
baseline_time,
local_today,
)
_PHONE = Path(__file__).resolve().parents[2] / "phone_app"
_DART = _PHONE / "lib/services/alarm_ramp.dart"
_KOTLIN = _PHONE / "android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmRamp.kt"
class TestBaseline:
"""A minute earlier per calendar day, from 08:00 to a permanent 07:00."""
@pytest.mark.parametrize(
("day", "expected"),
[
(date(2026, 1, 1), (8, 0)),
(date(2026, 9, 25), (8, 0)),
(date(2026, 9, 26), (7, 59)),
(date(2026, 10, 24), (7, 31)),
(date(2026, 10, 25), (7, 30)),
(date(2026, 10, 26), (7, 29)),
(date(2026, 11, 23), (7, 1)),
(date(2026, 11, 24), (7, 0)),
(date(2026, 11, 25), (7, 0)),
(date(2030, 6, 1), (7, 0)),
],
)
def test_the_ramp(self, day: date, expected: tuple[int, int]) -> None:
"""Before the anchor stays 08:00; the floor holds for good."""
assert baseline_time(day) == expected
def test_never_moves_later(self) -> None:
"""Day over day, the baseline is monotonically non-increasing."""
days = [date.fromordinal(RAMP_ANCHOR.toordinal() + n) for n in range(-5, 90)]
minutes = [baseline_minutes(d) for d in days]
assert minutes == sorted(minutes, reverse=True)
def test_local_today_is_a_date(self) -> None:
"""The seam returns the system-local calendar date."""
assert isinstance(local_today(), date)
def _grab(pattern: str, text: str) -> tuple[str, ...]:
match = re.search(pattern, text)
assert match is not None, pattern
return match.groups()
class TestCopiesAgree:
"""The Dart and Kotlin copies carry the same constants as this one.
Three copies of a pure function are cheap; three copies that silently
disagree mean the phone rings at one time and the PC fires at another.
"""
def test_dart(self) -> None:
"""``alarm_ramp.dart`` matches ``_ramp.py``."""
text = _DART.read_text()
y, m, d = _grab(r"rampAnchor = DateTime\.utc\((\d+), (\d+), (\d+)\)", text)
assert date(int(y), int(m), int(d)) == RAMP_ANCHOR
h, mi = _grab(r"rampStartMinutes = (\d+) \* (\d+);", text)
assert int(h) * int(mi) == RAMP_START_MINUTES
h, mi = _grab(r"rampFloorMinutes = (\d+) \* (\d+);", text)
assert int(h) * int(mi) == RAMP_FLOOR_MINUTES
def test_kotlin(self) -> None:
"""``AlarmRamp.kt`` matches ``_ramp.py``."""
text = _KOTLIN.read_text()
y, m, d = _grab(
r"ANCHOR: LocalDate = LocalDate\.of\((\d+), (\d+), (\d+)\)", text
)
assert date(int(y), int(m), int(d)) == RAMP_ANCHOR
h, mi = _grab(r"START_MINUTES = (\d+) \* (\d+)", text)
assert int(h) * int(mi) == RAMP_START_MINUTES
h, mi = _grab(r"FLOOR_MINUTES = (\d+) \* (\d+)", text)
assert int(h) * int(mi) == RAMP_FLOOR_MINUTES

View File

@ -163,6 +163,16 @@ class TestRefresh:
assert entry is not None
assert entry["exempt_until"] == _local("2026-09-19T08:15:00").isoformat()
def test_the_clamp_follows_the_ramp(self) -> None:
# 2026-10-05 is 07:50 on the ramp, so a synced 08:00 grants 08:05.
with (
patch("wake_alarm._session.fetch_firebase_logs", return_value=[]),
patch("wake_alarm._session.get_alarm", return_value=Alarm(8, 0, "cache")),
):
entry = refresh(datetime(2026, 10, 5, 7, 0).astimezone())
assert entry is not None
assert entry["exempt_until"] == _local("2026-10-05T08:05:00").isoformat()
def test_an_earlier_synced_alarm_shortens_the_grace(self) -> None:
with (
patch("wake_alarm._session.fetch_firebase_logs", return_value=[]),

View File

@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import date
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
@ -9,9 +10,6 @@ import urllib.error
import pytest
from wake_alarm._constants import (
FALLBACK_ALARM_HOUR,
)
from wake_alarm._sync import (
Alarm,
_fetch_github_alarm,
@ -226,12 +224,11 @@ class TestGetAlarm:
"stale-cache",
)
def test_falls_back_to_constant(self) -> None:
"""With no cache and no network, the fixed fallback hour is used."""
with patch("wake_alarm._sync.fetch_remote_alarm", return_value=None):
def test_falls_back_to_the_ramp(self) -> None:
"""With no cache and no network, today's ramp baseline is used."""
with (
patch("wake_alarm._sync.fetch_remote_alarm", return_value=None),
patch("wake_alarm._sync.local_today", return_value=date(2026, 10, 5)),
):
alarm = get_alarm()
assert (alarm.minute, alarm.source) == (0, "fallback")
# Bound to the constant, not a literal: the fallback deliberately
# matches the phone's baked-in baseline, so hardcoding the number here
# would fail every time that shared value moves.
assert alarm.hour == FALLBACK_ALARM_HOUR
assert (alarm.hour, alarm.minute, alarm.source) == (7, 50, "fallback")

View File

@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import date
import json
import time
from typing import TYPE_CHECKING
@ -10,7 +11,6 @@ from unittest.mock import patch
import pytest
from wake_alarm._constants import (
FALLBACK_ALARM_HOUR,
PUBLISHED_ALARM_MAX_AGE_SECONDS,
)
from wake_alarm._sync import (
@ -84,10 +84,10 @@ class TestLapsedPublishedAlarm:
"wake_alarm._sync.fetch_remote_alarm",
return_value=(7, 0, ancient),
),
patch("wake_alarm._sync.local_today", return_value=date(2026, 10, 5)),
):
alarm = get_alarm()
assert alarm.source == "fallback"
assert alarm.hour == FALLBACK_ALARM_HOUR
assert (alarm.hour, alarm.minute, alarm.source) == (7, 50, "fallback")
def test_a_recent_remote_is_used(self, tmp_path: Path) -> None:
"""A freshly stamped record is honoured as normal."""

View File

@ -2,12 +2,12 @@
from __future__ import annotations
from datetime import datetime
from datetime import date, datetime
import logging
from unittest.mock import patch
import pytest
from wake_alarm._constants import FALLBACK_ALARM_HOUR
from wake_alarm._sync import Alarm
from wake_alarm._trigger import (
_clamp_to_baseline,
@ -38,27 +38,52 @@ def _ungated() -> None:
yield
# 2026-09-26 is the ramp's first step: 07:59.
_DAY = date(2026, 9, 26)
class TestClampToBaseline:
"""The PC-side watchdog: a synced alarm may never land later than 08:00."""
"""The PC-side watchdog: a synced alarm may never land later than the ramp."""
def test_an_earlier_alarm_passes_through_untouched(self) -> None:
"""The phone ratchets earlier, so earlier values are legitimate."""
alarm = Alarm(6, 30, "remote")
assert _clamp_to_baseline(alarm) == alarm
assert _clamp_to_baseline(alarm, _DAY) == alarm
def test_the_baseline_itself_passes_through(self) -> None:
"""Equal to the baseline is not later than it."""
alarm = Alarm(FALLBACK_ALARM_HOUR, 0, "remote")
assert _clamp_to_baseline(alarm) == alarm
"""Equal to the day's baseline is not later than it."""
alarm = Alarm(7, 59, "remote")
assert _clamp_to_baseline(alarm, _DAY) == alarm
def test_a_later_alarm_is_clamped_to_the_baseline(self) -> None:
"""The one direction the design forbids must not be reachable."""
clamped = _clamp_to_baseline(Alarm(13, 0, "remote"))
assert (clamped.hour, clamped.minute) == (FALLBACK_ALARM_HOUR, 0)
clamped = _clamp_to_baseline(Alarm(13, 0, "remote"), _DAY)
assert (clamped.hour, clamped.minute) == (7, 59)
assert clamped.source == "clamped-remote"
def test_a_later_minute_within_the_baseline_hour_is_clamped(self) -> None:
def test_before_the_ramp_the_baseline_is_eight(self) -> None:
"""08:30 is later than 08:00, so the minute matters too."""
clamped = _clamp_to_baseline(Alarm(FALLBACK_ALARM_HOUR, 30, "cache"))
assert (clamped.hour, clamped.minute) == (FALLBACK_ALARM_HOUR, 0)
clamped = _clamp_to_baseline(Alarm(8, 30, "cache"), date(2026, 9, 1))
assert (clamped.hour, clamped.minute) == (8, 0)
assert clamped.source == "clamped-cache"
def test_yesterdays_time_is_clamped_quietly(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A record a minute behind the ramp is lag, not tampering: INFO only.
This runs every tick, so a WARNING here would be 1440 lines a day on
every morning the phone app was not opened.
"""
with caplog.at_level(logging.INFO, logger="wake_alarm._trigger"):
clamped = _clamp_to_baseline(Alarm(8, 0, "remote"), _DAY)
assert (clamped.hour, clamped.minute) == (7, 59)
assert [r.levelno for r in caplog.records] == [logging.INFO]
def test_later_than_eight_still_warns(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""Past the old 08:00 baseline no phone could have published it."""
with caplog.at_level(logging.INFO, logger="wake_alarm._trigger"):
_clamp_to_baseline(Alarm(8, 1, "remote"), _DAY)
assert [r.levelno for r in caplog.records] == [logging.WARNING]