Open the PC from 05:00 until the alarm has been dismissed; the session is the check

The first carrot only opened at 08:30: someone up at 07:00 (the goal) got
the LeetCode gate at the 05:00 login-arm, and the workout lock was held off
by an unrelated clock. A day with no session yet is now exempt until the
phone's alarm plus 15 min -- clamped to the 08:00 baseline like the trigger
-- so the login-arm defers by itself; the alarm rings regardless, and a
dismiss that has produced no session by then means "not up". The refresher
runs from 05:00 (every 10 min until 07:00) so the file is today's when the
locks decide. The rule moved to _session_policy (250-line cap).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XTdfXjbGYYrY7Quxcfz6mg
This commit is contained in:
Krzysztof Rudnicki 2026-09-20 08:39:24 +02:00
parent c3c129b068
commit d953d67ae3
7 changed files with 295 additions and 155 deletions

View File

@ -17,14 +17,21 @@ provisioning, and a 10 s hardware off still wins); it can be *noticed*.
## The rule
A morning earns the carrot **only by being completed in time**:
The goal is *waking up*, not reaching a clock. So the PC is open from the
moment it is usable (the night lockdown lifts at 05:00) until the alarm has
rung and been dismissed; the dismiss plus the morning session is the "are
you still up" check, and passing it keeps the PC open until 11:00
(2026-09-20 — the first version only opened at 08:30 and locked someone who
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" |
| 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 |
| `failed`, or nothing started today | none | today's ordinary ladder (screen-locker's 05:00–08:30 window, leetcode-guard at login/09:00) |
| `failed` | none | today's ordinary ladder |
| alarm unknown (unconfigured PC) | none | fail closed |
Fail closed: a sync outage, a refresher that is not running, a bad signature
— all read as "no carrot". Nothing here can make a lock *earlier* than today.
@ -32,8 +39,9 @@ Fail closed: a sync outage, a refresher that is not running, a bad signature
## The plumbing
**wake-alarm is the only Firebase reader.** `wake-alarm-session.timer`
(`*-*-* 07..10:00/2:00` and `11:00:00`, `Persistent=true`, ~121 reads/day)
runs `python -m wake_alarm._session --refresh`:
(`*-*-* 05..06:00/10:00`, `07..10:00/2:00` and `11:00:00`, `Persistent=true`,
~133 reads/day — from 05:00 because that is when the login-armed locks
decide) runs `python -m wake_alarm._session --refresh`:
1. `_sync_transport.fetch_firebase_logs()` — every device's `alarm.json`.
2. `_session_payload.newest_session()` — the finished entries of
@ -45,9 +53,9 @@ runs `python -m wake_alarm._session --refresh`:
3. `_session.to_entry()` + `write_entry()` — an HMAC-signed
`~/.local/state/wake_alarm/morning_session.json` that **always describes
today** (PC-local date): today's session with `exempt_until` signed in, or
a `none` heartbeat when the phone has nothing for today. The heartbeat is
what lets a consumer tell "fresh, no session" from "the refresher has not
run yet" by the date alone.
a `none` entry (exempt until alarm + 15 min) when the phone has nothing
for today. The entry is also what lets a consumer tell "fresh, no session"
from "the refresher has not run yet" by the date alone.
Dates are the phone's local day throughout. `wake_alarm._state._today_str`
is UTC and must not be used here (screen-locker compares against its local
@ -57,10 +65,13 @@ is UTC and must not be used here (screen-locker compares against its local
∧ `exempt_until` present ∧ `now < exempt_until`. Neither re-derives the
cutoffs, neither imports `crdt_sync`, neither talks to Firebase:
- screen-locker `screen_locker/_morning_session.py` → the `wake_alarm_skip`
rung of `_auto_upgrade._check_today_state_exits`, in its old position
(after `workout_logged_today`, before `early_bird_banked`). The decision
record carries `exempt_until` and `outcome`.
- screen-locker `screen_locker/_morning_session.py` → **the early-bird
window *is* this carrot** (`EarlyBirdMixin._is_early_bird_time`, since
2026-09-20; the 05:00–08:30 clock and the extended-to-09:00 reward are
gone). The `wake_alarm_skip` rung defers and banks the early-bird marker;
when the carrot ends, the next run tries a phone/RunnerUp workout before
locking (`early-bird-workout-check.timer` at 09:30:30 and 11:00:30). The
decision record carries `exempt_until` and `outcome`.
- leetcode-guard `leetcode_guard/_morning_session.py` → `_cli._run_lock`
returns `EXIT_OK` with `deferred: …` before `build_client()`. A run
deferral, never ledger state (`decide()` stays pure; a deleted file cannot
@ -70,7 +81,7 @@ cutoffs, neither imports `crdt_sync`, neither talks to Firebase:
**A PC booted mid-morning** has a missing or yesterday's file until the
timer's `Persistent=true` catch-up lands, and that needs the network. Only
the enforce path, only inside 07:00–11:00, and only when the file is not
the enforce path, only inside 05:00–11:00, and only when the file is not
today's, both consumers retry for ≤ 30 s (5 s steps) and then proceed as
normal with a WARNING. Status paths never wait; tests pin the retry to 0.
@ -78,7 +89,8 @@ normal with a WARNING. Status paths never wait; tests pin the retry to 0.
- A lock already on screen is not lifted by a later publish: a session
that completes at 09:45 after the 09:30 lock stays locked. The publish
would have to arrive before the boundary.
would have to arrive before the boundary. (The 05:00 login-arm no longer
hits this: the day starts exempt.)
- A session finishing inside ~2 min before 09:30 may be seen as
`in_progress` at the 09:30 tick and lock; bounded by the timer cadence.
- No extra stick for a `failed` session beyond losing the carrot.

View File

@ -3,8 +3,11 @@ Description=Wake Alarm morning-session refresh, every 2 min through the morning
Documentation=https://github.com/kuhyx/wake-alarm
[Timer]
# Every two minutes from 07:00 to 10:58, then once at 11:00 (the carrot's end)
# so the last rewrite lands on the boundary. ~121 Firebase reads/day.
# From 05:00 (the night lockdown lifts and the login-armed locks decide):
# every 10 min until the alarm hour is near, every 2 min from 07:00 to 10:58,
# then once at 11:00 (the carrot's end) so the last rewrite lands on the
# boundary. ~133 Firebase reads/day.
OnCalendar=*-*-* 05..06:00/10:00
OnCalendar=*-*-* 07..10:00/2:00
OnCalendar=*-*-* 11:00:00
AccuracySec=1s

View File

@ -150,3 +150,9 @@ ENERGY_FIELD: str = "latest_energy"
SESSION_PROVISIONAL_GRACE: timedelta = timedelta(minutes=90)
SESSION_PROVISIONAL_CAP: tuple[int, int] = (9, 30)
SESSION_COMPLETED_UNTIL: tuple[int, int] = (11, 0)
# Before the alarm, being up is the goal, not an offence: a day with no
# session yet is exempt until the alarm has rung and had time to be
# dismissed (ring -> tags -> steps -> answers -> the start publish reaches the
# PC). A phone switched off at the alarm locks this long after it.
SESSION_NONE_GRACE: timedelta = timedelta(minutes=15)

View File

@ -8,14 +8,17 @@ morning; each run fetches the phone's logs, picks the newest morning
entry that always describes **today**:
* today's session, with ``exempt_until`` signed in when it is live
(``min(started_at + 90 min, 09:30)``) or completed (``11:00``);
* a ``none`` heartbeat when the phone has nothing for today, so a consumer can
tell "fresh, no session" from "the refresher has not run yet" (a PC booted
mid-morning) by the date alone.
(``min(started_at + 90 min, 09:30)``) or completed in time (``11:00``);
* a ``none`` entry when the phone has nothing for today, exempt until the
alarm plus ``SESSION_NONE_GRACE``: waking up early is the goal, so the PC
stays open until the alarm has rung and been dismissed. The entry is also
what lets a consumer tell "fresh, no session" from "the refresher has not
run yet" (a PC booted mid-morning) by the date alone.
Consumers apply one rule -- HMAC ok, date is today, ``now < exempt_until`` --
and never re-derive the cutoffs. Dates are the phone's local day throughout;
``_state._today_str`` is UTC and must not be used here.
and never re-derive the cutoffs; those live in ``_session_policy``. Dates are
the phone's local day throughout; ``_state._today_str`` is UTC and must not
be used here.
python -m wake_alarm._session --refresh # fetch and rewrite the file
python -m wake_alarm._session --show # print the verified entry
@ -24,116 +27,22 @@ and never re-derive the cutoffs. Dates are the phone's local day throughout;
from __future__ import annotations
import argparse
from datetime import datetime, time
from datetime import datetime
import json
import logging
import sys
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
from wake_alarm._constants import (
MORNING_SESSION_FILE,
SESSION_COMPLETED_UNTIL,
SESSION_PROVISIONAL_CAP,
SESSION_PROVISIONAL_GRACE,
)
from wake_alarm._constants import FALLBACK_ALARM_HOUR, MORNING_SESSION_FILE
from wake_alarm._logging_setup import configure_logging
from wake_alarm._session_payload import SessionRecord, newest_session
from wake_alarm._session_payload import newest_session
from wake_alarm._session_policy import to_entry
from wake_alarm._sync import get_alarm
from wake_alarm._sync_transport import fetch_firebase_logs
_logger = logging.getLogger(__name__)
NONE_OUTCOME = "none"
def _local(iso: str) -> datetime:
"""A phone-stamped naive local ISO instant as an aware local datetime."""
return datetime.fromisoformat(iso).astimezone()
def _at(date: str, clock: tuple[int, int]) -> datetime:
"""Local wall-clock instant ``clock`` on the phone's session date."""
return datetime.combine(
datetime.fromisoformat(date).date(), time(*clock)
).astimezone()
def _cutoff(record: SessionRecord) -> datetime | None:
"""The instant a live morning stops being exempt: start + grace, capped."""
try:
started = _local(record.started_at)
except ValueError:
_logger.info(
"Session started_at %r unreadable; no exemption", record.started_at
)
return None
return min(
started + SESSION_PROVISIONAL_GRACE, _at(record.date, SESSION_PROVISIONAL_CAP)
)
def exempt_until(record: SessionRecord) -> datetime | None:
"""When the carrot this morning earned runs out; None when it earned none.
Live: the start plus one honest morning, capped -- relative so an early
alarm cannot bank hours by aborting. Completed: the flat end, but only if
it finished inside that same cutoff -- a phone switched back on at noon
completes the legs then, and that must not un-lock anything. Failed: none.
"""
cutoff = _cutoff(record)
if cutoff is None or record.outcome == "failed":
return None
if record.outcome == "in_progress":
return cutoff
try:
finished = _local(record.finished_at or "")
except ValueError:
_logger.info(
"Session finished_at %r unreadable; no exemption", record.finished_at
)
return None
if finished > cutoff:
_logger.info(
"Session finished %s, after the %s cutoff; no exemption", finished, cutoff
)
return None
return _at(record.date, SESSION_COMPLETED_UNTIL)
def to_entry(
record: SessionRecord | None, *, today: str, refreshed_at: float
) -> dict[str, object]:
"""The unsigned file body for ``record`` (today's) or the ``none`` heartbeat."""
if record is None:
return {
"date": today,
"outcome": NONE_OUTCOME,
"started_at": None,
"finished_at": None,
"energy": None,
"weight_kg": None,
"re_rings": 0,
"device_id": "",
"published_at": None,
"refreshed_at": refreshed_at,
}
entry: dict[str, object] = {
"date": record.date,
"outcome": record.outcome,
"started_at": record.started_at,
"finished_at": record.finished_at,
"energy": record.energy,
"weight_kg": record.weight_kg,
"re_rings": record.re_rings,
"device_id": record.device_id,
"published_at": record.published_at,
"refreshed_at": refreshed_at,
}
until = exempt_until(record)
if until is not None:
entry["exempt_until"] = until.isoformat()
return entry
def write_entry(entry: dict[str, object]) -> bool:
"""Sign and write ``entry``; False when the disk refused."""
@ -183,7 +92,15 @@ def refresh(now: datetime) -> dict[str, object] | None:
if record is not None and record.date != today:
_logger.info("Newest morning is %s, not today; writing none", record.date)
record = None
entry = to_entry(record, today=today, refreshed_at=now.timestamp())
alarm = get_alarm()
entry = to_entry(
record,
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)),
)
return entry if write_entry(entry) else None

View File

@ -0,0 +1,135 @@
"""The carrot's rule: what a morning earns, as one signed ``exempt_until``.
Pure -- a ``SessionRecord`` (or none) in, the unsigned file body out. Split
from ``_session`` (fetch, sign, write, CLI) at the 250-line cap; this is the
half a reader wants when asking "why is the PC open right now".
* nothing started today: exempt until the alarm plus ``SESSION_NONE_GRACE``
-- being up before the alarm is the goal, and the phone rings at the alarm
regardless, so a dismiss that has not produced a session by then means
"not up";
* live: ``min(started_at + 90 min, 09:30)``, relative so an aborted early
alarm cannot bank hours;
* completed inside that cutoff: 11:00; completed later, or failed: nothing.
"""
from __future__ import annotations
from datetime import datetime, time
import logging
from typing import TYPE_CHECKING
from wake_alarm._constants import (
SESSION_COMPLETED_UNTIL,
SESSION_NONE_GRACE,
SESSION_PROVISIONAL_CAP,
SESSION_PROVISIONAL_GRACE,
)
if TYPE_CHECKING:
from wake_alarm._session_payload import SessionRecord
_logger = logging.getLogger(__name__)
NONE_OUTCOME = "none"
def _local(iso: str) -> datetime:
"""A phone-stamped naive local ISO instant as an aware local datetime."""
return datetime.fromisoformat(iso).astimezone()
def _at(date: str, clock: tuple[int, int]) -> datetime:
"""Local wall-clock instant ``clock`` on the phone's session date."""
return datetime.combine(
datetime.fromisoformat(date).date(), time(*clock)
).astimezone()
def _cutoff(record: SessionRecord) -> datetime | None:
"""The instant a live morning stops being exempt: start + grace, capped."""
try:
started = _local(record.started_at)
except ValueError:
_logger.info(
"Session started_at %r unreadable; no exemption", record.started_at
)
return None
return min(
started + SESSION_PROVISIONAL_GRACE, _at(record.date, SESSION_PROVISIONAL_CAP)
)
def exempt_until(record: SessionRecord) -> datetime | None:
"""When the carrot this morning earned runs out; None when it earned none.
Live: the start plus one honest morning, capped -- relative so an early
alarm cannot bank hours by aborting. Completed: the flat end, but only if
it finished inside that same cutoff -- a phone switched back on at noon
completes the legs then, and that must not un-lock anything. Failed: none.
"""
cutoff = _cutoff(record)
if cutoff is None or record.outcome == "failed":
return None
if record.outcome == "in_progress":
return cutoff
try:
finished = _local(record.finished_at or "")
except ValueError:
_logger.info(
"Session finished_at %r unreadable; no exemption", record.finished_at
)
return None
if finished > cutoff:
_logger.info(
"Session finished %s, after the %s cutoff; no exemption", finished, cutoff
)
return None
return _at(record.date, SESSION_COMPLETED_UNTIL)
def to_entry(
record: SessionRecord | None,
*,
today: str,
refreshed_at: float,
alarm: tuple[int, int] | None = None,
) -> dict[str, object]:
"""The unsigned file body for ``record`` (today's) or the ``none`` entry.
``alarm`` is the phone's alarm time; with no session yet the day is
exempt until that plus ``SESSION_NONE_GRACE``. None means "unknown",
which grants nothing -- fail closed.
"""
if record is None:
entry: dict[str, object] = {
"date": today,
"outcome": NONE_OUTCOME,
"started_at": None,
"finished_at": None,
"energy": None,
"weight_kg": None,
"re_rings": 0,
"device_id": "",
"published_at": None,
"refreshed_at": refreshed_at,
}
if alarm is not None:
entry["exempt_until"] = (_at(today, alarm) + SESSION_NONE_GRACE).isoformat()
return entry
entry = {
"date": record.date,
"outcome": record.outcome,
"started_at": record.started_at,
"finished_at": record.finished_at,
"energy": record.energy,
"weight_kg": record.weight_kg,
"re_rings": record.re_rings,
"device_id": record.device_id,
"published_at": record.published_at,
"refreshed_at": refreshed_at,
}
until = exempt_until(record)
if until is not None:
entry["exempt_until"] = until.isoformat()
return entry

View File

@ -11,7 +11,6 @@ from unittest.mock import patch
from wake_alarm import _session
from wake_alarm._session import (
describe,
exempt_until,
main,
read_entry,
refresh,
@ -19,9 +18,12 @@ from wake_alarm._session import (
write_entry,
)
from wake_alarm._session_payload import SessionRecord
from wake_alarm._sync import Alarm
if TYPE_CHECKING:
import pytest
from collections.abc import Generator
import pytest
NOW = datetime(2026, 9, 19, 8, 30).astimezone()
@ -49,35 +51,6 @@ def _local(iso: str) -> datetime:
return datetime.fromisoformat(iso).astimezone()
class TestExemptUntil:
"""The policy, signed in once so no consumer re-derives it."""
def test_completed_in_time_earns_eleven(self) -> None:
assert exempt_until(_record()) == _local("2026-09-19T11:00:00")
def test_live_is_start_plus_grace_capped(self) -> None:
assert exempt_until(_record("in_progress", finished=None)) == _local(
"2026-09-19T09:30:00"
)
early = _record("in_progress", started="2026-09-19T06:00:00.000", finished=None)
assert exempt_until(early) == _local("2026-09-19T07:30:00")
def test_completed_after_the_cutoff_earns_nothing(self) -> None:
"""A phone switched on at noon completes the legs then; no carrot."""
assert exempt_until(_record(finished="2026-09-19T12:33:00.000")) is None
# An aborted 06:00 alarm "completed" at 10:00 locks no later than today.
late_early = _record(
started="2026-09-19T06:05:00.000", finished="2026-09-19T10:00:00.000"
)
assert exempt_until(late_early) is None
def test_failed_and_unreadable_instants_earn_nothing(self) -> None:
assert exempt_until(_record("failed")) is None
assert exempt_until(_record(started="when?")) is None
assert exempt_until(_record(finished=None)) is None
assert exempt_until(_record(finished="later")) is None
class TestEntryFile:
"""Writing, signing, reading back."""
@ -88,9 +61,16 @@ class TestEntryFile:
assert read_entry() == entry
assert "hmac" in entry
def test_none_heartbeat_and_failed_have_no_exemption(self) -> None:
entry = to_entry(None, today="2026-09-19", refreshed_at=5.0)
def test_no_session_yet_is_exempt_until_the_alarm_plus_grace(self) -> None:
"""Being up before the alarm is the goal; the PC stays open until it rang."""
entry = to_entry(None, today="2026-09-19", refreshed_at=5.0, alarm=(8, 0))
assert entry["outcome"] == "none"
assert entry["exempt_until"] == _local("2026-09-19T08:15:00").isoformat()
early = to_entry(None, today="2026-09-19", refreshed_at=5.0, alarm=(6, 30))
assert early["exempt_until"] == _local("2026-09-19T06:45:00").isoformat()
def test_unknown_alarm_and_failed_have_no_exemption(self) -> None:
entry = to_entry(None, today="2026-09-19", refreshed_at=5.0)
assert "exempt_until" not in entry
failed = to_entry(_record("failed"), today="2026-09-19", refreshed_at=5.0)
assert failed["outcome"] == "failed"
@ -125,6 +105,11 @@ class TestEntryFile:
class TestRefresh:
"""Fetch, select, write."""
@pytest.fixture(autouse=True)
def _alarm(self) -> Generator[None]:
with patch("wake_alarm._session.get_alarm", return_value=Alarm(8, 0, "cache")):
yield
def _logs(self, record_json: dict[str, object]) -> list[tuple[str, str]]:
raw = json.dumps(
{
@ -167,6 +152,25 @@ class TestRefresh:
entry = refresh(NOW)
assert entry is not None
assert (entry["date"], entry["outcome"]) == ("2026-09-19", "none")
assert entry["exempt_until"] == _local("2026-09-19T08:15:00").isoformat()
def test_a_synced_alarm_later_than_the_baseline_is_clamped(self) -> None:
with (
patch("wake_alarm._session.fetch_firebase_logs", return_value=[]),
patch("wake_alarm._session.get_alarm", return_value=Alarm(13, 0, "cache")),
):
entry = refresh(NOW)
assert entry is not None
assert entry["exempt_until"] == _local("2026-09-19T08:15:00").isoformat()
def test_an_earlier_synced_alarm_shortens_the_grace(self) -> None:
with (
patch("wake_alarm._session.fetch_firebase_logs", return_value=[]),
patch("wake_alarm._session.get_alarm", return_value=Alarm(6, 30, "remote")),
):
entry = refresh(NOW)
assert entry is not None
assert entry["exempt_until"] == _local("2026-09-19T06:45:00").isoformat()
def test_unreadable_backend_leaves_the_file_alone(self) -> None:
write_entry(to_entry(_record(), today="2026-09-19", refreshed_at=5.0))
@ -209,7 +213,10 @@ class TestCli:
assert "no verified" in capsys.readouterr().out
def test_refresh_uses_the_backend(self) -> None:
with patch("wake_alarm._session.fetch_firebase_logs", return_value=[]) as fetch:
with (
patch("wake_alarm._session.fetch_firebase_logs", return_value=[]) as fetch,
patch("wake_alarm._session.get_alarm", return_value=Alarm(8, 0, "cache")),
):
assert main(["--refresh"]) == 0
fetch.assert_called_once()
entry = read_entry()

View File

@ -0,0 +1,60 @@
"""The carrot's rule: ``exempt_until`` per outcome (``_session_policy``)."""
from __future__ import annotations
from datetime import datetime
from wake_alarm._session_payload import SessionRecord
from wake_alarm._session_policy import exempt_until
def _record(
outcome: str = "completed",
started: str = "2026-09-19T08:01:00.000",
finished: str | None = "2026-09-19T08:40:00.000",
date: str = "2026-09-19",
) -> SessionRecord:
return SessionRecord(
date=date,
outcome=outcome,
started_at=started,
finished_at=finished,
energy=3,
weight_kg=73.8,
re_rings=0,
device_id="p",
published_at=1.0,
)
def _local(iso: str) -> datetime:
return datetime.fromisoformat(iso).astimezone()
class TestExemptUntil:
"""The policy, signed in once so no consumer re-derives it."""
def test_completed_in_time_earns_eleven(self) -> None:
assert exempt_until(_record()) == _local("2026-09-19T11:00:00")
def test_live_is_start_plus_grace_capped(self) -> None:
assert exempt_until(_record("in_progress", finished=None)) == _local(
"2026-09-19T09:30:00"
)
early = _record("in_progress", started="2026-09-19T06:00:00.000", finished=None)
assert exempt_until(early) == _local("2026-09-19T07:30:00")
def test_completed_after_the_cutoff_earns_nothing(self) -> None:
"""A phone switched on at noon completes the legs then; no carrot."""
assert exempt_until(_record(finished="2026-09-19T12:33:00.000")) is None
# An aborted 06:00 alarm "completed" at 10:00 locks no later than today.
late_early = _record(
started="2026-09-19T06:05:00.000", finished="2026-09-19T10:00:00.000"
)
assert exempt_until(late_early) is None
def test_failed_and_unreadable_instants_earn_nothing(self) -> None:
assert exempt_until(_record("failed")) is None
assert exempt_until(_record(started="when?")) is None
assert exempt_until(_record(finished=None)) is None
assert exempt_until(_record(finished="later")) is None