Compare commits

...

139 Commits

Author SHA1 Message Date
89e6eed105 Bump sync_settings_ui to 0.6.1
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,free-days-interop) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / free-days-interop (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 18:28:23 +01:00
06b70ab312 Bump crdt_sync to v0.12.0
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 14:24:46 +01:00
10938ed012 Align pre-commit sickdays pin to 0.4.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:38:22 +01:00
f182453567 Add morning-session corner strip
Top-right always-on-top strip while the signed morning session is
in_progress: title, "Next: <step>", "Locks return at HH:MM".
wake-alarm-strip.path starts it on every file rewrite; it re-reads
the file each second, asks for a refresh every 30 s, exits 0 when
the session ends. No display/output: warning, exit 1.
Bump gatelock pin to 0.12.0 (corner_strip).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:19:42 +01:00
537a3a79e4 Retry session refresh; sign next_step
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:12:01 +01:00
672eaf8aba Add todo app git hooks
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 13:56:22 +01:00
13f6e3f5d2 Use google_account_token for sign-in
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 11:27:35 +01:00
5525ca6f95 Move TODOs to todo app
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 11:14:40 +01:00
58c4260b6e Pin focus-project 0.3.0, sickdays 0.4.0
Conflicting git-tag pins in the shared user site let the last install downgrade focus_project/sickdays (no harvest, no focus locker).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 10:02:56 +01:00
6033e3815f Home: fit one screen, details behind tiles
Stakes and history move behind two tiles that open bottom sheets;
the page no longer scrolls at Pixel 6a geometry (home_fit_test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWcbzoov1KFZJSFcSs
2026-11-01 22:06:43 +01:00
18a304de55 Trim hardening TODO to real residue
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 22:02:50 +01:00
a51a67e2fe Remove done file-length TODO
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 22:02:11 +01:00
fd65c454e3 chore: bump deps to newest stable
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXTUM9dpnCS2wtFkx4
2026-11-01 20:13:43 +01:00
05738db15a feat: JSON export/import on device
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXTUM9dpnCS2wtFkx4
2026-11-01 19:55:04 +01:00
69be24d4c0 Session: tag catch-up + pre-deadline buzz
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 18:25:15 +01:00
1c2197a3cd deps: flutter 3.47.7 (workflows), gradle 9.8.2, coverage 7.17.0, ruff 0.17.2 (newest stable)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017k9j5dbjenpfZj7dh2faPN
2026-10-23 18:09:14 +02:00
2defe09e6a Launcher: label WakeAlarm, icon fitted to the shared 340px ink circle
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012kQ5PCKqBHAkAVkPSvp6dk
2026-10-23 14:36:09 +02:00
4b72899e5b Pin gatelock-v0.11.0 (Claim.grab_held + held_grabs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dsh4Znwh2KnC7q6vbGpX1N
2026-10-19 11:47:24 +02:00
14b6dac605 deps: gatelock 0.9.0 -> 0.10.0 (pin only)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 18:49:51 +02:00
0060b48b10 deps: sickdays 0.3.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-17 13:53:14 +02:00
597901dc08 phone: sick-day interop both ways with keep; docs
check.sh now runs Dart->Python (keep, unsorted/duplicate input, a cleared
keep day, a keep-only edit that must not re-stamp state) and
Python->Dart (0.2.0 keep sets plus a 0.1.0 record with no keep, a stale
keep and a malformed one), Python 0.2.0 as the oracle with explicit
paths and HOME pointed at a scratch dir. DOCS-sick-days.md and the
SickDays.kt contract describe the alarm-only native cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-16 15:31:11 +02:00
ee7e380278 phone: per-locker sheet on the sick-day calendar
Tapping today or a later normal day opens a sheet with one switch per
locker (Workout lock, LeetCode, Book, Diet, Wake alarm), all off, and
"Mark sick"; a sick day reopens with its switches, "Save" (keep-only
edit, nothing written when unchanged) and "Clear sick day". Past days
stay inert. A sick day keeping any locker carries a dot in the calendar
and a "Kept: ..." line in the list. DayCell moves to day_cell.dart for
the 250-line cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-16 15:30:11 +02:00
7fe6108df3 phone: sick-day keep set (sickdays 0.2.0) in the Dart pool; alarm cache filtered
SickDayPool gains keep: mark/clear write state+actor+keep on one tick,
setKept re-stamps only keep+actor, read rules 1-5 in sick_day_keep.dart.
The native SickDays cache now holds only days on which the alarm stands
down, so a sick day that keeps the alarm rings like a normal day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-16 15:30:11 +02:00
5d0f06b19e PC: sick days stand the alarm down only when it is not kept
All PC enforcement (fallback ring, RTC self-wake, trigger, workday penalty
write/retract, audit) now asks sickdays.stands_down(LOCKER_ALARM, day) via
_sick.alarm_stands_down instead of is_sick_day, so a sick day that keeps the
alarm behaves exactly as a normal stick day. Bump sickdays pin to v0.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-16 15:13:23 +02:00
2e594f041d phone: pin the clock in the stageLocalSettings enforcement test
The test staged a 2026-10-01 event through stageLocalSettings, which called
stageEnforcementData on the real clock; on 2026-10-16 the event aged past
boundEvents' 14-day window and the test went red for everyone.
stageLocalSettings now forwards an optional `now` to stageEnforcementData
(callers unchanged), and the test passes its fixed clock. phone_app suite:
402 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 14:55:26 +02:00
7e40bb138c ci_mirror: build the clean venv with uv (18.3 s -> 2.1 s cold)
The venv rebuild after a requirements.txt change was the largest cold-path
cost of `scripts/check_gate_stamp.sh full`. uv is also what CI installs
with, so the mirror gets closer to CI, not further. The interpreter is
passed as a path: `--python python3` let uv pick an active ~/.venv (3.13)
that crdt-sync 0.9.2 (>=3.14) cannot install into. pip stays as fallback.

Measured under capped.sh (4G, 20 %): `full` warm 10.9 s; fully cold
(no venv, empty PRE_COMMIT_HOME, empty mypy cache) 45.9 s, floor = the
pylint hook env install (~24 s, only after .pre-commit-config.yaml changes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 14:55:18 +02:00
4f149e67a4 phone: read the native sick-day cache back on the Sick days screen
A release build gives no way to see the SharedPreferences cache that
AlarmReceiver reads at ring time (no run-as, no log of its contents), so
"the Dart UI shows it" could not prove "the alarm will stay silent".

- SickDays.store/dates log the sorted set under WakeAlarmSickDays.
- AlarmChannel getSickDays returns the cached set (null if unreadable).
- The Sick days screen reads it on open (before the sync rewrites it) and
  after every sync: "Alarm cache: <dates>" / "none" / "unreadable".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 14:38:25 +02:00
29e64fb7fa Merge branch 'sickdays-phone' into sickdays-pc
# Conflicts:
#	AGENTS.md
2026-10-16 13:26:09 +02:00
e0ef3e1217 docs: sick_day in the phone event contract; portable gradle test note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 13:25:31 +02:00
34037e55c1 phone: sick days — picker, silent ring, stick stand-down, pre-alarm sync
- Sick days screen (own name, sick icon, cat-2 fill): tap today or a later
  day to mark it sick, tap again to clear; past days inert. Writes the
  sickdays wire format (state sick/cleared + actor, one HLC per write) to
  sickdays-sync/devices via crdt_sync syncLog.
- Mutual exclusion in both pickers: each syncs the other pool on open and
  refuses a date it holds, naming the pool; an unreadable pool refuses all.
- Native SickDays cache (fail closed via DayCache); AlarmReceiver skips the
  ring with reason "sick_day" (no markFired, no ring_started); StickCheck
  verdict sick_day, streak skips sick days; stakes card says so.
- Pre-alarm pool sync: allow-while-idle alarm at 21:00 and A-30 (request
  code 1006) runs a headless engine (poolSyncMain) that pulls both pools
  from RTDB and rewrites both native caches, so a PC mark arrives with the
  app closed. The ring decision stays a cache read.
- JVM unit tests (JUnit 4.13.2) for DayCache, RingDecision,
  PoolSyncSchedule, StickCheck; Dart tests; Dart->Python interop check.

pylint hook skipped: verify.py imports sickdays, not in the hook env until
the sickdays-v0.1.0 tag exists; run by hand in a sickdays venv (10.00/10).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 13:22:40 +02:00
8696f2d0bf wake_alarm: sick days stand the PC down (fallback ring, RTC wake, trigger, workday penalty)
A date in the new shared sickdays pool (not a free day) now means, on the PC:
no fallback ring (a ring in progress stops, reason sick_day), no RTC
self-wake for that morning (ours is disarmed), no morning-routine trigger,
and no workday_penalty.json; a penalty issued on a day later marked sick is
retracted (penalty_cancelled, cause sick_day) by the next session refresh or
RTC tick. The audit treats the day as one where nothing is expected.

All pool access goes through wake_alarm/_sick.py: fail closed (unreadable
pool or missing package = not sick), and act modes pull the pool from
Firebase first (RTC --arm on a stick-day target, in-window fallback ticks
and ring polls, the day's first penalty write) because the sickdays timer
pauses through hibernate. Dry runs never pull.

Pins: sickdays-v0.1.0, freedays-v0.4.0, crdt-sync-v0.9.2 (needed by both);
pre-commit 4.7.0, pylint 4.1.3, ruff 0.17.1 (freshness gate).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 08:45:29 +02:00
3b8cd21969 chore: add MIT LICENSE
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-11 18:14:11 +02:00
ffe7666f49 deps: Flutter 3.47.7, shared_preferences 2.5.6
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:27:56 +02:00
a0731c496c Sync: stop reading screen-locker's sync_token (screen-locker is Firebase-only now)
screen-locker's PC sync went Firebase-only on 2026-10-09 and nothing
maintains ~/.config/screen_locker/sync_token any more. The GitHub-fallback
token list now holds only diet_guard's repo-scoped PAT. Drop the stale
note about shutdown-wrapper.sh mirroring the list (the wrapper was removed
on 2026-08-30).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018RHwVPyiiQMPh4M3JQwQku
2026-10-09 19:11:50 +02:00
57a6c6ba0e dependency freshness: bump pylint 4.1.2, url_launcher 6.3.3, github_device_auth v0.3.2 (CI red fix)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-04 17:39:28 +02:00
8e254dbef6 repo contract: CLAUDE.md commands, test_changed, CI gate, AGENTS.md update
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-04 16:58:12 +02:00
a6d5688eb7 CI: slim Flutter SDK for the interop job; APK only on app changes, Gradle cached
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-02 15:08:47 +02:00
83b9d5c4c7 CI: Flutter 3.47.6 in the workflow pins too
The .fvmrc moved in the previous commit; CI's freshness gate also reads the
flutter-version pins in python-tests.yml and release-apk.yml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FBbkN4ZB4aUPJPzR2prRan
2026-10-02 14:40:58 +02:00
9325103f5d Flutter 3.47.6; dismiss re-arm test no longer passes only on Tue-Thu
The expectation resolved the next alarm without the earned ramp set, while
the app (correctly) re-arms with the minute the dismiss just earned. On a
non-workday that is one minute apart, so the test failed Fri-Mon on any
Flutter version. It now loads the policy exactly as the app does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FBbkN4ZB4aUPJPzR2prRan
2026-10-02 14:28:55 +02:00
f95cf826d2 gatelock 0.8.2 -> 0.9.0; mypy 2.4.0, pylint 4.1.1, ruff 0.16.10
gatelock 0.9.0 adds gatelock.morning_session (the shared reader of
wake-alarm's morning carrot, now used by screen-locker, leetcode-guard and
book-guard); nothing here changes behaviour. The tag moved the freshness
gate, so the pin moves with it, together with today's lint-tool releases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FBbkN4ZB4aUPJPzR2prRan
2026-10-02 14:19:53 +02:00
012673aa99 TODO: v2 follow-ups for the next session
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-01 19:39:58 +02:00
9b3c3ba26b Docs: v2 verification status; vmbox can emulate RTC wake now
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-01 12:30:32 +02:00
4527834b45 Take pylint 4.1.1 (newest stable)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-01 12:27:37 +02:00
728e00cde7 Wake enforcement v2: PC fallback ring + RTC self-wake, stacking Tue-Thu phone lockdown, escape hatch until 2026-10-15, stakes in the app, daily incident audit
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-01 12:17:06 +02:00
19f23f35a6 Free days: a month calendar of the shared pool; tap a future date to book it, tap a booked one to release it
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-27 20:53:46 +02:00
7f7fd916f7 Earned ramp: a dismissed Mon/Fri/Sat/Sun morning earns the minute; workdays hold, misses and free days earn nothing; workdays from freedays 0.3.0
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-27 20:13:22 +02:00
a4876d84ec Speed up CI: uv installs, split pre-commit into mypy/pylint/rest
- pre-commit: drop the 28 s requirements.txt install (only
  dependency-freshness among the system hooks needs third-party code:
  pyyaml, packaging), run pre-commit directly instead of
  pre-commit/action, and split mypy and pylint into their own matrix
  jobs with per-group hook-env caches. Same hook set, same
  SKIP=free-days-interop (the rest group).
- Tests: uv with a cached wheel store for requirements.txt (pip took
  22 s), -q and -p no:sugar. No -n auto: the suite runs in ~0.5 s and
  measured ~1.2 s under pytest-xdist.
- free-days-interop (the critical path): build the freedays venv with
  uv instead of venv + pip (12 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 17:45:00 +02:00
16f9ddeb13 Keep the test suite's JSONL log out of the live events.jsonl
_logging_setup attaches its JSONL sink the first time an entry point's
main() runs, and the conftest never redirected LOG_JSONL_FILE or
LOG_DEDUPE_FILE. Every suite run appended ~25 fixture warnings ("Synced
alarm out of range: 24:0") to ~/.local/state/wake_alarm/events.jsonl, the
log a failed wake-up is reconstructed from. Patch _logging_setup's names
(it imported them by value) in the autouse _hermetic fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 17:44:52 +02:00
702f37a7ba Bump ruff 0.16.8 -> 0.16.9 and Gradle 9.7.1 -> 9.8.0: newest stable dependency-freshness gate
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 13:27:37 +02:00
d8b07b2be4 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>
2026-09-25 13:15:44 +02:00
8be972c31a Record the two deferred hardware wake-defeat ideas as a repo TODO
ESP32 second-alarm device and wearable wake-defeat check were scoped
during the workday-stick session but explicitly deferred (no existing
firmware project, no owned wearable, both need a real purchase first).
Kept here instead of ~/src/todo/BACKLOG.md, which is gitignored and
export-only from the todo app and would silently drop the addition on
the next export.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018kwx6YYv9Mnw9EtRsJ6hbf
2026-09-23 22:07:56 +02:00
8275966a83 Bump pylint 4.0.8 -> 4.0.9: newest stable dependency-freshness gate
CI's dependency-freshness check runs live against PyPI and caught the
new release after this session's local pre-commit run used a stale
snapshot.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018kwx6YYv9Mnw9EtRsJ6hbf
2026-09-23 21:37:38 +02:00
bfe8bab58a Add the Tue/Wed/Thu workday stick: signal focus-owner and write tomorrow's penalty
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:20:58 +02:00
92b7ae5d76 pre-push is a 1-second stamp check; the suites moved to the manual stage
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 21:29:10 +02:00
d953d67ae3 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
2026-09-20 08:39:24 +02:00
c3c129b068 Make the morning session the carrot: earn 11:00 by finishing it in time
On 2026-09-19 the phone was powered off after the bathroom tag and nothing
on the PC noticed: every finished session was published and nothing read
it. Now wake-alarm distils the phone's morning into an HMAC-signed
~/.local/state/wake_alarm/morning_session.json (wake-alarm-session.timer,
07:00-11:00 every 2 min) that screen-locker and leetcode-guard read to
defer their locks -- provisionally until min(start + 90 min, 09:30) while
the session is live, until 11:00 once it completed inside that cutoff,
and not at all for a session finished later (the phone switched on at
noon completes the legs then; that must un-lock nothing).

The phone publishes the session at start as well as at finish
(current_session, cleared with the finish stamp), so the PC can tell
"started, not finished" from "never started". A required 1-5 energy tap
joins the weigh-in and ships as latest_energy with a PC reader mirroring
_weight (the shared half is _field_reader).

Also fixes the vmbox harness, red since the 2026-09-11 home-tidy: the
guest tree lives at ~/wake-alarm, and the INSTALL-OK grep matched vm's
echo of the command line. Takes Flutter 3.47.5.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tp54ewdXRLaimUuT8LgYyn
2026-09-19 16:40:51 +02:00
af293413c0 Keep the morning session reachable after leaving the app; drop the still-phone watch
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:01:22 +02:00
c7e7695466 Read the phone's newest weigh-in on the PC
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:49:08 +02:00
6bfb059309 Take gatelock 0.8.2, flutter_secure_storage 11.2.0, coverage 7.16.1 and ruff 0.16.8
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:36:33 +02:00
f31f195187 Keep the morning going after the ring: weigh-in, shower, dress, desk, or it rings again
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:35:40 +02:00
84d6cbdc17 Take gatelock 0.8.1, Flutter 3.47.4 and flutter_secure_storage 11.1.1
The freshness gate's three findings. gatelock 0.8.1 restructured
LockConfig, which this repo does not use (only log_integrity), so the
pin moves without a code change; pylint stays at 10 against it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 20:02:31 +02:00
07f2408f7e Re-point paths for the ~ reorganisation (home-tidy)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwtowrowDXx6ccmWVPkCaF
2026-09-11 18:46:34 +02:00
8e60a3667a Run the free-day interop gate in CI where Flutter exists
The pre-commit job has no Flutter and no freedays venv, so the new hook
could only fail there. It now runs as its own job in python-tests.yml
(utils checkout + a venv with crdt-sync and freedays + subosito Flutter),
and the pre-commit job SKIPs that one hook, with the reason next to it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019pBgaXSJKyY3DarYpDatDF
2026-09-11 13:55:53 +02:00
758b2976b8 Gate the free-day rules against the Python package, and fix two picker paths
showDatePicker asserts that initialDate satisfies selectableDayPredicate,
so with today already free the picker asserted in debug and, in release,
pre-selected a disabled day. The cursor now starts on the first non-free
day. And the reason dialog had no Cancel: a barrier tap marked the day
anyway. Both covered by widget tests; the first fails without the fix.

The cross-language check that proved the Dart port was a one-off probe,
deleted after it ran. It is now scripts/free_days_interop/check.sh, a
pre-commit hook on both inputs: Dart writes one pool through every policy
branch, Python replays the same edits into a scratch pool, and every
semantic reading has to agree. The Python package is the oracle -- Dart's
own count compared to what Python reads from Dart's file cannot see a
drift in what Dart writes. Proved by dropping the sticky consumed flag
from release: remaining dart=33 python=32.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019pBgaXSJKyY3DarYpDatDF
2026-09-11 13:53:56 +02:00
146c427d6d Add the free-day picker, and stop the phone ringing on a free day
The shared pool (~/utils/freedays) was CLI-only: the gates on the PC stood
down, but the phone kept ringing at 08:00 and there was nowhere to mark a
day from bed. This is the one picker for every app.

FreeDayPool is a Dart port of the Python rules with the identical record
shape (id = ISO date; state/consumed/actor/reason on one tick; un-mark is
a state flip, never a tombstone), verified by a real cross-language round
trip: a log written here reads back through freedays.is_free_day and
remaining() with the same verdicts and count, and the PC's live pool reads
here as the same 27 of 35 that `freedays status` prints.

The alarm fires from Kotlin with no engine running, so the pool is
mirrored into a native SharedPreferences set after every mark, release and
sync (channel method setFreeDays), and AlarmReceiver consults it before
starting AlarmService. Fail closed: a missing or corrupt cache rings. All
three branches exercised on the API 36 AVD by broadcasting the receiver.

Firebase only for this namespace -- no GitHub mirror; the alarm record
keeps its own because un-migrated installs depend on it.

Known gap, documented rather than papered over: a day marked on the PC
reaches the phone at the next app launch or picker open, not overnight.
The ring path takes no background dependency by design, so mark on the
phone, or open the app once after marking on the PC.

Verified on the phone (release build, 23181JEGR08034): picker shows the
budget, marks 2026-09-30 with a reason, pushes it to
freedays-sync/devices/<uuid>, releases it with a full refund back to 35.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019pBgaXSJKyY3DarYpDatDF
2026-09-11 13:45:42 +02:00
f709fb8028 Bring Flutter, flutter_secure_storage and ruff up to latest stable
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 12:37:33 +02:00
b5701fb359 Sync the NFC tags and home location so a reinstall gets them back
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 12:34:50 +02:00
c0ed168540 Pin freedays v0.2.0
v0.2.0 drops freedays's gatelock dependency (importing gatelock pulled in
tkinter, so the headless pool needed a GUI toolkit) and adds the sync
timer that makes a day marked on the phone actually reach this machine.

Mechanical, but not optional: the freshness gate compares the pinned tag
against the newest release, so leaving v0.1.0 here would turn this repo
red on its next commit.

Suite re-run against v0.2.0 before pinning it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:58:35 +02:00
2904d97b2c Bring the phone app's analyzer up to latest stable
very_good_analysis ^10.3.0 -> ^11.0.0, which the freshness gate flagged
against phone_app/pubspec.yaml the moment the pre-push CI mirror ran
--all-files. Pre-existing; it blocked the push rather than being caused
by it.

The major bump newly flags two async_return_with_no_await sites, both now
`return await` rather than suppressed. The rule is correct in both: a
future returned without awaiting escapes the enclosing async function, so
a failure surfaces at the caller with a stack trace that no longer names
the code that made the call. firebase_backend.dart:91 is the one that
matters -- a rejected credential fetch should fail inside the function
that describes itself as recovering from exactly that.

flutter analyze clean, 146 phone-app tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:30:00 +02:00
981396442d Do not ring at all on a shared free day
Fourth app onto freedays (~/utils/freedays), the shared pool of
pre-declared days when every gate app stands down.

_skip_reason is the right seam: it already exists to say why the alarm
must not fire, and the free-day check joins the day gate and the
once-per-day latch as another clock-independent reason. It goes first
because it is the cheapest and the most absolute.

"free day" means the alarm does not ring -- not that it rings later. The
orchestrator is never started, so neither the alarm nor the workout lock
behind it appears. That is the one app in this fleet where standing down
is a physical event rather than an absent dialog, so it is worth being
explicit: nothing happens that morning.

Fail closed, as everywhere else: an unreadable pool reads as "not free"
and the alarm rings normally. Silence is never the failure mode -- there
is a test that a corrupt pool still wakes you up.

The pool is one local file read, so the per-minute tick stays a
millisecond-scale process with no network in it.

The pylint hook's gatelock pin had drifted all the way back to v0.4.1;
it moves to v0.7.3 alongside crdt-sync and freedays. pip refuses two
different direct URLs for one distribution, so that stale pin would have
made the hook environment unresolvable rather than merely old.

requirements.txt also takes pytest-randomly 5.0.0 and ruff 0.16.6, which
the freshness gate flagged once the file was touched. 171 tests, 100%
coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:28:54 +02:00
4e5908baa7 Read the versionCode offset from the repo root, not the app dir
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 11:55:45 +02:00
7523cb4225 Ring the away profile when the phone is not at home
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 11:45:11 +02:00
25321d88fa Stop a hand-picked build number from stranding the phone
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 11:45:04 +02:00
6e668df5c1 Note that uninstall.sh is load-bearing for install
install.sh calls it as its last step, so renaming or deleting uninstall.sh
breaks installing, not just removing. Easy to miss from either file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 16:53:27 +02:00
3410b1bc45 Write down the two invariants this session cost
The sequential bootstrap in HomeScreen.initState and the published-age check
are both the kind of thing a later change reverts as tidy-up: one looks like
three independent futures that could run in parallel, the other like a
duplicate of the cache-age check. Both took a three-week silent outage to
find, so they are recorded with the failure rather than just the rule.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 16:38:04 +02:00
6be5420fcf Stop trusting an alarm the phone published months ago
Belt-and-braces for the publishing race fixed in the previous commit. That bug
is gone, but the shape of the failure is worth closing on this side too: a
publish that never happens is indistinguishable from one that has not changed,
so the last successful publish stayed authoritative forever. One record stamped
2026-08-09 had the PC starting the morning routine at 07:00 for three weeks.

get_alarm now skips any record the phone published longer ago than
PUBLISHED_ALARM_MAX_AGE_SECONDS (14 days) and falls back. That is safe
precisely because FALLBACK_ALARM_HOUR is the phone's own baseline, so a lapsed
record degrades to the right answer rather than to a guess -- and an override
is one-shot anyway, so reverting to the baseline is what the phone would say.

The check is on when the PHONE stamped it, never on when we fetched, and that
distinction is the whole design. Checking the fetch would be trivially
defeated: the cache is rewritten from the same stale record every few minutes,
so `fetched_at` is always fresh no matter how old the record behind it is.
So the winning HLC's instant is now carried out of _alarm_payload, through
_sync_transport, and persisted in the cache as `published_at`. Nothing else
reads that cache any more -- the shutdown wrapper that used to went with the
PC's waking role -- so widening its shape is free.

An undated record is trusted rather than expired. The GitHub mirror reads a
single fixed path with no per-field HLC, so treating "cannot tell how old this
is" as "too old" would break that whole backend, and refusing an alarm we
merely failed to date is a worse failure than honouring it.

test_sync.py and test_sync_backends.py crossed the 250-line cap, so the new
lapse cases and the backend-ordering cases move to test_sync_lapsed.py and
test_sync_dispatch.py.

168 tests at 100% branch coverage. Verified against the real backend: the
cache now carries published_at, and `_sync --show` still resolves 08:00 from
the record the phone stamped minutes earlier.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 16:37:13 +02:00
60f79774c9 Fix the race that stopped the phone publishing at all
The PC has been firing the morning routine at 07:00 instead of 08:00, off a
record the phone published on 2026-08-09 and never superseded. The phone was
connected to Firebase the whole time and the home screen still said "Connect a
sync backend in Settings first."

initState fired three futures concurrently and the last one read what the
first two were still writing:

    unawaited(_applyPolicy());     // sets _hour/_minute
    unawaited(_loadSyncState());   // sets _service
    unawaited(_syncToPc());        // reads BOTH

`publish` takes the service as a *parameter*, so it captured `_service` by
value while it was still null. Assigning it moments later could never reach
the call. The startup publish therefore passed null every time and bailed out
before touching the network -- and `_syncToPc` had exactly one call site, that
one, so nothing published, ever. `_applyPolicy` has the same shape: a publish
that did win the race would have sent the baseline instead of an active
override. The bootstrap is now strictly sequential.

Three things conspired to hide it for three weeks:

- `publish` returned "Connect a sync backend in Settings first." for BOTH a
  missing backend and a null service, so a broken store looked like a setup
  step the user had never done. The advice pointed at something that was not
  broken. The two causes now report differently, with a regression test.
- `_loadSyncState` swallowed its exception with `on Exception catch (_)`, so
  if the store genuinely failed to open there was no trace anywhere. It logs
  now.
- `_pickEarlier` never published at all, so "Wake me earlier tomorrow" -- the
  one schedule edit the app offers -- never reached the PC either. It does now.

home_screen.dart went over the 250-line cap, so its body moves to
`screens/home_body.dart` as a stateless widget taking plain values. The screen
keeps the state and the ordering rules, which is where the bugs lived.

Verified on the Pixel 6a: home screen now reads "Synced to PC ✓", and the PC's
`_sync --show --no-cache` returns `08:00 (remote)` stamped seconds earlier,
against `07:00` from 2026-08-09 before. The phone had also minted a new device
id, so both records exist in Firebase and the HLC ranking picks the newer --
which is exactly why that reader ranks by HLC and not by listing order.

104 Dart tests pass; analyzer clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 16:28:20 +02:00
ada7e69c60 Don't let the retired-cleanup abort a working install
install.sh runs under `set -euo pipefail` and step 3 called uninstall.sh,
which uses `sudo rm`. On a machine without cached or passwordless sudo that
call fails, so the install aborted at step 3 -- after the package was
installed and the timer enabled. It would report failure for an install that
had actually worked, which is precisely the half-finished state the
sudo-refusal guard at the top of the script exists to prevent.

The vmbox harness could not have caught this: the guest's `arch` user has
passwordless sudo, which is why the run went green.

The cleanup is opportunistic -- a machine with no /usr/local/bin/shutdown
needs nothing done -- so it is now non-fatal, gated on `sudo -n` so it cannot
hang on a password prompt in a non-TTY context either. When it is skipped the
script says why it matters and gives the exact command, rather than leaving
the shutdown wrapper in place silently.

Verified: uninstall.sh --retired-only and install.sh are both idempotent and
exit 0 on a host where the retired pieces are already gone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:38:30 +02:00
ccb0018a2c Take gatelock 0.7.3
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:36:43 +02:00
a573b1b9d6 Fix two ways the vmbox harness went green while broken
Trimming the harness to the three surviving cases took `pacman -S tk` with it,
and that step was doing two jobs nobody had written down.

It was the guest's BOOT. `vm new`/`vm reset` leave a sandbox stopped and there
is no `vm up`, so the first `vm run` is what starts it; `vm repo` then failed
with "sandbox is not running". The pacman step is restored with that spelled
out, so the next person to prune it knows what else they are removing.

And tk is still genuinely required, despite the Tk alarm window being gone:
`_state` imports `gatelock.log_integrity` for the HMAC, and gatelock's
`__init__` imports tkinter at module scope, so `import gatelock` dies with
"libtk8.6.so: cannot open shared object file". Measured in the guest.

The second fix is the one that matters. `run_install` trusted `vm run`'s exit
code, but `vm run` reports the VM's verdict rather than the guest command's
status -- the same fail-open `guest_cases.sh` already guards against with its
ALL-CASES-PASSED sentinel. So install.sh died on that ImportError, the step
reported success, and the three cases downstream failed with no hint that the
install was the cause. It now confirms an INSTALL-OK marker in the output.

Harness passes: imports-from-system-python, trigger-timer-enabled,
trigger-dry-run. That run exercised the new install.sh end to end, including
its call into uninstall.sh --retired-only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:33:35 +02:00
e67cef0c54 Retire the PC's waking role; keep the trigger
The PC no longer wakes anyone -- the phone does. This deletes the alarm
window, the audio escalation, the sink/reactivation machinery, the power-key
inhibitor, the escape hatch, the curtains, the smart plug, the brightness and
DDC/CI control, the hibernate path (shutdown wrapper + rtcwake + sleep hook)
and the challenge set: 30 modules, 34 test files, ~5k lines.

What stays is the part that still earns its keep: the per-minute trigger
reads the alarm the phone published and starts morning-routine.service, so
the workout lock still runs at the right time.

THE ONE LOAD-BEARING BEHAVIOUR CHANGE. Deleting _alarm.py orphaned the only
writer of wake_state.json, and _trigger gated on it via
was_alarm_dismissed_today(). With that gone -- and was_workout_logged_today()
already permanently False, since WORKOUT_LOG_FILE does not exist -- both
gates would have been dead and the routine restarted on every tick for the
rest of the 60-minute catch-up window. The unit is Type=simple, so a start
while it runs is a no-op, but the moment the workout lock finished the next
tick would relaunch it on top of the user. So _trigger now writes its own
once-per-day latch (save_trigger_fired / was_trigger_fired_today) and gates
on that. Collapsing the catch-up window instead was rejected: that window is
the entire reason a suspended or just-booted machine still fires. It also
replaces the deleted sleep hook, via Persistent=true.

_trigger also imported should_refire from _alarm_session, which was on the
delete list. Since start_session lived only in _alarm.py, no session record
is ever written again and the branch was unreachable, not merely unused.

WAKE_STATE_FILE is now redirected in tests/conftest.py rather than per-file.
The trigger tests never redirected it, because until this commit nothing on
that path wrote anything -- and a per-file redirect is exactly the kind that
gets forgotten when a new writer appears, with a silent failure: a green
suite that quietly stamped the live state file. Verified by mtime that it
did not.

Cross-repo, same change: morning_routine._orchestrator loses its alarm leg
and its --with-alarm flag. Leaving an orchestrator pointing at a deleted
module caused a month-long silent failure once already.

uninstall.sh is new, and matters more than it looks. /usr/local/bin/shutdown
is root-owned and shadows /usr/bin/shutdown; deleting this repo would leave
it in place, and with the alarm cache gone it falls through to rtcwake +
hibernate -- so "shutdown now" would silently stop being a poweroff, every
day, forever. /etc/sudoers.d/wake-alarm is deliberately NOT removed:
screen-locker's own _wake_alarm.py still needs passwordless rtcwake.

159 tests pass at 100% branch coverage; all 26 pre-commit hooks green.
Verified by running it: _sync --show and _trigger --dry-run both resolve.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:24:02 +02:00
e83ff97f47 Take pylint 4.0.8
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:10:44 +02:00
150a8cd7e5 Require two tags, the walk, and three answers to dismiss
The dismiss gate was an OR — NFC tag *or* QR *or* (25 steps + 2 min) —
followed by one challenge. QR never worked at ring time (no scanner
package, no CAMERA permission, `onQrScanned` had no caller), so the real
bar was "walk 25 steps, wait 2 minutes, answer one question" and the NFC
tag was already fully bypassable.

It is now a strict, latched sequence owned by `DismissGate`:

    tag 1 -> 25 steps + 2 min -> tag 2 -> 3 challenges

Every stage is required, in that order, and a stage once passed never
reverts. That last part also fixes a real bug: `_onNfcTag` and `_trySteps`
both assigned the room-proof result straight onto `_inRoom`, so a wrong
tag tapped after the gate had passed sent the user back to the start.

Two *distinct* tags are required; the same id in both slots is refused at
registration, since one tag satisfying both stages removes the walk that
is the whole point. The existing single-tag registration migrates into
slot 1 rather than being stranded.

Answers are cumulative, not consecutive: a wrong one costs the attempt and
nothing else.

The bypass is the only fallback and is deliberately narrow. After 5 minutes
of ringing, or immediately when NFC is off or fewer than two distinct tags
are registered, the two *tag* stages are skipped and the count rises to 6.
The walk is never skipped — jumping straight to the challenges would let
someone lie in bed for five minutes and answer questions without standing
up, which is weaker than the gate this replaces. Without some such hatch a
dead tag at 06:00 leaves an alarm that cannot be switched off at all.

Also deletes the `flash` challenge outright, along with the now-orphaned
`generateCode`/`kDismissCodeLength`/`_dismissChars`. It was the only kind
that removed its prompt from the screen, which is unsolvable for someone
who has just walked in from another room.

The ring screen takes an injectable clock: `Stopwatch` reads the wall
clock, which `tester.pump()` does not advance, so without that seam no
widget test could reach the two-minute floor or the five-minute bypass.

Verified on the Pixel 6a: the existing tag migrated into slot 1 and both
rows render. 102 Dart tests pass; analyzer clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:09:00 +02:00
af07f52af1 Take coverage 7.16.0
Already red before today's Python work touched the repo; the commit hook had no
reason to look at requirements.txt, so only the CI mirror's whole-tree run saw
it. Bumped across every repo pinning 7.15.4 in the same pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:40:22 +02:00
c1dbdcda22 Grade against 3.14 too, not just run on it
`requires-python` and the CI pin already said 3.14, but ruff, mypy and pylint
were still grading against 3.10/3.11 -- three tools judging an interpreter
nothing runs any more, and ruff withholding the pyupgrade fixes that only
become safe at the newer target. `pin_ci_python.py` rewrites these three knobs.

What the stale target was hiding: `datetime.timezone.utc` where `datetime.UTC`
is now correct (UP017), `socket.timeout` where `TimeoutError` is (UP041), and
ruff's stable formatter applying PEP 758 -- `except (A, B):` becomes
`except A, B:`. That makes the source 3.14-only at the syntax level, which is
what `requires-python = ">=3.14"` already promised; kuhy chose it deliberately
over holding ruff a release back (2026-08-29).

ruff, ruff-format, mypy --strict and pylint all clean at the new target.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:39:33 +02:00
d14ece9129 One Python, always the newest
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 20:06:35 +02:00
28c6b71865 Refresh the gate workflow from the shared template
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 17:14:56 +02:00
932cc68fc5 Raise the Python floor to 3.11, and give the pre-commit workflow the shared gates
Two CI failures, both real, neither visible locally.

**`python-kasa==0.10.2` requires Python >= 3.11** and the test matrix still
ran 3.10, so `pip install -r requirements.txt` could not resolve there. The
floor moves to 3.11 across `requires-python`, mypy and pylint, and the matrix
becomes 3.11/3.12/3.13. Nothing runs 3.10 -- production is system Python 3.14
-- so this documents what was already true rather than dropping support.

**The `pre-commit` workflow never checked out `kuhyx/utils`,** so both
delegating hooks exited 1 with "shared gate not found at
/home/runner/utils/...". That workflow has been red on every run since those
hooks were added; the freshness hook just made it two failures instead of one.
It now checks the shared repo out to `.utils` and points `UTILS_ROOT` at it,
the same way every other workflow in the fleet does.

465 tests at 100% branch coverage in a clean venv; gate exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 15:17:42 +02:00
6b2ede2d03 Pin the CI toolchain to the SDK this repo actually builds with
`.fvmrc` says 3.47.2 and nothing read it: `subosito/flutter-action` takes its
own `flutter-version:`, and the fleet had drifted to 3.44.6, 3.44.8, 3.44.9,
3.47.0 and 3.47.1 with no one tracking it. kuhylog is the proof it matters --
its runner on 3.44.9 predates the `@awaitNotRequired` annotation, so the same
`unawaited(Navigator.push(...))` is a violation on one SDK and required on the
other, and CI went red on a commit that is clean locally.

The freshness gate reads these pins now (utils@98213cb), so this cannot drift
again in silence.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 15:06:11 +02:00
5117f5a0c9 Latest stable dependencies, and the gate that keeps them there
**The two shared Python libraries were four minor versions behind and the gate
could not see it.** They are PEP 508 direct references
(`gatelock @ git+...@gatelock-v0.4.1`), which parsed as unpinned PyPI packages
that do not exist on PyPI -- an undeterminable answer, not a stale one.
utils@7a682a4 teaches the gate that shape; this repo is the first to benefit:
gatelock v0.4.1 -> v0.7.2, crdt-sync v0.5.1 -> v0.9.1. The system install was
already on 0.7.1/0.9.0, so only the manifests were adrift.

Python side: bandit 1.7 -> 1.9.4, mypy 1 -> 2.3.1, pylint 3 -> 4.0.7,
pytest 8 -> 9.1.1, pytest-cov 4 -> 7.1.0, pytest-randomly 3 -> 4.1.0,
ruff 0.8 -> 0.16.5, python-kasa 0.7 -> 0.10.2, and the rest exact-pinned.
Five majors and not one lint or type finding: `scripts/ci_mirror.sh` builds a
clean venv from requirements.txt and runs the whole CI set, 465 tests at 100%
branch coverage.

phone_app takes crdt_sync_dart v0.11.1 and the flutter_secure_storage 11 chain
(compileSdk 37 / AGP 9.3.2 / Gradle 9.7.1). 79 tests green, analyzer clean,
release APK builds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 14:56:16 +02:00
e25bb5a1d7 Remove the push handoff: the gate is green and everything is pushed
Option B was taken. All seven oversized files are split, `pre-commit
--all-files` passes clean, and the 39 commits are on origin/main with no
--no-verify.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:46:24 +02:00
6691bbab79 Apply ruff-format to the split test file
A blank line the formatter wanted gone, left by the test_state.py split.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:45:42 +02:00
801177972b Split _sync.py along the transport/resolution seam item 8 needs
371 -> 168. Token discovery and both backends move to _sync_transport.py;
_sync.py keeps resolution (cache, staleness, fallback), the Alarm dataclass
and the CLI.

The seam is chosen for item 8, not just for line count: that phase adds a
dismissal-record reader, which belongs beside the alarm reader in the
transport rather than inside the resolution chain.

ALARM_CACHE_FILE deliberately stays in _sync. The suite patches
`wake_alarm._sync.ALARM_CACHE_FILE` to keep tests off
~/.config/wake_alarm/alarm_cache.json — the file shutdown-wrapper.sh reads at
poweroff — and moving that binding would silently reconnect the tests to the
real one. That is the failure mode that once wrote 27 fake entries into a
live log while the suite still looked green.

The split broke 31 tests loudly, all of them patch targets that had to follow
the code: the three SYNC_* constants, the two fetchers, the patch.multiple on
the firebase names, and the reload test for the crdt_sync import guard. Every
one is repointed at _sync_transport; none was left silently patching nothing.

Verified after: 465 passed at 100% coverage, `python -m wake_alarm._sync
--show` prints, `--no-cache` still resolves the phone's real alarm through
Firebase, `_trigger --dry-run` prints, and wake_state.json is byte-identical.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:44:24 +02:00
64ee81f077 Split _alarm_view.py: the fan-out proxies move to _view_proxies.py
329 -> 207. The proxies are pure plumbing over already-built widgets —
nothing in them constructs Tk, which is what makes them separable from the
builders that do.

One trap the split surfaced: `tk` had to stay a RUNTIME import in the new
module, not a TYPE_CHECKING one. `tk.TclError` is caught in a suppress()
there, so deferring the import raised NameError the first time a widget call
failed — i.e. exactly the path these proxies exist to swallow. 48 tests
caught it, loudly.

465 passed at 100% coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:37:30 +02:00
7f24ed4fa6 Split _escape_flow.py: the dialog moves out, the policy stays
317 -> 143. EscapeDialog and _FormFields move to _escape_dialog.py; the
policy (whether an escape may be offered, and the budget it spends) stays.

ESCAPE_HISTORY_FILE deliberately stays imported in _escape_flow: conftest
patches `wake_alarm._escape_flow.ESCAPE_HISTORY_FILE` to keep the suite off
the production budget, and moving that binding would silently reconnect the
tests to the real file. EscapeDialog is re-imported for the same reason,
guarded by __all__.

Two things the split broke loudly, both worth noting:
- The test patched `wake_alarm._escape_flow.tk`, which after the move
  intercepted nothing; repointed at _escape_dialog.
- The gatelock imports the dialog needs (escape_text_tab_trap and friends)
  did not come across, and ruff then stripped TYPE_CHECKING before my
  annotation block could use it — so the import and its first usage had to be
  added in the same edit, exactly as the standing rule says.

465 passed at 100% coverage; both documented CLIs still print real output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:34:38 +02:00
1c8a40d410 Split _sinks.py and home_screen.dart under the 250-line gate
_sinks.py 341 -> 249: the pactl *parsing* moves to _sink_parsing.py. That half
is pure text handling with no subprocess and no side effects, so it is
testable without touching the host's audio; _sinks.py keeps command execution
and the activate/restore orchestration.

The parsers are re-imported into _sinks under their original names, guarded by
__all__. The suite patches `wake_alarm._sinks._parse_cards` and friends, and a
moved symbol makes patch() stop intercepting *silently* — the test then
asserts nothing and still passes. Ruff proved the point mid-split: shortening
__all__ let it delete two of the re-exports and broke an import outright.
_parse_profile_line is only imported (never patched), so its test now imports
from the new module instead.

home_screen.dart 270 -> 249. This one was mine — the automatic-alarm change
pushed it over and I claimed in TODO-push-and-gate.md that nothing this
session touched was over the limit; that was wrong. Publishing moves to
AlarmPublisher, which returns a status line instead of calling setState, so it
is testable without a widget. _loadSavedTime became _loadSyncState: it no
longer loads a *time*, because the schedule is baked in and owned by
AlarmPolicy, so a stored value could only disagree with it.

465 Python at 100% coverage, 79 Dart, APK builds, and both documented CLIs
still print real output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:30:02 +02:00
5340cce396 Split test_state.py at the write/read seam
314 lines, over the 250 gate. The UTC day key and the save/load round-trip
stay; the read-side queries (workout skip, and the two "already done today"
gates the trigger consults) move to test_state_queries.py.

Checked the trap this file is shaped for: wake_state.json is real on-disk
state that screen-locker mirrors, so a lost redirect would have the suite
writing to it while still looking green. Its mtime and md5 are unchanged
across the split (Aug 24 07:01, 19bf741a...).

465 passed, 100% coverage, unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:23:07 +02:00
3b2ad70b69 Split test_smart_plug.py at the config/operations seam
351 lines, over the 250 gate. Config loading and connection stay; set_state,
run and the kasa import fallback move to test_smart_plug_ops.py. The whole
preamble is carried, not just the imports — the module-level fixtures live
after them and a header-only copy would error every moved test.

465 passed, 100% coverage, unchanged from before the split.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:22:12 +02:00
605eeb8d28 Add the handoff prompt for pushing the 31 local commits
The push is blocked by the pre-push ci-mirror hook failing the 250-line gate
on seven Python files that were ALREADY over before this session (verified:
the identical set fails at 0e8da72). Nothing this session touched is over —
where a change pushed a file over, it was split in the same change.

--no-verify is banned by git-rules.md and splitting untouched files is banned
by the standing rule that cost a full revert once, so this is a decision for
the user rather than something to route around. The prompt lays out the three
options and the traps that apply to the split path.

Also records what is already verified on hardware so a fresh session does not
redo it, and the three things still genuinely open.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:09:25 +02:00
867ff8da22 Qualify the DND claim: priority DND yes, total silence no
Measured on the Pixel via the muted-stream mask in `dumpsys audio`:
STREAM_ALARM is unmuted under priority DND (zen_mode=1, mask 0x1a6) and
MUTED under total silence (zen_mode=2, mask 0x9be). The verified ring was
priority DND, so "STREAM_ALARM ignores DND" was true but overstated — no
audio flag escapes total silence, and the fix if that gap ever matters is a
zen-policy check at arm time, not an audio change.

Also records that raiseAlarmVolume() genuinely runs on this hardware
(observed raising oldIndex:0 -> 7, no SecurityException), so it recovers a
stream turned down to zero but not one muted by total silence.

Two probe-harness traps kept: --build-number produces a non-running APK, and
the arm probe can register for TOMORROW because main.dart's rearm()
recomputes nextOccurrence after the armed minute has passed.

Folded in from scratch notes left mid-session (.dnd-findings/,
TODO-verify-dnd-ring.md), both now deleted — the verification they asked for
has since been done.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:07:57 +02:00
91e3f30653 Record the automatic alarm verified on the Pixel
Armed itself at 08:00 with zero taps (RTC_WAKEUP, window=0, exact), the
earlier-only ratchet rejected a later time on-device without weakening the
armed alarm, and the daily watchdog is scheduled.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:05:41 +02:00
95be57b575 Make the alarm fully automatic and un-weakenable (08:00, earlier-only)
The alarm was opt-in: it only armed when the user tapped "Set Alarm & Sync to
PC", so it could be defeated by simply not tapping it, or by cancelling it the
night before. It is now automatic and there is no lever a half-asleep user can
pull that buys them sleep.

- AlarmPolicy bakes the schedule in at 08:00 daily. The only edit the UI
  offers is moving the NEXT alarm earlier; setEarlier() refuses anything at or
  after the baseline, and refuses to relax an active override. Earlier-only is
  the whole design: every available change costs the user sleep.
- The ratchet resets after each fire, so an early start is one-shot. A one-way
  ratchet with no reset is a trap, not a defence — the first 05:00 would
  otherwise be permanent with no way back short of reinstalling.
- load() re-validates the stored value and ignores anything at or after the
  baseline. SharedPreferences is not a trust boundary.
- No cancel. The Kotlin handler is deleted, not just the Dart wrapper, so the
  capability genuinely does not exist rather than being one invokeMethod away.
- Arming happens in main()'s init seam and via AlarmWatchdog, a daily
  self-rescheduling check that re-arms if nothing is scheduled — closing the
  gap where a force-stop or a failed re-arm goes unnoticed until the morning
  it does not ring. BootReceiver re-establishes it, since setInexactRepeating
  does not survive a reboot.
- Publishing to the PC is automatic too; it used to need the same tap.

PC half, so the two agree with the network down:
- FALLBACK_ALARM_HOUR 13 -> 8, matching the phone's baseline. At 13:00 a
  Firebase outage silently moved the alarm five hours LATER — the one
  direction the design refuses to allow.
- _trigger._clamp_to_baseline() refuses any resolved alarm later than the
  baseline, whatever its source. Without it the PC would faithfully reproduce
  a stale or tampered remote value and the forbidden direction stays reachable
  through sync.

Tests: 465 Python at 100% branch coverage, 79 Dart. Both ratchet directions
are covered, per the standing rule about monotonic counters. test_sync.py and
test_trigger.py were split (payload, token, CLI, clamp) to stay under the
250-line gate; the split lost indirect coverage of extract_hlc/newest_alarm,
which now have direct tests instead.

`python -m wake_alarm._sync --show` and `_trigger --dry-run` both re-run and
still print real output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 23:03:00 +02:00
f53003ee4d Record the phone alarm verified end to end, by the user, on the Pixel
The dismiss path is no longer "covered by widget tests": the user ran it and
confirmed it. tag discovered: 0465dab3ce2a81 on the ring screen, challenge
solved, alarm silent.

Records the four defects that only a hardware run could have found — the
onPause reader-mode teardown, the cumulative step sensor that could never move
off 0/25, the ON_LOCKED NFC gating, and the self-hiding flash challenge — and
the two things still genuinely unverified: the QR scanner UI (which does not
exist) and the locked-keyguard dismiss (implemented, never run to completion).

Also records the process lesson, because it cost the most time here: after
hardware confirms a path, the next change must be the smallest delta on that
exact state, never a restructure bundled with a fix.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 22:47:20 +02:00
a845cac883 Remove the flash challenge; revert the MethodChannel split that regressed NFC
Two things, one of them an undo of my own change.

The flash challenge is gone from the phone's rotation. It hides the code after
kDismissFlashSeconds, and on the phone that is unsolvable in practice: the ring
screen is reached by walking to another room and tapping a tag, so the code has
already vanished by the time the user is looking at it. Reported from the phone
as "invisible - impossible to actually do". Every challenge the alarm shows now
stays on screen until it is answered, and a test asserts next() never returns
one that hides itself. The constructor stays for the PC half's parity tests;
nothing routes to it.

The two-channel split is reverted. I introduced it to fix a tag reaching Kotlin
but not Dart, and pointed the push channel at the call channel — which broke
NFC *and* the step counter, both of which had been confirmed working on the
phone one build earlier. The user caught it: "they worked previously so your
changes regressed it". The split was a theory that was never shown to be
necessary; the single channel from 08b44b4 is restored unchanged.

Lesson worth keeping: when hardware has just confirmed a path works, the next
change should be the smallest possible delta on top of that exact state, not a
restructure bundled with a fix.

flutter test: 70 pass. dart analyze lib/ test/: clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 22:45:35 +02:00
859e6effbb Record what the Pixel run actually proved, and what it did not
Three claims are now measured rather than assumed: the alarm fires from Doze
on time, wakes the screen over the lockscreen, and rings through DND with
zen_mode=1 (player state:started on USAGE_ALARM/STREAM_ALARM(4)).

The dismiss is still unverified. Three defects were found and fixed during the
attempt, but no fix has been confirmed on hardware — the run ended before a
successful tap. Recorded as unverified rather than implied by the commit that
fixed them.

Also recorded: requestDismissKeyguard raises the PIN prompt rather than
silently unlocking, so a no-touch NFC tap was never achievable on a secured
phone. Better stated now than discovered at 06:00.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 22:23:41 +02:00
08b44b4ca2 Fix three defects the hardware run exposed in the room-proof path
All three were invisible to the emulator (no NFC, no step sensor) and to the
widget tests (which mock the platform channel), and each one on its own made
the alarm harder or impossible to dismiss.

1. AlarmActivity.onPause called NfcReader.stop(). enableReaderMode is
   per-activity but disableReaderMode is effectively global, so anything
   briefly coming in front of the ring screen killed NFC polling for the rest
   of the ring. Measured on the Pixel: `flags: 271` immediately followed by
   `flags: 0`. Teardown moves to onDestroy, and onResume re-asserts.

2. StepCounter could never report progress from a standing start.
   TYPE_STEP_COUNTER is an on-change *cumulative* sensor: it emits nothing
   until the user has already walked, and the first emission was being
   consumed as the baseline — so the ring screen sat at 0/25 no matter how far
   you walked. TYPE_STEP_DETECTOR is now primary (one event per stride, no
   baseline to miss); the counter stays as the fallback for devices without a
   detector.

3. NFC cannot be read while the ring shows over the lockscreen. Measured
   A/B on the Pixel with the same tag: registration while unlocked →
   mScreenState=ON_UNLOCKED, tag discovered; ring screen over the keyguard →
   mScreenState=ON_LOCKED, reader mode accepted (flags 271) but no discovery.
   Android gates NFC polling on lock state. showWhenLocked draws *over* the
   keyguard without unlocking, so the alarm now calls
   requestDismissKeyguard() on fire and re-asserts reader mode from the
   dismiss callback. User's call, taken explicitly: on a secured phone this
   surfaces the PIN prompt, which is an acceptable trade for an alarm you
   must get up for.

Without (3) the only satisfiable proof at 06:00 is steps, which is exactly
the single-mechanism dependency the room-proof redundancy exists to prevent.

flutter test: 69 pass. dart analyze lib/ test/: clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 22:23:23 +02:00
10a594305c Bring the two files this change grew back under the 250-line gate
The gate runs --all-files at push time, so it caught two files this session
pushed over: AGENTS.md (244 -> 330) and home_screen.dart (238 -> 269). Both
are mine; the pre-existing Python overages are untouched, per the standing
rule not to split a file this change does not already have to edit.

- The phone section moves to DOCS-phone-alarm.md, following the repo's own
  pattern (DOCS-architecture.md, DOCS-vmbox.md), leaving a pointer.
- Alarm arming moves out of home_screen.dart into AlarmArming — "what it
  takes to arm an alarm" was never the picker's concern, and the extraction
  also repaired a doc comment my earlier edit had orphaned onto the wrong
  method.

flutter test: 69 pass. dart analyze lib/ test/: clean. APK builds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:43:16 +02:00
026048c7a8 Record NFC registerable, and the two things still unverified on hardware
NFC now works end to end (register in Settings, tap to satisfy), so item 3's
remaining piece is the QR scanner UI alone — the third mechanism, not a
missing one.

Two honest gaps recorded rather than glossed: no real alarm has ever rung on
the Pixel, and the dismiss path has never run on any device because the AVD
has neither a step sensor nor NFC. Widget tests cover it; a real tag tap does
not yet.

Also noted: mute the host before firing a ring on the emulator — it routes
STREAM_ALARM to the PC speakers and raiseAlarmVolume() sets it to max.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:39:22 +02:00
dc2d54668b Phase 4/3: close the ring screen on dismiss, and make NFC registerable
Two defects that each defeated the alarm in a different way:

1. Nothing finished AlarmActivity after a correct answer. Sound stopped and
   the alarm re-armed, but the dismiss screen stayed up over the lockscreen
   forever — back is disabled in both halves by design — and the live instance
   kept _inRoom=true with the solved answer still typed, so the next ring
   could reuse an already-passed gate. AlarmActivity now handles
   closeRingScreen; the shared AlarmChannel deliberately holds
   applicationContext and cannot finish an activity, hence the split handler.

2. Nothing could write roomProof.nfcTagId — there was no registration UI — so
   checkNfc always answered "no tag registered" and checkQr was never called.
   Functionally that left steps as the only satisfiable proof, which is
   exactly the state the decision rules out ("NFC or QR qualifies; steps alone
   does NOT") and removes the redundancy whose purpose is that one failing
   mechanism at 06:00 must never block dismissal. Added RoomProofScreen
   (reader mode from MainActivity, since registration needs an Activity) and
   linked it from Settings.

Also: StepCounter kept one listener instead of registering a fresh one per
ring and never unregistering, and the ring screen drops its NFC handler on
dispose.

New tests cover what had been dead code: a registered tag satisfies the proof
and reveals the challenge, a foreign tag does not, and a correct answer
invokes BOTH dismiss and closeRingScreen. The emulator cannot reach the
dismiss path at all (no step sensor, no NFC), which is why it is covered by
widget tests rather than claimed from the AVD run.

Documented ringNow/main_ring_probe.dart in AGENTS.md as a deliberate manual
test handle, the phone-side equivalent of wake-alarm.service.

flutter test: 69 pass. dart analyze lib/ test/: clean. pre-commit: passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:39:01 +02:00
9980b47cf4 Record the phone alarm done; drop the finished session file
Items 1 and 4 ship and are emulator-verified. Item 3 has NFC and the
steps+elapsed fallback wired into the ring screen; the QR scanner UI is the
remaining piece and is now the top entry under "Remaining".

Records what has NOT been verified rather than letting the deploy stand in for
it: the ring has only ever fired on the API 36 AVD, never on the Pixel, and
never with DND on — which is the one condition the STREAM_ALARM claim rests on.

Four new traps, all of which cost time here: the plan's LogStore.changes does
not exist (so re-arm needs three explicit hooks), the Android SDK was never
missing but merely unexported, a manifest permission is not a granted
permission, and a debug probe with its own UI proves nothing about the route
it was written to test.

TODO-phone-alarm-session.md deleted: its work is done, and a finished task
file must not be left behind.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:30:38 +02:00
cb50e58a56 Phase 4/3: NFC room proof, runtime permissions, non-blocking step reads
Three defects found by reviewing the emulator run, all on the dismiss path:

1. ACTIVITY_RECOGNITION was declared but never requested at runtime (API 29+).
   Denied, TYPE_STEP_COUNTER delivers nothing, so checkSteps() reports "sensor
   unavailable" forever. With steps the only wired proof, that made the alarm
   *undismissable*, not merely degraded. MainActivity now requests it
   alongside POST_NOTIFICATIONS.

2. checkNfc/checkQr were dead code — no reader, no channel method, no
   registration — so steps was the only reachable proof. That inverts the
   decision ("NFC or QR qualifies; steps alone does NOT") and removes exactly
   the redundancy whose purpose is that one failing mechanism at 06:00 must
   never block dismissal. Added NfcReader (hand-written on the existing
   channel, NfcAdapter.enableReaderMode so the tap does not restart the
   activity and reset the challenge) plus RoomProofSettings for the registered
   tag/QR. mobile_scanner stays the droppable extra.

3. StepCounter blocked the platform main thread up to 3s per read, called from
   the MethodChannel handler — jank-to-ANR on the ring screen. Now registers a
   listener and serves the last sample; reads never block.

Also: raiseAlarmVolume() is guarded. setStreamVolume can throw under a zen
rule, and by then startForeground() has already posted — a failed volume bump
must not take the ring down with it.

Verified on the API 36 AVD with the real app widget and route (the earlier
probe rendered its own UI, so it proved the Kotlin path but nothing about
/ring): screen Asleep -> Awake, AlarmActivity top resumed over the lockscreen,
RingScreen showing the room-proof gate. New widget tests cover the /ring route
resolving and the challenge staying gated behind the room proof.

flutter test: 57 pass. dart analyze: clean. Zero Python files touched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:28:24 +02:00
af2a9b416b Phase 4/3: the phone's Dart half — ring screen, challenges, room proofs
Dart side of the alarm (items 1, 4, 3). main.dart had no init seam at all;
it now has ensureInitialized(), a navigatorKey and a /ring route.

- challenge.dart: all five kinds ported from _challenges.py so both halves
  behave identically. kDismissCodeLength/kDismissFlashSeconds are duplicated
  from _constants.py, not synced — noted in the file, since Dart cannot read
  Python.
- alarm_scheduler.dart: the Dart side of the single MethodChannel.
- ring_screen.dart: room proof first, then a challenge, then dismiss. Back is
  a no-op (PopScope) so the alarm cannot be escaped.
- room_proof.dart: NFC or QR satisfies on its own; steps NEVER do alone —
  the phone is stationary while you walk to it, so steps only accrue after
  pickup and can be faked by shaking it in bed. Steps count only together
  with elapsed time, as the fallback when both others fail.
- home_screen: arms the app's own alarm instead of asking the user to confirm
  in the Clock app (item 1's "no user interaction"). SET_ALARM stays as
  redundancy with SKIP_UI=true.

Re-arm has three hooks and needs all three: startup, BOOT_COMPLETED, and
dismiss. The plan assumed LogStore.changes would cover this; that stream does
not exist in crdt_sync_dart (verified — the library has no Stream at all), so
the picker's save is only one hook and a restart would otherwise arm nothing.

Fixed a real gap the API 36 AVD exposed: POST_NOTIFICATIONS was never
requested at runtime, so a fresh install sat at importance=NONE and the
full-screen intent was rejected outright — the alarm would ring with no
dismiss screen. MainActivity now requests it, and canUseFullScreenIntent()
also checks areNotificationsEnabled() so the check gates rather than warns.

Verified on the API 36 AVD: screen Asleep -> Awake, AlarmActivity became the
top resumed activity over the lockscreen, service isForeground=true
types=0x2 (mediaPlayback) category=alarm, no crash. flutter test: 54 pass.
dart analyze: clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:22:07 +02:00
e0cc20664c Phase 4: the phone's Kotlin ring path (item 4)
Hand-written Kotlin behind ONE MethodChannel, never a plugin: AGP 9.0.1 /
Gradle 9.1 / Kotlin 2.3.20 is bleeding edge and a plugin that will not compile
breaks the build outright rather than degrading.

- AlarmScheduler: setAlarmClock() (Doze-exempt, no SCHEDULE_EXACT_ALARM
  prompt), persists the time so boot and dismiss can re-arm.
- AlarmReceiver: hands straight to the service — a receiver gets ~10s and no
  wakelock, so nothing that must outlive it belongs there.
- AlarmService: foreground service, PARTIAL_WAKE_LOCK, USAGE_ALARM
  (= STREAM_ALARM, which is what ignores DND and silent mode), looping
  ringtone, vibration, full-screen intent over the lockscreen.
- AlarmActivity: showWhenLocked + turnScreenOn, routes to the Dart ring
  screen, back is a no-op so the alarm cannot be escaped.
- BootReceiver: re-arms on BOOT_COMPLETED; AlarmManager drops alarms across a
  reboot.
- StepCounter: TYPE_STEP_COUNTER baseline for item 3's fallback proof, also
  hand-written to keep plugin risk off this path.

Details that are a hard crash or a silent no-ring rather than a warning:
FLAG_IMMUTABLE on every PendingIntent (mandatory since API 31);
foregroundServiceType declared on the <service> AND passed to
startForeground(); explicit android:exported on every component;
USE_FULL_SCREEN_INTENT declared (missing from the plan's list) and
canUseFullScreenIntent() exposed so the Dart side can gate rather than warn.

Every permission verified present in android-36's api-versions.xml rather
than from recall. Compiles green with `flutter build apk --debug`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:12:51 +02:00
738027d527 Phase 4 prereq: pin explicit min/target/compile SDK on the phone app
All three were delegated to the Flutter Gradle plugin, so there was no floor
to reason about — and full-screen-intent and foreground-service semantics both
changed at API 34/35, which is exactly the code the alarm path needs.

- compileSdk/targetSdk = 36, matching the target phone.
- minSdk = 28: the floor for android:showWhenLocked / android:turnScreenOn as
  plain manifest attributes (no legacy branch), which also clears
  flutter_secure_storage's API 23 and Flutter's own default of 24.

Verified with `flutter build apk --debug` (exit 0).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:09:56 +02:00
0e8da72b69 Add the handoff prompt for the phone-alarm session
Items 4/3/1 are their own session: new Kotlin on AGP 9 / Gradle 9 / Kotlin
2.3, an emulator that is not installed yet, and physical-device verification
at the end.

Records two prerequisites measured today rather than assumed: the app's
min/target/compileSdk are all still delegated to the Flutter plugin (no floor
to reason about full-screen-intent or foreground-service semantics), and only
/usr/bin/adb is on PATH — emulator, avdmanager and sdkmanager are absent, and
the image needs to be API 36 to match the phone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:03:20 +02:00
c1319231f5 Record item 5 done, and two traps the split cascade cost
Curtains move to Done. Remaining is the phone chunk, then gating, then the
black screen.

Two new traps, both paid for this session:

- Do not split a file the change does not already have to touch. The gate
  fires on staged files, so editing _sync.py just to repoint an import pulled
  its 371 lines in and cascaded into five modules and a broken tree. Put a new
  constant in its single consumer instead.
- Extracting a __main__ CLI silently broke `python -m wake_alarm._sync
  --show`: it printed nothing and exited 0, which every linter and the whole
  suite passed straight over.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:00:30 +02:00
f5eb7fc2bd Phase 7: curtains open on the alarm, no-op until hardware exists (item 5)
_curtains.py: a two-method driver protocol, a registry, and a logging no-op
default. prepare_hardware() calls open_curtains() next to turn_on_plug().

The no-op is not a placeholder awaiting hardware -- it is the correct
behaviour on a machine with no motor. Shipping it now means the call site and
the JSONL event are real, so buying a motor later is a config file rather than
a code change.

Shaped like _smart_plug.py, which solves the same problem: absent or malformed
config means "no curtains" rather than an error, an unknown driver name
degrades with a WARNING, and a driver that throws is caught -- a jammed motor
must never be the reason nobody is woken. The call sits on the startup path,
ahead of the first beep, so an exception escaping it would take the alarm down
entirely.

Why bother at all with no hardware: the audio failsafe silences the alarm at
FAILSAFE_SILENCE_SECONDS, and daylight is the one wake cue that outlives it --
and the only one independent of a sink, a speaker or an HDMI handshake, which
is the exact chain that made this alarm silent in the first place.

DOCS-curtains-hardware.md has the buy list, the three rules a new driver must
follow, and what is deliberately excluded (no cloud, no scheduling of its own,
no close-at-night -- closing belongs to the night lockdown, item 13).

CURTAINS_CONFIG_FILE and CURTAINS_DEFAULT_DRIVER live in _curtains.py rather
than _constants.py, since this is their only consumer -- the same call
_rounds.py and _alarm_session.py already make. That also keeps _constants.py
under the 250-line cap without dragging _sync.py's pre-existing overage into
this commit; splitting _sync.py belongs to the phase that legitimately touches
it (item 8).

465 tests pass, 100% branch coverage. vmbox harness 8/8, exit 0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 21:00:11 +02:00
c43af4edb7 Update the continuation TODO for phases 4-6
Items 6, 2 and 10 move to Done. Remaining is the phone chunk (1/4/3), then
gating (8), then curtains (5) and the black screen (13).

Adds three traps this session paid for: vm run's exit code fails a gate open,
_state.py's UTC key is load-bearing across repos and must not be "fixed", and
ruff's autofix will silently gut a function whose only effect is printing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:49:55 +02:00
97d32c803d Phase 6: vmbox becomes the gate for the system scripts (item 10)
scripts/vmbox/harness.sh provisions a disposable Arch guest, runs the REAL
install.sh in it, and adjudicates 8 cases on a host-side exit code. Plus
DOCS-vmbox.md, which states what a pass does and does not mean.

Covered: system-python imports, timer enabled, wake-alarm.service still
`static` (an [Install] there fires the alarm at *login*), the shutdown wrapper
shadowing /usr/bin/shutdown, the alarm-cache shape jq expects, a trigger tick,
the inhibitor, and the re-fire path. With --window it also opens the real
fullscreen Tk window and screenshots it from the host -- confirmed showing
"WAKE UP!", round 1/4 and a live flash challenge.

Not covered, and said plainly in the doc rather than implied away: audio (the
guest has no pactl/paplay), the phone, GPU and real outputs, and anything
bootloader-related (guest is BIOS, this machine is UEFI).

**The VM earned its place immediately by finding two live bugs that the host
could not reach and the unit suite passed straight through.**

1. The inhibitor claimed a block it did not have. Popen succeeding only means
   the binary launched; logind can still refuse -- the guest's polkit denies a
   non-interactive session outright ("Failed to inhibit: Access denied", exit
   1) while the alarm cheerfully logged the power key as blocked.
   take_power_key_inhibitor() now waits INHIBIT_CONFIRM_SECONDS and confirms
   the child survived, returning None and logging the refusal otherwise.

2. An unsigned session record was written and then rejected on read. With no
   HMAC key on the machine (/etc/gatelock absent, as in the guest),
   verify_entry_hmac returns False for a *missing* key exactly as it does for
   a forgery -- so every session record was unreadable and item 2's power-off
   defence silently did not exist. An entry with no "hmac" field is now
   honoured with a loud warning; a present-but-wrong signature is still
   rejected, since that one really is tampering.

Two harness traps worth recording, both hit while building it:

- `vm run` reports the *VM's* verdict, not the guest command's exit code, so a
  guest script exiting 1 still gives rc=0. A gate built on that fails OPEN.
  guest_cases.sh prints ALL-CASES-PASSED only when every case passed and the
  harness greps for it; verified by breaking a case on purpose and watching
  the gate go red.
- `vm share`/`vm repo` key off the path basename, so REPO_DIR must be absolute
  and symlink-resolved. A relative "scripts/vmbox/../.." makes rsync write
  into /home and fail with permissions errors that look like a guest fault.

Guest checks live in real .py files beside the shell, not heredocs, so they
get linted like everything else -- ruff's autofix gutted an early heredoc
version (stripped the assignments AND the print) exactly as TODO-hardening
warned, and only running it showed the file had stopped producing output.

Also drops three stale fan references the guest install run surfaced:
install.sh still announced "Fans will ramp to 100%" and README.md still
described the fan ramp, three commits after item 14 deleted the feature.

Splits carried: test_inhibit.py -> + test_inhibit_cleanup.py,
test_alarm_session.py -> + test_alarm_session_refire.py.

455 tests pass, 100% branch coverage. Harness: 8/8 cases, exit 0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:49:16 +02:00
e8f50828e6 Phase 5: the power button no longer ends the alarm (item 2)
Two defences, because one press and one held press are different problems.

**Prevention — _inhibit.py.** A logind block-mode inhibitor on
handle-power-key:shutdown:idle, taken while the alarm is audible and released
in on_close(). Confirmed on the host before writing it that
PowerKeyIgnoreInhibited=no is in force, so no logind.conf drop-in is needed --
and none is added: a drop-in changes the machine permanently, an inhibitor is
scoped to the alarm.

Verified live: the inhibitor appears in `systemd-inhibit --list` as
`wake-alarm ... shutdown:idle:handle-power-key ... block` and disappears on
release.

The child runs `sleep 7200`, never `sleep infinity`. An orphaned block-mode
inhibitor would hold the power button down until reboot -- worse than the bug
being fixed -- so it self-terminates, and a stale one is cleared at startup.

That cleanup was wrong on the first attempt and the host run caught it:
`pkill -f "--who=wake-alarm"` matched the *shell that had just typed the
pattern* and killed it, leaving the real inhibitor alive (`killed 0`, one
inhibitor still listed). Substring matching is inherently self-matching. Now
it lists `pgrep -x systemd-inhibit` and confirms each pid via
/proc/<pid>/cmdline. Re-verified: orphan reaped, exactly one live inhibitor,
zero remaining after release.

**Consequence — _alarm_session.py.** The real gap was that nothing on disk
ever said "ringing, not yet dismissed": wake_state.json is written only on
dismissal, so a hard power-off left no trace and the catch-up window closed
while the machine was down. A signed record is now written at fire time, and
_trigger re-fires on one still marked ringing, ignoring the window.

Deliberately no date field. _state.py keys by UTC and
screen_locker/_wake_state.py mirrors that helper to read the very same file
from another repo, so the UTC basis there is load-bearing. The plan's
_today_str() flip is therefore NOT done -- it would have made any dismissal
between 00:00-02:00 local read as yesterday's in screen-locker and silently
lose an earned workout skip. This record carries only an aware fired_at and
compares elapsed time, so the midnight question never arises.

Age-bounded at 5400 s: an alarm that dies before dismissal leaves a record
nothing ever clears, and unbounded this would restart the alarm every minute
forever.

Two bugs the unit tests could not see, both found by running it:

- A future-stamped record returned None, i.e. "not ringing". But a backward
  clock jump is routine on a machine that hibernates nightly (NTP correcting
  after resume), so that failed *open* on exactly the escape it closes: ring
  on a fast clock, clock corrects, power-off works again. Now clamped to zero
  within a 900 s tolerance and logged.
- _alarm.py derived the correlation id from the alarm's *start* instant. On a
  catch-up or re-fire the PC would write wake-...-0735 while the phone wrote
  wake-...-0700 and the two log streams stop joining. Now
  correlation_id_for_today() derives it from the resolved alarm time, which is
  what _correlation.py always specified.

Every trigger test patched should_refire, so _decide against a real record was
untested -- which is why only the manual run found the first one. There is now
an end-to-end test that writes a real session and asserts the decision.

Splits carried: test_trigger.py 294 -> 197 + test_trigger_main.py,
test_alarm_part2.py 266 -> 170 + test_alarm_timers_flash.py. The inhibitor
handle moved into _AlarmHardware, which also settles pylint's attribute count
and puts it beside the other thing on_close() gives back.

No new suppressions: the one inline pylint disable was redundant, since
consider-using-with is already disabled repo-wide in pyproject.toml.

452 tests pass, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:26:37 +02:00
931a4187cb Phase 4: wire sink reactivation into the alarm (finishes item 6)
_reactivate.py shipped in phase 2a with tests but nothing called it, so the
HDMI sink fix was never actually in the alarm's path. WakeAlarm.__init__ now
starts the retry next to _activate_all_outputs(), stopped by the same
_stop_beep event the beep loop watches.

Verified on the host, not just in tests. Starting state was the exact bug:

    alsa_card.pci-0000_01_00.1  Active Profile: off
    sinks: alsa_output.pci-0000_0d_00.6.analog-stereo

After the retry ran, both passes logged:

    2 sink(s) present: alsa_output.pci-0000_01_00.1.hdmi-stereo,
                       alsa_output.pci-0000_0d_00.6.analog-stereo
    default=alsa_output.pci-0000_01_00.1.hdmi-stereo

and the captured card profiles restored cleanly afterwards.

Two wiring details worth keeping:

- _activate_outputs_only() drops what _activate_all_outputs() returns. Only
  the first call sees the user's real audio state; every retry captures the
  alarm's own. Returning one would let a later caller restore the alarm's
  settings as if they were the user's.
- _list_real_sinks_now() re-resolves pactl each pass and reports no sinks
  when it is absent. The retry outlives the startup lookup and runs on a
  thread nobody is watching, where an exception would vanish silently.

_alarm.py was exactly at the 250-line cap, so the flash timers move to
_alarm_flash.py as a mixin, mirroring AlarmTimersMixin. AlarmTimersMixin's
abstract _start_flash_countdown stub had to go: it is first in the MRO and
would shadow the real implementation. main() stays in _alarm.py --
morning_routine/_orchestrator.py:39 hardcodes that path.

conftest stubs the reactivation autouse; without it every WakeAlarm test
would reshape the host's audio routing.

409 tests pass, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:14:00 +02:00
82abbefa01 Add the continuation prompt for the remaining hardening phases
The PC shut down mid-session. This is the entry point for picking the work
back up without the transcript: what is done, what is left in what order, the
decisions already settled, and the traps that actually cost time.

Points at ~/.claude/plans/wake-alarm-still-does-witty-toucan.md for detail
rather than duplicating it, so the two cannot drift apart.

Every factual claim in it was re-checked against the tree, not written from
memory -- including the one that matters most: _reactivate.py is finished and
tested but is called by NOTHING (it appears only in a _startup.py docstring),
so item 6 is not actually fixed at runtime yet. That is step 1 for the next
session.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:05:14 +02:00
b3e8c237af Phase 3b: finish item 14 -- delete the fan script, clean up installed state
Completes the fan removal started in 9e0cd12, which took the Python out but
left the shell side behind.

- Delete wake-alarm-fans.sh.
- install.sh step 7 now REMOVES the retired script instead of installing it.
  An upgrade has to actively clean up: a machine that ran the old installer
  keeps a passwordless-root sudoers entry for a script that no longer exists,
  which is worse than the fan ramp ever was.

Verified on this machine rather than assumed -- both stale artifacts really
were present:

    /usr/local/bin/wake-alarm-fans.sh                        (existed)
    kuhy ALL=(root) NOPASSWD: /usr/local/bin/wake-alarm-fans.sh   (granted)

After the cleanup: script gone, /run state gone, the fan NOPASSWD line gone,
`visudo -c` parses, `sudo -n true` still works, and the rtcwake NOPASSWD entry
the alarm actually needs is untouched. The sed was rehearsed against a fake
sudoers file first, since getting it wrong locks the user out of sudo.

- AGENTS.md: drop the stale "ramps fans to 100%" description, and point the
  module map at the new DOCS-architecture.md (moved there to keep AGENTS.md
  under the 250-line cap).
- DOCS-architecture.md: where each behaviour now lives after the split, the
  HDMI-silence root cause, and the two timing invariants that must not
  collide -- both of which silently gut the alarm if broken.

404 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:04:01 +02:00
9e0cd123ff Phase 3: remove the max-fan ramp, split _alarm.py, wire the new modules
Item 14: the fan ramp is gone entirely. It caused anxiety without helping
anyone wake up. Deletes _max_fans/_restore_fans/_find_fan_hwmon, the
_AlarmHardware.fan_state field, both call sites, and their tests.
wake-alarm-fans.sh and its NOPASSWD sudoers entry come out in the install.sh
pass -- dropping a passwordless root helper is a bonus.

_alarm.py was 478 lines and the 250-line gate fires on any commit that stages
it, so this carries the split it has owed for a while. New modules, each a
real seam rather than an arbitrary cut:

  _gating          should-it-run-today + CLI (no time gate; that is _trigger's)
  _beep_loop       the sounding thread, now driving _escalation's planner
  _alarm_timers    self-rescheduling challenge refresh / skip window (mixin)
  _alarm_state     the progress + hardware dataclasses
  _rounds          challenge presentation, re-exporting the view helpers
  _countdown       skip-window arithmetic and demo/production intervals
  _dismiss_view    the post-dismissal banner
  _screen_flash    the ~1.3 Hz attention flash (kept under the 3 Hz threshold)
  _lock_setup      gatelock config + arbiter claim
  _startup         wake display, brightness, plug
  _tone            tone synthesis and cache (out of _audio)
  _brightness      xrandr brightness (was in _audio, never belonged there)

main() deliberately stays in _alarm.py: morning_routine/_orchestrator.py:39
hardcodes "wake_alarm._alarm", and moving it is the exact mistake that caused
a month-long silent production failure once already. Verified after the split
that the module still resolves and accepts --production.

Also fixes the plug pre-roll found while researching speakers: main() fired
turn_on_plug() and the first beep in the same instant, so an amplifier's
soft-start relay swallowed the opening of the alarm. PLUG_PREROLL_SECONDS=4
now sits between them.

Two bugs found by running the code rather than by lint:
- ruff stripped `struct` from the extracted _tone.py because the import
  landed before its first usage; only executing it caught the NameError.
- test fixtures patched _play_on_all_sinks/_set_max_brightness at
  wake_alarm._alarm, which silently stopped intercepting once those moved.

404 tests, 100% branch coverage, no new noqa/type-ignore suppressions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-26 23:46:10 +02:00
aa01e0e3e6 Phase 2b: add the 5-minute audio failsafe, and retune escalation to fit it
The failsafe silences AUDIO ONLY at 300 s. The lock, the typed challenge and
the workout gate all persist, so waiting it out in bed is not an escape --
it only stops a ring nobody is present to dismiss from sounding forever.

Adding it exposed two collisions that would each have quietly defeated the
alarm:

1. The escalation ladder ended outside the audible window. PHASE_SOFT_END
   was 5 minutes and PHASE_MEDIUM_END 15, so with the failsafe at 5 minutes
   the alarm was silenced before it ever left its SOFTEST rung -- the medium
   and loud phases became unreachable code. Printed timeline before the fix:

       0s soft 440Hz ... 299s soft 440Hz | 300s failsafe-silent

   Phases are now 1 and 2 minutes, so the alarm spends 3 of its 5 audible
   minutes on the loud alternating rung, which is what makes lying in bed
   for five minutes unattractive.

2. ESCAPE_OFFER_AFTER_SECONDS was also 300, so the escape hatch appeared in
   the same instant the sound stopped -- at its most tempting, precisely when
   the alarm had just stopped being annoying. Moved to 900.

Both invariants are now locked in by tests, so retuning one constant without
the other fails instead of silently degrading the alarm.

Also fixes a latent test bug this surfaced: TestBeepLoopPhases anchored
elapsed time to "one minute past the previous boundary", so a phase retune
made it miss its rung, never set _stop_beep, and spin forever calling the
REAL audio stack -- hanging the whole suite rather than failing. It now uses
the midpoint of the band and patches every rung, so a mistuned boundary fails
fast.

test_alarm_part3.py split (372 -> 195) for the 250-line gate.

413 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-26 23:17:41 +02:00
eeb567ccce Phase 2a: retry card-profile activation so the HDMI sink can appear
Root cause of the silent-alarm-on-HDMI bug, measured on the host rather than
inferred:

    $ pactl list cards | grep 'alsa_card.pci-0000_01_00.1' -A1
    Active Profile: off
    $ pactl list short sinks
    61  alsa_output.pci-0000_0d_00.6.analog-stereo   IDLE

While that card's profile is "off" the G27Q's HDMI sink does not exist, so
_list_real_sinks() cannot return it. _play_on_all_sinks re-enumerates sinks
every beep cycle -- its docstring says it picks up late outputs "without
re-running activation" -- but that can never find a sink whose card is off.
There is nothing to enumerate.

Activation runs exactly once, at startup. At wake time the monitor has not
finished its HDMI handshake, the profile reads "available: no",
_parse_profile_line drops it, and the card is never revisited. Silent alarm.

_reactivate re-runs activation on a decaying schedule (3,5,7,10,15,20,30s)
on a daemon thread, logging the full enumerated sink list every pass so the
next failure is diagnosable from the JSONL log instead of guessed at.

Verified end to end on this machine:
  BEFORE: ['alsa_output.pci-0000_0d_00.6.analog-stereo']
  AFTER : ['alsa_output.pci-0000_01_00.1.hdmi-stereo',
           'alsa_output.pci-0000_0d_00.6.analog-stereo']
and a 1 kHz tone plays through the HDMI sink (paplay exit 0). Note the
constant ALARM_AUDIO_SINK was correct all along; only the activation was
failing.

Wiring into WakeAlarm lands with the _alarm.py split, since touching that
478-line file trips the 250-line gate.

399 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-26 23:02:52 +02:00
f5cfc3e452 Phase 1: structured JSONL logging with cross-process dedupe
Adds the diagnostic substrate the rest of the hardening work builds on. A
6am failure should be reconstructable afterwards instead of re-debugged.

Two sinks, deliberately. stderr -> journal is unchanged. Alongside it, one
JSON object per line in ~/.local/state/wake_alarm/events.jsonl, so a morning
can be replayed with jq.

The hard constraint is that _trigger is a fresh process every 60 seconds, so
an in-memory rate limiter would reset on every tick and suppress nothing.
_log_dedupe therefore persists the last emitted fingerprint to disk and
flushes a suppressed_repeats count onto the next distinct record. Verified
across separate processes: 4 invocations logging the same routine event
produce 1 record plus an accurate count of 3.

That is what satisfies the standing "do not raise the level of _sync's
degraded-read paths" rule by construction, rather than by keeping levels
artificially low and losing the signal.

The correlation id is derived, never generated: both halves compute
wake-YYYYMMDD-HHMM from the resolved alarm instant, so the PC and the phone
agree with no handshake and no uuid exchange -- which matters precisely when
sync is down.

Logging never raises. An unwritable sink degrades to journal-only.

_alarm.py and _sync.py keep the default component= for now; tagging them
means splitting them for the 250-line gate, which belongs in the phases that
actually restructure those files.

389 tests pass, 100% branch coverage held.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-26 23:00:08 +02:00
4286fcb019 Phase 0: fix dependency pin mismatch, stale docs, add speaker research
Groundwork for the alarm-hardening work. No behaviour change.

- .pre-commit-config.yaml pinned gatelock-v0.4.0 while pyproject.toml and
  requirements.txt pinned v0.4.1, so pylint type-checked against a different
  gatelock than production runs. All three now agree on v0.4.1.
- AGENTS.md claimed ALARM_DAYS is "Mon, Fri, Sat, Sun"; _constants.py:9 is
  frozenset({0..6}), i.e. every day. Corrected.
- Complete the CLAUDE.md -> AGENTS.md symlink migration that was left
  uncommitted in the working tree.
- DOCS-speaker-recommendation.md: item 7 of the hardening work. Prose only.
  Researched from official manuals/vendor FAQs. The deciding spec turns out
  to be the power switch, not the LED: _alarm.py already cuts plug mains on
  every exit path, so a speaker needs a latching mechanical switch to come
  back without a button press. Anything shipping a remote has a standby
  microcontroller that a mains cycle cannot clear (confirmed by Edifier's own
  support article), which disqualifies it.
- Drop the stale "TODO: Specify your own unique Application ID" template
  comment; applicationId has been set to com.kuhy.wake_alarm_sync all along.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-26 22:53:01 +02:00
9379f14779 Add the removal marker to every TODO file
The rename commit staged the git mv but not the accompanying content
edit, so these TODO files landed without the "REMOVE ME AFTER FINISH"
line the md-naming gate requires. Repos whose hook was already live
refused that commit; repos without it accepted a file the gate would
now reject.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A47aX5DJwmA3QFn3pkEWi7
2026-08-24 15:56:24 +02:00
21a989ce21 Adopt the four markdown namespaces and gate them
Renames this repo's markdown onto README.md / CLAUDE*.md / DOCS*.md /
TODO*.md so a future session can tell a live task from a finished
record without reading the file to find out.

TODO files carry the literal "REMOVE ME AFTER FINISH" and are deleted
when the work lands. Enforced by the md-naming pre-commit hook and CI
workflow, both delegating to the shared gate in kuhyx/utils so this
repo's idea of a valid name cannot drift from every other repo's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A47aX5DJwmA3QFn3pkEWi7
2026-08-24 15:53:51 +02:00
0c348a5ee9 Add dopamine-ux session prompt to prompts/
Copy of the canonical prompt in ~/utils/dopamine-ux/, distributed here so the
repo can be opened and the prompt run directly. Derived from a survey of this
repo plus "The Dopamine Architecture" (london-post.co.uk).

Each prompt states its own completion protocol: when finished, the session
deletes this copy in the implementation commit and logs a DONE row in
~/utils/dopamine-ux/00-INDEX.md. Partial completion is never recorded as done.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FdApz7EZ1zDfvtvvi1idDv
2026-08-16 21:12:52 +02:00
b9abbf7043 phone_app: use the shared github_device_auth package
The inline `_DeviceCodeDialog` (86 lines) was byte-for-byte identical to
diet-guard's, and `services/github_device_auth.dart` was a fourth copy of
the auth client. Both now come from `github_device_auth` in the
kuhyx/utils monorepo.

This app's client was not merely a drifted copy -- it carried a fix the
other three lacked: `pollForToken` swallowed a transient socket failure and
kept polling, because GitHub can close the connection at the exact moment
the user authorizes. Extracting todo's version would have silently deleted
that. The package took this behaviour instead, so the fix now protects all
four apps rather than just this one.

It is expressed as `on http.ClientException` rather than the local
`SocketException` arm, because the package is also imported by
diet-guard's **web** build where `dart:io` will not compile. Verified that
nothing is lost: package:http wraps a dead socket as
`_ClientSocketException`, which implements both types.

19 tests pass, analyze clean, and the release APK is installed on the
phone and launching.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U4Rj3s7K2qzrLNgJqqPhno
2026-08-15 16:16:17 +02:00
59cc9bffef Update refactor_claude_todo.md counts after gate exemption fixes
Git-ignored files, vendored agent-skill bundles and the CI checkout dir are
now exempt, since no commit could ever fix them. Repo counts and the ranked
violation lists are regenerated accordingly; the global baseline drops from
657 to 597.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 16:03:01 +02:00
be8d1d8f1f Add refactor_claude_todo.md: 250-line file-length cap
A ready-to-use prompt describing the goal (every file at most 250 lines,
code and prose alike), this repo's actual violations ranked by Fowler ROI
(lines x commits/yr), how to split each kind, and the requirement to wire in
the shared pre-commit gate so files stay small permanently.

Generated from a measured survey of every repo; the gate itself lives in
~/utils (file_length/ + scripts/check_file_length.sh).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 14:25:41 +02:00
90a7dafb48 phone_app: migrate Sync settings to the shared sync_settings_ui package
Settings screen becomes a thin dispatcher with two links: "Sync settings"
(the shared sync_settings_ui package, Firebase-only) and "Advanced sync
(GitHub)" (app-local, moved verbatim -- the shared package carries no
GitHub surface).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-14 11:29:32 +02:00
37a7829757 phone_app: add Google sign-in support for the Firebase sync account
Same pattern as todo, diet_guard_app, and workout_app: openFirebaseWithGoogle()
(google_platform.dart abstracts the plugin's platform-channel dependence),
isFirebaseConfigured() reading the stored session rather than the account
marker alone, and the settings screen offering "Sign in with Google" ahead
of the password form.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-14 11:26:33 +02:00
b1762fad29 Bump gatelock to v0.4.1: keep the dismiss box focused after a monitor blip
The dismiss-code entry rendered normally every alarm morning but accepted
no keystrokes, tracking exactly with HDMI-0's recorded dark/recover blips
near 07:00 and 07:55 each day in the journal. Root cause was upstream in
gatelock: LockWindow only focuses the entry once, on first grab
acquisition, so a surface rebuilt after an output recovers gets a widget
nothing ever re-focuses -- fixed in gatelock-v0.4.1
(kuhyx/utils@92f55ce).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NGAEbavLSCAotBqhVfFhPc
2026-08-12 22:17:31 +02:00
6ae5805610 Derive versionCode from the commit count, not github.run_number
run_number counts workflow RUNS, not code. Two failure modes, one of which
already bit: it resets to 1 if this file is renamed (the existing NOTE warned
about that), and it can fall BEHIND a build produced outside this workflow.
On 2026-08-09 diet-guard's phone held a manually sideloaded vc 8 while CI's
next build was vc 6, so `adb install -r` refused every CI build with
INSTALL_FAILED_VERSION_DOWNGRADE. The only non-destructive escape was
re-running the workflow until the counter passed 8 -- forcing a downgrade
needs an uninstall, which wipes app data.

`git rev-list --count HEAD` only ever increases, tracks the code rather than
the CI file, and is already far ahead of every installed build (diet-guard
62 vs 9, screen-locker 118 vs 5, wake-alarm 41 vs 5, todo 51).

Needs fetch-depth: 0 -- checkout@v4 is shallow by default and would count 1.
Verified the count is identical from the repo root and from app/, so the
job's `working-directory: app` default does not affect it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GZH89WEqAjuJT8WZdqc7AP
2026-08-09 18:15:34 +02:00
03392e7ea5 Discover alarm device directories instead of reading a fixed phone path
The PC read one hardcoded path, wake-alarm-sync/devices/phone/alarm.json,
and never parsed the HLC. The phone's device id is migrating from the fixed
constant "phone" to a per-install uuid (a role constant collides as soon as
a second install takes the same role, and a reinstall inherits the previous
install's CRDT identity). A reader pinned to the old path would have stopped
seeing the alarm the moment the phone migrated, fallen through to the cache
and then to FALLBACK_ALARM_HOUR -- i.e. woken at the wrong time, silently.

So the PC half ships first, and this commit is that half plus the phone
change it makes safe:

- _fetch_firebase_alarm() lists SYNC_DEVICES_PREFIX, reads every device's
  alarm.json, and picks the newest by the hour field's HLC rather than by
  listing order. device_id breaks an exact tie so two devices stamped in the
  same millisecond don't alternate between ticks; a device whose payload
  doesn't parse is skipped rather than allowed to win with a bad value.
- SYNC_ALARM_PATH stays as a last-resort read for a backend that lists
  nothing, so an un-migrated install keeps working. The GitHub mirror still
  reads the single fixed path.
- The phone persists a uuid under SharedPreferences 'crdt.nodeId' (the key
  todo and home_inventory already use) and pushes under it. deviceId is now
  an instance field, injectable so tests don't touch real prefs.

Parsing and ranking moved to _alarm_payload.py: _sync.py was over the repo's
500-line cap, and the wire format deserves testing without network or disk --
a misparse here doesn't raise, it just resolves to the wrong wake-up time.

Verified against the live RTDB, not just mocks: seeded a uuid-named device
directory and confirmed the reader discovered it, read it and ranked it --
losing to the phone with an old stamp, winning with a new one (03:15 vs the
real 07:45). Test device deleted; --show returns 07:45 and the cache is
intact.

354 tests, 100% branch coverage. Phone app: 10 tests, analyzer clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GZH89WEqAjuJT8WZdqc7AP
2026-08-09 17:06:43 +02:00
402 changed files with 35404 additions and 9012 deletions

3
.fvmrc Normal file
View File

@ -0,0 +1,3 @@
{
"flutter": "3.47.9"
}

View File

@ -0,0 +1,62 @@
name: dependency freshness
# Every dependency on its ecosystem's newest STABLE release, enforced on push
# as well as at commit time. The local pre-commit hook only sees the manifests
# in a commit and can be skipped entirely by a fresh clone that never ran
# `pre-commit install`; this runs `--all` over the whole repo.
#
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
# passes, because `--no-verify` is banned locally and a hook that hard-failed
# on a flaky connection would leave no way to commit. A runner is always
# online, so here an undeterminable answer is a real failure.
#
# Expect this to go red for reasons this repo's commit did not cause: an
# upstream release overnight is enough. That is the chosen behaviour -- the
# alternative is a gate that only notices staleness when someone remembers to
# look.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
dependency-freshness:
name: dependencies on newest stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate lives in the shared utils repo so every repo resolves the
# same "latest stable" the same way. Checking it out beats vendoring a
# copy, which is exactly how a gate and its survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
# "3.x", never a pinned minor: the Python target IS the interpreter the
# gate runs under (registries/toolchain.python_installed), so a runner
# held a release behind this machine reports a repo's `requires-python`
# as excluding "latest" while the same check passes locally. flax-docs-mcp
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Install the gate's two runtime dependencies
run: python -m pip install --upgrade pyyaml packaging
- name: Cache registry lookups
uses: actions/cache@v4
with:
path: ~/.cache/dep-freshness
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
restore-keys: dep-freshness-
- name: Every dependency is on newest stable
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict

38
.github/workflows/md-naming.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: md-naming
# The four markdown namespaces, enforced on push as well as at commit time.
# The local pre-commit hook can be skipped (a fresh clone that never ran
# `pre-commit install` has no hooks at all), so the convention needs a second
# gate that no one can forget to install.
#
# Deliberately a SEPARATE workflow from any release job: a badly named doc
# should fail lint, not block publishing an artifact.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
md-naming:
name: markdown naming convention
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same namespaces. Checking it out beats vendoring a
# copy here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the naming convention
run: bash .utils/scripts/check_md_naming.sh --all
# Warns only: no machine can prove a task is finished, so an old TODO
# gets a nudge, never a failure.
- name: Warn about stale TODOs
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py

View File

@ -7,13 +7,65 @@ on:
branches: [main]
jobs:
# mypy and pylint check the whole repo and are the two slowest hooks, so
# each gets its own runner and the other hooks share a third; the workflow
# takes as long as the slowest group rather than the sum.
pre-commit:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
# free-days-interop needs Flutter and the freedays venv; it runs as
# its own job in python-tests.yml, so skipping it here is not
# fail-open.
- group: rest
hooks: ""
skip: mypy,pylint,free-days-interop
name: pre-commit (${{ matrix.group }})
steps:
- uses: actions/checkout@v4
# Two hooks here delegate to the shared gates in kuhyx/utils. Without
# this checkout they exit 1 with "shared gate not found at
# /home/runner/utils/..." -- which is what this workflow had been doing
# on every run since those hooks were added.
- name: Check out the shared gates
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Point the delegates at that checkout
run: echo "UTILS_ROOT=$GITHUB_WORKSPACE/.utils" >> "$GITHUB_ENV"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: pip install -r requirements.txt
- uses: pre-commit/action@v3.0.1
python-version: "3.x"
- uses: astral-sh/setup-uv@v10.2.0
# Every hook brings its own environment except the language: system
# ones; of those only dependency-freshness imports third-party code
# (pyyaml, packaging). The whole requirements.txt used to be installed
# here for nothing -- 28 s of a 60 s run.
- name: Install pre-commit and the system hooks' imports
run: uv pip install --system pre-commit pyyaml packaging
# One cache per group: a shared key would hold whichever group saved
# first, and the others would rebuild their hook envs on every run. The
# restore key lets a config change reuse every env whose rev it kept.
- uses: actions/cache@v4
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ matrix.group }}-${{ env.pythonLocation }}-${{ hashFiles('.pre-commit-config.yaml') }}
restore-keys: pre-commit-${{ matrix.group }}-${{ env.pythonLocation }}-
- name: pre-commit run (${{ matrix.group }})
env:
SKIP: ${{ matrix.skip }}
run: pre-commit run ${{ matrix.hooks }} --all-files --show-diff-on-failure --color=always

View File

@ -9,20 +9,70 @@ on:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
python-version: "3.x"
# uv with a cached wheel store (and cached builds of the three
# git+ kuhyx/utils packages) installs requirements.txt in seconds;
# plain pip took 22 s of a 32 s job.
- uses: astral-sh/setup-uv@v10.2.0
with:
enable-cache: true
cache-dependency-glob: requirements.txt
- name: Install dependencies
run: pip install -r requirements.txt
run: uv pip install --system -r requirements.txt
# No -n auto: the whole suite runs in ~0.5 s, and under pytest-xdist it
# measured ~1.2 s locally (worker start-up outweighs the parallelism).
# Coverage and its 100% bar come from pyproject.toml's addopts.
- name: Run tests with coverage
run: python -m pytest -v
run: python -m pytest -q -p no:sugar
# The Dart free-day rules are a port of ~/src/utils/freedays. This is the
# cross-language gate (scripts/free_days_interop/check.sh): it needs both
# Flutter and the Python package, which the pre-commit job does not have,
# so it runs here and the pre-commit job SKIPs that one hook.
free-days-interop:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check out the Python side of the pool
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- uses: actions/setup-python@v5
with:
python-version: "3.x"
# This job is the workflow's critical path (the Flutter SDK restore and
# the Dart test are its floor); uv builds the venv in a couple of
# seconds where venv + pip took 12 s.
- uses: astral-sh/setup-uv@v10.2.0
with:
enable-cache: true
cache-dependency-glob: |
.utils/crdt-sync/pyproject.toml
.utils/freedays/pyproject.toml
- name: Install freedays into its own venv
run: |
uv venv --python "$pythonLocation/bin/python" .freedays-venv
uv pip install --quiet --python .freedays-venv/bin/python .utils/crdt-sync
uv pip install --quiet --python .freedays-venv/bin/python --no-deps .utils/freedays
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1
with:
flutter-version: 3.47.9
working-directory: phone_app
- name: Dart writes, Python replays, both must agree
run: FREEDAYS_PYTHON="$PWD/.freedays-venv/bin/python" bash scripts/free_days_interop/check.sh

View File

@ -3,6 +3,14 @@ name: release-apk
on:
push:
branches: [main]
# A publisher, not a gate: build only when something that ends up in
# the APK changed. versionCode is the commit count, so skipped pushes
# still leave it monotonic.
paths:
- 'phone_app/**'
- '.fvmrc'
- '.versioncode-offset'
- '.github/workflows/release-apk.yml'
# Lets a release be rebuilt from the current main without a dummy commit.
workflow_dispatch:
@ -15,9 +23,13 @@ concurrency:
group: release-apk-${{ github.ref }}
cancel-in-progress: false
# NOTE: versionCode is github.run_number, which is per-workflow-FILE. Never
# rename or replace this file — the counter resets to 1, versionCode goes
# backwards, and Android silently refuses every future update.
# NOTE: versionCode is the commit count (`git rev-list --count HEAD`), which
# only ever increases and tracks the code rather than the CI file. It replaced
# github.run_number on 2026-08-09: run_number counts workflow RUNS, so it
# resets to 1 if this file is renamed AND it can fall behind a build made
# outside this workflow — which happened, leaving CI unable to install over a
# manually sideloaded APK (INSTALL_FAILED_VERSION_DOWNGRADE). The checkout
# below therefore needs fetch-depth: 0; a shallow clone counts 1 commit.
#
# This job is NOT gated on a test suite: this repo has no Flutter analyze/test
# job to depend on, so a broken commit still publishes. The build failing is
@ -31,15 +43,51 @@ jobs:
working-directory: phone_app
steps:
- uses: actions/checkout@v4
with:
# versionCode is the commit count; a shallow clone would report 1.
fetch-depth: 0
# `.versioncode-offset` is the recovery valve for a phone stranded
# above CI by a hand-numbered local build. Android only ever compares
# versionCode upward, so a device ahead of CI locks CI out permanently
# and the only other escape is an uninstall, which wipes app data.
# ~/.claude/scripts/lib/phone_deploy_version.sh reads the SAME file, so
# raising it moves both sides together; raising either alone re-strands
# the device. Never lower it.
- name: Derive versionCode from the commit count plus the offset
id: vc
# working-directory overrides the job default of phone_app. The offset
# file lives at the REPO ROOT, and reading it from the app subdirectory
# silently finds nothing and yields 0 -- git rev-list still works there
# because git searches upward, so the step goes green with the wrong
# number. That exact mistake shipped versionCode 108 instead of 209 on
# 2026-08-31; it is also the failure phone_deploy_version.sh warns
# about on its own side.
working-directory: ${{ github.workspace }}
run: |
offset=0
if [[ -r .versioncode-offset ]]; then
read -r offset < .versioncode-offset
fi
[[ "$offset" =~ ^[0-9]+$ ]] || offset=0
# Fail loudly rather than mint a too-low code: a silent 0 here is
# what leaves the phone unreachable by CI.
if [[ -r .versioncode-offset && "$offset" == 0 ]]; then
echo "::error::.versioncode-offset exists but parsed as 0" >&2
exit 1
fi
echo "code=$(( $(git rev-list --count HEAD) + offset ))" >> "$GITHUB_OUTPUT"
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "17"
# ~/.gradle caches + wrapper, keyed on the Gradle files.
cache: gradle
- uses: subosito/flutter-action@v2
with:
flutter-version: 3.44.8
flutter-version: 3.47.9
channel: stable
cache: true
@ -87,7 +135,7 @@ jobs:
run: |
flutter build apk --release \
--build-name="${{ steps.ver.outputs.semver }}" \
--build-number="${{ github.run_number }}"
--build-number="${{ steps.vc.outputs.code }}"
# Fail closed. `findByName("release") ?: debug` silently falls back to
# the debug key if key.properties is misplaced, producing a green build
@ -115,7 +163,7 @@ jobs:
id: art
run: |
set -euo pipefail
out="wake-alarm-${{ steps.ver.outputs.semver }}-build.${{ github.run_number }}.apk"
out="wake-alarm-${{ steps.ver.outputs.semver }}-build.${{ steps.vc.outputs.code }}.apk"
cp build/app/outputs/flutter-apk/app-release.apk "$out"
echo "path=$out" >> "$GITHUB_OUTPUT"
@ -124,12 +172,12 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
tag="v${{ steps.ver.outputs.semver }}-build.${{ github.run_number }}"
tag="v${{ steps.ver.outputs.semver }}-build.${{ steps.vc.outputs.code }}"
gh release create "$tag" "${{ steps.art.outputs.path }}" \
--prerelease \
--target "${{ github.sha }}" \
--title "$tag" \
--notes "Automated build of ${{ github.sha }} (versionCode ${{ github.run_number }})."
--notes "Automated build of ${{ github.sha }} (versionCode ${{ steps.vc.outputs.code }})."
# Cut a clean vX.Y.Z the first time a pubspec version is seen. A failing
# `gh release view` is the "not published yet" signal, which also covers
@ -149,4 +197,4 @@ jobs:
gh release create "$tag" "${{ steps.art.outputs.path }}" \
--target "${{ github.sha }}" \
--title "$tag" \
--notes "Release $tag (versionCode ${{ github.run_number }})."
--notes "Release $tag (versionCode ${{ steps.vc.outputs.code }})."

25
.github/workflows/repo-contract.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: repo-contract
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
# contract is enforced on push too. Mirrors md-naming.yml.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
repo-contract:
name: repo contract
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the repo contract
run: bash .utils/scripts/check_repo_contract.sh

3
.gitignore vendored
View File

@ -21,3 +21,6 @@ wake_alarm/wake_state.json
# ci_mirror.sh cached requirements.txt venv (rebuilt on demand)
.ci-mirror-venv/
# FVM Version Cache
.fvm/

View File

@ -8,6 +8,7 @@ default_language_version:
default_stages: [pre-commit]
fail_fast: false
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
@ -32,6 +33,12 @@ repos:
- repo: local
hooks:
- id: repo-contract
name: repo contract (CLAUDE.md Commands + test_changed)
entry: scripts/check_repo_contract.sh
language: system
pass_filenames: false
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
- id: no-noqa
name: Block noqa comments
entry: '(?i)#\s*(noqa|type:\s*ignore)'
@ -95,8 +102,14 @@ repos:
- --jobs=4
additional_dependencies:
- pytest
- python-kasa
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
# Kept in step with pyproject.toml: pip refuses two different
# direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.4.0#subdirectory=sickdays
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
@ -123,7 +136,7 @@ repos:
pass_filenames: false
always_run: true
require_serial: true
stages: [pre-push]
stages: [manual]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
@ -134,20 +147,101 @@ repos:
- repo: local
hooks:
# Fails a commit that still points crdt_sync at a local path. Local
# tests would go green against a library CI has never seen, silently.
- id: crdt-sync-override
name: no local crdt_sync dependency_override
entry: bash scripts/check_no_crdt_sync_override.sh phone_app/pubspec.yaml
language: system
pass_filenames: false
always_run: true
# The Dart free-day rules are a port of ~/src/utils/freedays; this replays
# one edit sequence through both and fails on any semantic disagreement.
# Only fires when either implementation's inputs change.
- id: free-days-interop
name: free-day rules agree with the Python package
entry: scripts/free_days_interop/check.sh
language: system
pass_filenames: false
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
- id: shellcheck
name: shellcheck
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
language: system
types: [shell]
- id: screens-fit
name: Every lock screen fits 1366x768 (no scrolling required)
entry: python3 -m scripts.verify_screen_fits
# The shared 250-line cap. This repo used to run a local script with a
# higher limit under this same hook id, so it looked gated while letting
# through files every other repo rejects.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system
files: '^wake_alarm/.*\.py$'
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
# Shared gate in ~/src/utils owns the namespaces and the exemption list, so
# one repo's idea of a valid name cannot drift from every other repo's.
- id: md-naming
name: markdown naming convention
entry: scripts/check_md_naming.sh
language: system
files: \.(md|markdown)$
- id: todo-closer
name: close Todo trailer tasks
entry: scripts/todo_hooks.sh closer
language: system
stages: [post-commit]
always_run: true
pass_filenames: false
require_serial: true
- id: max-file-length
name: Max file length (500 lines)
entry: python3 scripts/check_file_length.py
- id: todo-import-pr-merge
name: import PR Todo sections (pull)
entry: scripts/todo_hooks.sh import-pr post-merge
language: system
types_or: [python, shell]
stages: [post-merge]
always_run: true
pass_filenames: false
- id: todo-import-pr-rewrite
name: import PR Todo sections (pull --rebase)
entry: scripts/todo_hooks.sh import-pr post-rewrite
language: system
stages: [post-rewrite]
always_run: true
pass_filenames: false
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
# so the question is mechanically answerable at all.
#
# `files:` is what keeps this cheap: a commit touching only source makes
# ZERO network requests, and manifest commits mostly hit a 6h disk cache.
#
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
# answer and passes with a loud banner; `--no-verify` is banned here, so
# a hook that hard-failed on a flaky connection would leave no way to
# commit at all. CI, always online, is the strict authority.
- id: dependency-freshness
name: dependencies on newest stable
entry: scripts/check_dependency_freshness.sh
language: system
pass_filenames: true
files: >-
(pubspec\.(yaml|lock)|pyproject\.toml|requirements.*\.txt|uv\.lock
|package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version)$
- repo: local
hooks:
# The only pre-push hook. Everything that used to run here is now
# `stages: [manual]` -- run on demand with `scripts/check_gate_stamp.sh
# full`, and by CI on every push. finish_auto.sh stamps HEAD after its
# gate; a tree without that receipt cannot leave the machine.
- id: gate-stamp
name: pushed tree passed the local gate (stamp check)
entry: scripts/check_gate_stamp.sh check
language: system
pass_filenames: false
always_run: true
stages: [pre-push]

1
.versioncode-offset Normal file
View File

@ -0,0 +1 @@
105

250
AGENTS.md Normal file
View File

@ -0,0 +1,250 @@
# CLAUDE.md — wake_alarm
## What this does
**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. The time is an earned
ramp, 08:00 down to 07:00, owned by the phone alone — **`DOCS-ramp.md`**.
The PC's waking role was deleted on 2026-08-30: no alarm window, no smart
plug, no curtains, no `shutdown` wrapper, no sleep hook. On 2026-10-01 exactly
two pieces came back, because the phone **cannot** ring while powered off: a
**fallback ring** when the phone is silent or no session started, and an
**RTC self-wake** before Tue/Wed/Thu. Plus the stacking phone lockdown and a
temporary escape hatch (until 2026-10-15). All of it, and the data contract
the phone, PC and focus-owner share: **`DOCS-wake-enforcement.md`**. Anything
else from the old PC alarm still needs a reason the phone can't do it.
## The dismiss sequence (phone)
```
tag 1 -> 25 steps + 2 min -> tag 2 -> 3 challenges
```
Owned by `phone_app/lib/services/dismiss_gate.dart`. **Strict order, and every
stage latches** — an unknown or out-of-order tag is ignored, never a reset.
`room_proof.dart` answers only "did this one check pass just now"; the
ordering lives in the gate. Keep it that way: the previous version smeared the
decision across `setState` calls and had a real bug where a wrong tap after
passing sent the user back to the start.
- **Two *distinct* tags.** The same id in both slots is refused at
registration — one tag satisfying both stages removes the walk, which is the
entire point. Stored as a JSON list under `roomProof.nfcTagIds`; a legacy
single `roomProof.nfcTagId` migrates into slot 1. **Tags and home location
sync** (`settings_sync.dart`, see `DOCS-phone-alarm.md`) — a reinstall
gets them back; do not make either local-only again.
- **Steps** (`requiredSteps = 25`) are counted from ring start, *not*
re-baselined at tag 1, so walking to tag 1 already banks them and the stage
passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`)
applies **only under bypass/away**, where no tag proved the walk and a
shaken phone would count; on the normal path it was two minutes of ringing
nothing could shorten (dropped 2026-09-16).
- **Answers are cumulative, not consecutive.** A wrong one costs the attempt
and nothing else.
- **The bypass skips the tags, never the walk.** After
`DismissGate.bypassAfter` (5 min), or immediately when NFC is off or fewer
than two distinct tags are registered, the tag stages are skipped and the
count rises to 6. Jumping straight to the challenges would let someone lie in
bed for five minutes and answer questions without standing up — weaker than
the gate this replaced. Do not "simplify" it into that.
- **No challenge may hide its prompt.** The memorise-then-hide kind was
deleted, not merely unrouted: the ring screen is reached by walking in from
another room.
**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in
the same activity, to the silent **morning session**: weigh in → bathroom tag
→ shower → bathroom tag again → wardrobe tag → desk tag. A missed window
(AlarmManager, request code 1003) re-rings; silencing it is the full sequence
again; three re-rings fail the session. Leaving the app is fine: every launch
while the morning is live lands back on the leg (`SessionNotice.kt`). State is
persisted after every change, on wall-clock instants: **`DOCS-morning-session.md`**.
**`HomeScreen.initState` must stay strictly sequential** (`_applyPolicy` →
`_loadSyncState` → `_syncToPc`): run concurrently, the startup publish
captured a null store and **nothing published for three weeks**. Why, the
two deliberately distinct `publish()` failure strings, the ring's injectable
clock, and everything that is a hard crash or a silent no-ring:
**`DOCS-phone-alarm.md`**.
**Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone
does not ring at all: `AlarmReceiver` checks a native cache Dart rewrites
after every mark/release/sync. Picker, cache and its fail-closed contract:
**`DOCS-free-days.md`**. Sick days (`~/src/utils/sickdays`, never a free day):
phone + pre-alarm sync **`DOCS-sick-days.md`**, PC **`DOCS-wake-enforcement.md`**.
## Scheduling — a per-minute timer
`wake-alarm-trigger.timer` ticks every minute (`OnCalendar=*:*:00`,
`Persistent=true`) and runs `python -m wake_alarm._trigger` — a short,
stateless check-and-fire. It resolves the alarm via `_sync.get_alarm()`, builds
today's fire instant in **local** time, and fires iff `now` is in
`[fire_time, fire_time + TRIGGER_CATCHUP_MINUTES)`. Firing means
`systemctl --user start morning-routine.service`, which runs the workout lock.
**The once-per-day latch is load-bearing.** After a successful start,
`_trigger` writes `save_trigger_fired()` and `_skip_reason` gates on
`was_trigger_fired_today()`. Without it the routine restarts on every tick for
the rest of the 60-minute window: the unit is `Type=simple`, so a start while
it runs is a no-op, but the moment the workout lock finishes the next tick
relaunches it on top of the user. This latch replaced the alarm's own
dismissal record when `_alarm.py` was deleted — deleting one without adding the
other is a silent regression, and that is exactly the trap.
`Persistent=true` plus the 60-minute window is also what replaced the deleted
systemd-sleep hook: a suspended or just-booted machine still fires.
## Reading the phone's alarm
`_sync.py` is the only reader.
- Source of truth: a `crdt_sync` log written by `phone_app/` under
`wake-alarm-sync/devices/<device-id>/alarm.json`, at
`.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. Same logical path on both
backends, so only the transport differs, never the parse.
- **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 08:00 — 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
rather than allowed to win. `SYNC_ALARM_PATH` remains as a last-resort read
for a backend that lists nothing.
- Payload parsing/ranking lives in `_alarm_payload.py`: `_sync.py` owns
fetching, caching and fallback; `_alarm_payload.py` owns "what did the phone
actually say".
- **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is
deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
- Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config file
is checked **before** anything is constructed, so an unconfigured machine
never touches the network.
- GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`,
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker is
Firebase-only since 2026-10-09; its `sync_token` is no longer read).
Needs `repo` scope — the repo is private, so a token without access returns
**404, not 403**.
- `crdt_sync` is imported at module scope but **guarded by
`try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so
a dependency that failed to install must degrade the read to the GitHub path
rather than crash the per-minute trigger. The GitHub path stays stdlib-only
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 → 08:00. 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
stamped it*, never on when we fetched — checking the fetch is trivially
defeated, because the cache is rewritten from the same stale record every few
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
08:00 is the latest the phone can ever arm. 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;
a persistent condition logged loudly is 1440 journal lines a day. `_trigger`
emits the single WARNING that matters: firing *now* on a non-phone time.
- **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`,
**`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the
workout and LeetCode locks to 11:00 via one signed file both consumers read.
Phone-local dates only — never `_state._today_str()` (UTC).
## The morning_routine orchestrator lives elsewhere
`morning_routine._orchestrator` (in `testsAndMisc/python_pkg/morning_routine/`)
is what `_trigger` starts, and it now runs one leg: `screen_locker.screen_lock`.
Its alarm leg was removed in the same change that deleted `_alarm.py`.
**When this package's module paths change, the orchestrator must change in the
same commit.** Leaving it pointing at a module that no longer exists caused a
month-long silent production failure once already (2026-05-28, orchestrator
still on `python_pkg.screen_locker.screen_lock` after screen-locker's
extraction): the alarm fired and dismissed correctly while the workout lock
crashed with `ModuleNotFoundError` on every run.
## Production dependency installation
`wake-alarm-trigger.service` runs `/usr/bin/python` directly — **not** a venv.
Any new non-stdlib dependency must go into system Python's *user*
site-packages:
```bash
/usr/bin/python3 -m pip install --user --break-system-packages -e .
```
**Run `install.sh` (or `pip install -e`) from a durable clone**, not a scratch
directory — it is editable, so a later `git pull` in that clone updates the
running production code. From `/tmp` or via `pip install "wake_alarm @ git+..."`
you get a snapshot frozen at that commit, and the next push silently does not
reach the running service. Convention: `~/src/wake-alarm`, mirroring
`~/src/screen-locker`.
If you add a dependency and only install it into a dev venv, the service fails
with `ModuleNotFoundError` on its next run — this exact gap caused a 3-day
diet_guard outage. Verify against `/usr/bin/python3 -c "import <dep>"`.
## Uninstalling
`uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring
unit, the logind power-key drop-in and an RTC alarm we armed, and retires the
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls `uninstall.sh --retired-only` as its last step, so
**`uninstall.sh` is load-bearing for installing**, not just for removing —
renaming or deleting it breaks a fresh install. That call is non-fatal and
gated on `sudo -n`: the cleanup needs root, and a hard failure there would
abort an install that had already placed the package and enabled the timer.
**`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full
uninstall. Since 2026-10-01 it is live again: the RTC self-wake's `rtcwake`
and the root ring unit's `systemctl start|stop` lines live there.
## Operational gotchas
- **`wake_state.json` is runtime state, not tracked.** It holds the
HMAC-signed once-per-day latch. It was accidentally committed in the
monorepo and must stay gitignored here.
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.**
`_trigger` writes it now, and the trigger tests never redirected it — a
per-file redirect is exactly the kind that gets forgotten when a new writer
appears, and the failure is silent: a green suite that quietly stamped the
live state file.
## Commands
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run`
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact`
- test-changed: `scripts/test_changed.sh`
- lint: `pre-commit run ruff --all-files && cd phone_app && flutter analyze --fatal-infos --fatal-warnings`
- coverage: `python -m pytest -q wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-report=xml --cov-fail-under=100`
- coverage-gaps: `coverage-gaps coverage.xml`
Other: full lint gate `pre-commit run --all-files`; watch live
`journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` /
`bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh`
(disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning
`phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone
via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md` — starts a **real**
alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.
## Do NOT
- Don't add a dependency without the production install-path check above.
`_sync.py`'s GitHub path is stdlib-only for that reason — don't "improve" it
to `requests`, and don't make the `crdt_sync` import unconditional. Don't
forget the orchestrator when changing this package's module paths.
- Don't point the trigger at anything but `morning-routine.service` (or the
workout lock never runs), don't remove its once-per-day latch, and don't
raise the log level of `_sync`'s degraded-read paths.
- Don't let the bypass skip the walk, and don't add a challenge kind that
hides its own prompt.
- Don't close the ring screen on dismiss when a session should follow, don't
add a re-ring cancel beyond the session's own `finishSession`, and don't
restore a re-ring instant that has passed (BOOT_COMPLETED replays on launch).
- Don't make `HomeScreen.initState` concurrent again; keep `publish()`'s two failure messages.
- Don't date a record by when the PC fetched it, and don't let a consumer of
`morning_session.json` re-derive the 09:30/11:00 cutoffs or fetch its own copy.
- Don't delete `/etc/sudoers.d/wake-alarm`. Don't commit `wake_state.json`.

217
CLAUDE.md
View File

@ -1,217 +0,0 @@
# CLAUDE.md — wake_alarm
## What this does
A weekend wake alarm: on alarm days (`ALARM_DAYS` in `_constants.py` — Mon,
Fri, Sat, Sun), the machine hibernates overnight and wakes itself via
`rtcwake` at the configured alarm time. `wake-alarm.service` then opens a
fullscreen Tk window that must be dismissed (with a typed challenge — see
`_challenges.py`), ramps fans to 100% via `wake-alarm-fans.sh`, plays audio
through whatever sink comes up after the monitor wakes, and optionally
toggles a TP-Link Tapo P110 smart plug via `python-kasa`.
## Scheduling — a per-minute timer, with hibernate as the fallback
The PC is **always on**. The alarm time comes from the phone, which can change
it at any hour, so nothing about the schedule may be baked in ahead of time.
**Primary path — `wake-alarm-trigger.timer`:**
1. The timer ticks every minute (`OnCalendar=*:*:00`, `Persistent=true`) and
runs `python -m wake_alarm._trigger` — a short, stateless check-and-fire.
2. `_trigger` resolves the alarm via `_sync.get_alarm()`, builds today's fire
instant in **local** time, and fires iff `now` is in
`[fire_time, fire_time + TRIGGER_CATCHUP_MINUTES)`. The catch-up window is
what makes a suspended or just-booted machine still fire.
3. Firing = `systemctl --user start morning-routine.service`. **Never**
`wake-alarm.service` directly — see the orchestrator section below.
Starting an already-active unit is a no-op, so an alarm on screen needs no
extra dedupe state; the `was_alarm_dismissed_today()` /
`was_workout_logged_today()` gates cover the rest.
A timer, not a resident daemon: each tick is a fresh process, so there is no
long-lived scheduler to die silently and no wall-clock jump to handle across
suspend/resume.
**Fallback path — hibernate (only when the PC really is powered down):**
`shutdown-wrapper.sh` (installed to `/usr/local/bin/shutdown`, shadowing
`/usr/bin/shutdown` via PATH order) still intercepts shutdown/poweroff, reads
the same synced alarm, and sets `rtcwake`. `sleep-hook.sh` (in
`/usr/lib/systemd/system-sleep/`) fires on resume (`$1 == post`) and starts
`morning-routine.service`. This is now a backstop, not the main mechanism.
If you change `WAKE_AFTER_HOURS` in `_constants.py`, you must also update the
duplicate constant in `shutdown-wrapper.sh` (`WAKE_AFTER_HOURS=8`) — they are
not wired together, by design (the shell wrapper has no Python runtime
available at the point it intercepts `shutdown`).
**The wrapper no longer talks to the network or handles a token.** It reads
`~/.config/wake_alarm/alarm_cache.json` — the cache `_sync.py` already
refreshes every minute — and falls back to `WAKE_AFTER_HOURS` if that file is
absent, malformed, or more than 2 days old. This removed the duplicated token
search order (`read_sync_token()` used to mirror `SYNC_CONFIG_FILE` /
`SYNC_TOKEN_FALLBACK_FILES`), and it is what makes the wrapper survive the
move to Firebase unchanged: an ID token expires in about an hour, and a shell
script at shutdown time has no safe way to refresh one. The only coupling left
is the cache's `{"hour","minute","fetched_at"}` shape — keep the reader in the
wrapper in step with `_write_cache()` in `_sync.py`.
## `wake-alarm.service` must never auto-start
`wake-alarm.service` deliberately has **no `[Install]` section** and nothing
starts it automatically. `_should_run_alarm()` gates on day / dismissed /
workout-logged but has **no time gate**, so a
`WantedBy=graphical-session.target` there fires the alarm at *login* time on
any alarm day — which is every day now that the machine no longer reboots into
the alarm. `install.sh` explicitly runs `systemctl --user disable
wake-alarm.service` to clear the stale symlink from older installs.
The unit survives only as a manual test handle. Do not "fix" its missing
auto-start.
## Reading the phone's alarm
`_sync.py` is the only reader of the remote alarm. `shutdown-wrapper.sh` reads
`_sync.py`'s local cache instead of the remote file, so there is no second
remote reader to keep in step.
- Source of truth: `wake-alarm-sync/devices/phone/alarm.json`, written by
`phone_app/` as a `crdt_sync` log. The value lives at
`.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. **The same logical path
on both backends** — Firebase's namespace mirrors the repo layout — so only
the transport differs, never the parse.
- **Firebase first, GitHub as the cutover mirror** (`fetch_remote_alarm()` is
just `_fetch_firebase_alarm() or _fetch_github_alarm()`). Retiring the
mirror is deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
- Firebase config: the shared `~/.config/crdt-sync/firebase.json`; the
refresh token is cached per app under `SYNC_APP_NAME` (`wake_alarm`), so
this app's credential is separate from its siblings'. The config file is
checked **before** anything is constructed, so an unconfigured machine
never touches the network.
- GitHub token (fallback path only): `~/.config/wake_alarm/sync.json` key
`token`, else a sibling app's raw
`~/.config/{diet_guard,screen_locker}/sync_token`. Needs `repo` scope — the
repo is private, and a token without access returns **404, not 403**.
- `crdt_sync` is imported at module scope but **guarded by
`try/except ImportError`**, exactly like `python-kasa` in `_smart_plug.py`:
the service runs `/usr/bin/python`, not a venv, so a dependency that failed
to install must degrade the read to the GitHub path rather than crash the
per-minute trigger. The GitHub path stays stdlib-only 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
(`~/.config/wake_alarm/alarm_cache.json`) is what bounds remote reads to
~288/day despite the per-minute tick, and what keeps a network blip from
costing a wake-up.
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute,
so a persistent condition logged loudly is 1440 identical journal lines a
day. `_trigger` emits the single WARNING that matters: it is firing *now* on
a non-phone alarm time.
Check what the PC currently resolves: `python -m wake_alarm._sync --show`.
Check what it would do right now: `python -m wake_alarm._trigger --dry-run`.
## Cross-repo coupling — not a bug
`_constants.py`'s `WORKOUT_LOG_FILE` points at
`~/screen-locker/screen_locker/workout_log.json` — a file owned by the
separate, already-standalone `screen-locker` repo
(https://github.com/kuhyx/screen-locker). This is intentional: the alarm
reads whether today's workout was already logged by screen-locker to decide
whether the morning routine should also lock the workout screen. If this
path ever raises `ModuleNotFoundError`-style confusion, the bug is almost
certainly in the **orchestrator** (`morning_routine` in testsAndMisc), not
here — see the next section.
## The morning_routine orchestrator lives elsewhere
`morning_routine._orchestrator` (in `testsAndMisc/python_pkg/morning_routine/`)
runs this package and `screen_locker` as two sequential subprocesses. When
either package is extracted to its own repo, **the orchestrator's module
reference must be updated in the same change** — this exact mistake
(orchestrator left pointing at `python_pkg.screen_locker.screen_lock` after
screen-locker's extraction on 2026-05-28) caused a month-long silent
production failure where the alarm fired and dismissed correctly but the
workout lock crashed with `ModuleNotFoundError` on every run. Once both
`wake_alarm` and `screen_locker` are pip-installed system-wide, the
orchestrator needs no `PYTHONPATH`/`cwd` plumbing — plain
`subprocess.run([sys.executable, "-m", module, "--production"])` resolves
both.
## Production dependency installation — read this before adding any dependency
`wake-alarm.service` runs `/usr/bin/python` directly — **not** a venv. Any
new non-stdlib dependency (this package itself, `gatelock`, `python-kasa`,
anything added later) must be installed into system Python's *user*
site-packages:
```bash
/usr/bin/python3 -m pip install --user --break-system-packages -e .
```
**Always run `install.sh` (or `pip install -e`) from a durable clone, not a
scratch directory.** `install.sh` does `pip install -e "$REPO_DIR"` —
editable, so a later `git pull` in that same clone updates the running
production code with no reinstall needed. The clone must live somewhere
permanent (this repo's convention: `~/wake-alarm`, mirroring `~/screen-locker`
for the screen-locker package) — if you `pip install -e` from `/tmp/...` or
run `pip install "wake_alarm @ git+https://..."` as a one-off, you get a
non-editable snapshot frozen at that commit, and the next `git push` here
silently does **not** reach the running service.
`install.sh` already does this. **If you add a dependency and only install it
into a dev venv, the production service will silently fail with
`ModuleNotFoundError` on its next run** — this exact gap caused a 3-day
diet_guard production outage (2026-06-19 to 2026-06-22) for the sibling
`gatelock` migration. Always verify against
`/usr/bin/python3 -c "import <new_dep>"`, not just the dev venv, before
considering a dependency change done.
## Operational gotchas
- **`python-kasa` is optional at runtime** (`_smart_plug.py` catches
`ImportError` and disables smart-plug control with a warning log), but it
*is* a hard dependency for this repo's own tooling (mypy/pylint/tests need
it importable) — see `pyproject.toml`/`requirements.txt`.
- **The `wave` module needs special pylint handling.** `_audio.py` opens WAV
files in write mode; pylint's stdlib stub infers the read-mode overload and
wrongly flags `setnchannels`/`setsampwidth`/`setframerate`/`writeframes` as
missing. See the `generated-members` list in `pyproject.toml`'s
`[tool.pylint.typecheck]` — don't remove it if pylint starts complaining
about `wave.Wave_write`.
- **`wake_state.json` is runtime state, not tracked.** It holds the
HMAC-signed dismissal record for the current alarm day. It used to be
accidentally committed in the monorepo; it is gitignored here and must
stay that way.
## Commands
- Run tests: `python -m pytest wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-fail-under=100`
- Lint: `pre-commit run --all-files`
- Test the lock manually (safe, closeable): `python -m wake_alarm._alarm --demo`
- Show the resolved alarm: `python -m wake_alarm._sync --show` (add
`--no-cache` to force a live GitHub read)
- Show what the next tick would do: `python -m wake_alarm._trigger --dry-run`
- Watch it live: `journalctl --user -fu wake-alarm-trigger.service`
- Install for production: `bash install.sh`
Note the dev venv lacks `gatelock`, so anything importing `_state` (including
`_trigger`) must be run with `/usr/bin/python3`, not `.venv/bin/python`.
## Do NOT
- Don't add a dependency without doing the production install-path check
above. `_sync.py`'s **GitHub** path is stdlib-only for exactly this reason —
don't "improve" it to `requests`, and don't make the `crdt_sync` import
unconditional: the `try/except ImportError` guard is what keeps a failed
install from killing the trigger.
- Don't forget the orchestrator when changing this package's module path or
invocation — see "The morning_routine orchestrator lives elsewhere" above.
- Don't give `wake-alarm.service` an `[Install]` section or enable it. It
fires at login time, not alarm time — see the section above.
- Don't make the trigger start `wake-alarm.service`; it must start
`morning-routine.service` so the workout lock still runs.
- Don't raise the log level of the routine degraded-read paths in `_sync` —
the per-minute tick turns any WARNING there into journal spam.
- Don't commit `wake_state.json`.

1
CLAUDE.md Symbolic link
View File

@ -0,0 +1 @@
AGENTS.md

View File

@ -1,251 +0,0 @@
# Design audit — wake-alarm
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
Report only — nothing in this repo was changed by the audit itself.
This repo has two distinct UI surfaces, audited separately below:
1. Flutter app — `phone_app/lib/` (theme in `main.dart`, screens in `screens/`)
2. Python/Tkinter alarm dismiss-challenge UI — `wake_alarm/_alarm.py`
Passing/violation/N-A counts per surface are given at the top of each section
so all 28 rules are accounted for even though only violations get expanded.
---
## Flutter app (`phone_app/`)
Theme entry point: `phone_app/lib/main.dart:17-21` —
`ThemeData.dark(useMaterial3: true).copyWith(colorScheme:
ColorScheme.fromSeed(seedColor: Colors.orange, brightness: Brightness.dark))`.
Material 3's `fromSeed` auto-generates near-black surfaces, tinted neutrals,
and contrast-checked roles, so rules 1/2/3/9/10/18 pass "for free" via the
theme — the actual findings are places where code reaches for a literal
`Colors.*` constant instead of a role from that scheme, or a shadow/padding
value the theme doesn't control.
Verdict roster: Pass — 1,2,3,8,10,17,18,23,26. Violation — 4,9(partial,
see notes),11,20,26(Card),28. N/A — 5,6,7,12,13,14,15,16,19,21,22,24,25,27.
(9 and 26 appear in both lists — see the per-rule notes.)
### Violations
- **Rule 4 (everything deliberate)** — `phone_app/lib/screens/home_screen.dart:198-199` and
`settings_screen.dart:126-128,161,245` use raw `Colors.redAccent` /
`Colors.greenAccent` / `Colors.red` for status/error text instead of
`Theme.of(context).colorScheme.error` (or a `tertiary`/success role);
`home_screen.dart:207` uses raw `Colors.orange` and `settings_screen.dart:138`
uses raw `Colors.grey` for the same reason. None of these are derived from
the seeded `ColorScheme`, so they won't stay in sync if the seed color ever
changes, and they bypass whatever contrast guarantee `fromSeed` gives the
rest of the app. → Replace with `colorScheme.error` / a defined success
color / `colorScheme.onSurfaceVariant`.
- **Rule 9 (distinct brightness / no competing colors)** — `home_screen.dart:198-199`
vs `settings_screen.dart:126-128,161`: `Colors.redAccent`/`Colors.greenAccent`
are reused ad hoc as the only "status" signal color pair across two separate
screens with no shared definition — not a brightness clash per se, but an
undeliberate ad-hoc pairing (same root cause as rule 4).
- **Rule 11 (mathematically related measurements)** — the app mostly uses an
8px scale (`home_screen.dart:149,154,165,170,191,203` = 32/16/8/32/24/16;
`settings_screen.dart:93,98,121,131` = 16/16/16/32) but breaks it twice:
`settings_screen.dart:111` (`padding: EdgeInsets.symmetric(vertical: 14)`)
and `settings_screen.dart:163` (`SizedBox(width: 12)`) — 14 and 12 aren't on
the 8px grid the rest of the file uses. → change to 16/8 or otherwise round
to the established scale.
- **Rule 20 (body text ≥16px)** — `settings_screen.dart:138`:
`TextStyle(fontSize: 12, color: Colors.grey)` for the PC-config help text is
below the 16px minimum. `home_screen.dart:153` (`fontSize: 16`) and other
`fontSize: 18` usages are fine.
- **Rule 26 (no shadows in dark interfaces)** — `settings_screen.dart:154`
(`return Card(...)`) is an unmodified Material 3 `Card`, which renders with
default elevation (a soft shadow/tonal overlay) inside a `ThemeData.dark()`
app (`main.dart:17`). Per the rule, dark UIs should avoid shadows entirely.
→ Either set `elevation: 0` and rely on a filled/tonal surface color for
the card, or accept the default and drop this from future review — flagging
now since it's the only place shadows appear at all (see rule 27 below).
- **Rule 28 (lower icon contrast next to text)** — `settings_screen.dart:159-162`
(`Icon(connected ? Icons.check_circle : Icons.cancel, color: connected ?
Colors.greenAccent : Colors.redAccent)`) sits directly next to `Text(...)`
at full theme-text contrast — the icon isn't dimmed relative to the
adjacent label. Same issue for the settings-gear `IconButton` at
`home_screen.dart:133-134` (default `Icons.settings` color, undimmed, next
to the "Wake Alarm Sync" AppBar title).
### Not applicable
- Rule 5 (optical alignment) — only stock Material icons/text used, no custom
shapes needing eyeballed alignment.
- Rule 6 (letter-spacing/line-height by size) — no explicit `letterSpacing`/
`height` overrides anywhere in `phone_app/lib/` (grep confirmed); relies on
Material defaults, nothing to audit.
- Rule 7 (border contrast) — no `Border`/`BorderRadius`/`border:` usage found
anywhere under `phone_app/lib/` (grep confirmed); no borders exist.
- Rule 12 (order by visual weight) — single linear `Column` per screen, no
competing-weight layout to order.
- Rule 13 (12-column grid) — single-column mobile screens, no grid layout.
- Rule 14 (space between high-contrast points) — can't be assessed from
source; spacing is via `SizedBox`/`Padding` bounding boxes, not measured
edge-to-edge.
- Rule 15 (closer = lighter) — the one elevated element (`Card`,
`settings_screen.dart:154`) follows M3's automatic surface-tint elevation
overlay, which already lightens on elevation — no manual z-stack to check.
- Rule 16 (shadow blur = 2x distance) — shadow is Material's default (see
rule 26), not a custom `BoxShadow`, so there's no explicit offset/blur pair
to check a ratio on.
- Rule 19 (outer padding ≥ inner) — `settings_screen.dart:93` outer body
padding (16) vs `settings_screen.dart:156` `_StatusCard`'s own inner
padding (16): equal, satisfies "≥". `home_screen.dart:149` outer padding
(32) vs the button's inner vertical padding (16, `home_screen.dart:186`):
outer > inner. Both pass, no violation to report.
- Rule 21 (line length ~70 chars) — only short status strings/labels; the one
paragraph (`settings_screen.dart:132-137`) is already manually broken into
short lines, no long unbroken runs to measure.
- Rule 22 (button padding horizontal = 2x vertical) — `home_screen.dart:185-188`
and `settings_screen.dart:110-113` only override `vertical` padding
(16 and 14) and leave horizontal at the `ElevatedButton` theme default —
the actual rendered ratio can't be read from source alone.
- Rule 24 (nest corners) — no custom `BorderRadius` anywhere (grep
confirmed), only default Material shapes.
- Rule 25 (adjacent hard divides) — only one `Divider` in the whole app
(`settings_screen.dart:131`), not adjacent to another border/transition.
- Rule 27 (don't mix depth techniques) — only one depth technique appears at
all (the `Card`'s default elevation, rule 26) — nothing to mix.
### Notes
- No dedicated `theme.dart` — the `ColorScheme`/`ThemeData` is inline in
`main.dart:17-21`. That's fine at this size (2 screens), but every raw
`Colors.*` literal found above is a spot that would have been caught by a
lint/review pass if a shared palette module existed to import from instead.
---
## Python/Tkinter alarm UI (`wake_alarm/_alarm.py`)
No shared style/constants module exists for color or font — confirmed via
`find` (no `theme`/`style`/`colors` module under `wake_alarm/`) and via
`_constants.py`, which defines timing/day constants but nothing visual.
Every `tk.Label`/`tk.Frame`/`tk.Entry` call in `_alarm.py` repeats its own
hex-color and `font=(...)` tuple literal inline (confirmed: `_alarm.py:166,
172-174,181-183,190-192,200-206,209-211,219-224,228-232,326-331,409`). This
structural absence is itself the rule 4 finding — it also means the same
rule (e.g. rule 2, rule 10) is violated independently at every call site
rather than in one place, so a future fix should introduce a small
`_style.py`/constants block rather than patch each `tk.Label(...)` call.
Verdict roster: Pass — 3,8,17,20,21,23,26,27. Violation — 1(partial),
2,4,9(mixed reuse—see below),10,11,12. N/A — 5,6,7,13,14,15,16,18,19,22,24,25,28.
### Violations
- **Rule 1 (near-black/near-white, not pure)** — `_alarm.py:166` (`bg="#1a1a1a"`)
correctly uses near-black, not pure black — that part passes. But
`_alarm.py:191-192` (`info_label`, `fg="white"`) uses **pure white** text,
which the rule explicitly calls out to avoid. → use an off-white like
`#e8e8e8`/`#f0f0ee` instead of the literal `"white"`.
- **Rule 2 (saturate your neutrals)** — the only "neutral" grey values used
are perfectly desaturated (zero-chroma) greys: `_alarm.py:232`
(`timer_label`, `fg="#aaaaaa"`) and `_alarm.py:305` (hidden-code flash
state, `fg="#555555"`). Neither has any color tint, so they read as
generic gray rather than part of the warm/cool palette the rest of the
screen uses (see rule 10). → tint both toward the same hue family as the
accent colors (e.g. a warm dark gray like `#4a3f3f` / `#8a7d7d`).
- **Rule 4 (everything deliberate / centralize styling)** — see the surface
intro above; every color/font is a repeated inline literal across
`_alarm.py:166-234` and `_alarm.py:326-331`, with no single source of
truth. → extract a small `_COLORS`/`_FONTS` mapping (mirroring the
existing `_constants.py` pattern for non-visual constants) and reference
it from every widget call.
- **Rule 9 (distinct brightness / deliberate reuse)** — `title_label`
(`_alarm.py:173`, `fg="#ff4444"`) and `status_label`
(`_alarm.py:223`, `fg="#ff4444"`) reuse the exact same color for two
different semantic roles ("WAKE UP!" heading vs. a transient error/status
message) with no evidence it was a deliberate choice rather than
copy-paste — flagging alongside rule 4 since fixing the missing style
module would force this decision to be made explicitly.
- **Rule 10 (warm OR cool, not both)** — the screen simultaneously uses warm
reds/ambers (`_alarm.py:173` `#ff4444`, `:182` `#ffaa00`, `:409`
`#ff0000` flash) and a fully saturated cool green (`_alarm.py:204,263,274,
347` `#00ff00`) on the same screen at the same time. → pick one
temperature family for the "safe/positive" accent (e.g. a warm amber-green
or switch the alert red to a cooler red) so the palette reads as one
coherent set rather than a stoplight.
- **Rule 11 (mathematically related measurements)** — `pady` values across
the widget stack are `20, 5, 10, 30, 10, 10, 5` (`_alarm.py:176, 185, 194,
207, 215, 226, 235`) — mostly multiples of 5/10, but `pady=5` at lines 185
and 235 breaks the 10/20/30 pattern used by the surrounding widgets.
→ round the two `pady=5` calls to `10` for a consistent scale.
- **Rule 12 (order by visual weight)** — the largest, boldest element on
screen is `code_label` at up to 72pt bold (`_alarm.py:198-206`,
`code_font_size = 48 if ... else 72`), sitting in the visual middle of the
stack, while the actual title (`_alarm.py:172`, 48pt bold) anchors the top
edge and the lightest elements (`timer_label`, 14pt, `_alarm.py:231`) sit
at the bottom edge. The rule wants the heaviest element toward an outer
edge, not buried in the middle. → this is likely intentional here (the
code you must type back is the whole point of the screen), so treat as a
judgment-call violation to confirm rather than an unambiguous bug.
### Not applicable
- Rule 5 (optical alignment) — only text `Label`s stacked via `.pack()`, no
asymmetric shapes/icons to align by eye.
- Rule 6 (letter-spacing/line-height by size) — Tkinter's `font=(family,
size, weight)` tuple has no letter-spacing/line-height control at all;
not expressible in this toolkit.
- Rule 7 (border contrast) — no `relief`/`highlightthickness`/`borderwidth`
set on any widget (grep confirmed); nothing has a visible border.
- Rule 13 (12-column grid) — single fullscreen widget centered via
`.place(relx=0.5, rely=0.5)` (`_alarm.py:167`), no grid layout in use.
- Rule 14 (space between high-contrast points) — `pack(pady=...)` controls
bounding-box spacing, not measured edge-to-edge visual contrast; not
determinable from source.
- Rule 15 (closer = lighter) — Tkinter has no z-stack/elevation concept;
this is a flat 2D layout on one background plane.
- Rule 16 (shadow blur = 2x distance) — no shadow effects implemented
anywhere in the file.
- Rule 18 (container brightness limits) — only one background plane exists
(`#1a1a1a`, toggled with a full-screen alert flash to `#ff0000` at
`_alarm.py:409` — not a stacked container), so there's no second surface
brightness to compare it against.
- Rule 19 (outer padding ≥ inner) — `container` (`_alarm.py:166`) has no
configured padding of its own; only individual children set `pady`. No
outer/inner pair exists to compare.
- Rule 22 (button padding) — no `tk.Button` widget exists anywhere in the
file (grep confirmed) — dismissal is via `tk.Entry` + `<Return>` bind
(`_alarm.py:209-217`), not a button.
- Rule 24 (nest corners) — Tkinter widgets are square by default with no
corner-radius concept; not implemented here.
- Rule 25 (adjacent hard divides) — no border/divider lines used anywhere.
- Rule 28 (icon contrast next to text) — no icons used anywhere in this UI;
text-only.
### Passes (brief)
- Rule 3 (high contrast for important elements) — `_alarm.py:172-174`
"WAKE UP!" title in `#ff4444` on `#1a1a1a` background is clearly the
highest-contrast element on screen.
- Rule 8 (align with something) — `container.place(relx=0.5, rely=0.5,
anchor="center")` (`_alarm.py:167`) plus uniform `.pack()` centering means
every widget shares the same center-alignment axis.
- Rule 17 (simple on complex) — flat solid `#1a1a1a` background behind flat
text (`_alarm.py:166`) is plain-on-plain throughout; no visual noise.
- Rule 20 (body text ≥16px) — smallest font used is 14pt
(`_alarm.py:231`, `timer_label`) ≈ 18-19px at typical DPI, above the 16px
floor; all other labels are 18pt+ (`_alarm.py:190,222`) or larger.
- Rule 21 (line length ~70 chars) — only short single-line status strings
are used (longest is ~55 characters, `_alarm.py:372`); no wrapped
paragraph text to overflow the readable range.
- Rule 23 (two typefaces max) — exactly two families used throughout,
`"Arial"` and `"Courier"` (`_alarm.py:172,181,190,203,211,222,231,329`) —
at the limit, not over it.
- Rule 26 (no shadows in dark interfaces) — trivially satisfied: no shadow
effects are implemented anywhere in this file.
- Rule 27 (don't mix depth techniques) — trivially satisfied: zero depth
techniques are used, so none can conflict.
### Notes
- The most impactful single fix for this surface is structural, not any one
color/font value: introduce one `_style.py` (or a `_COLORS`/`_FONTS` dict
in `_constants.py`) and reference it from every `tk.Label`/`tk.Frame` call
in `_alarm.py`. That alone would make rules 2, 9, 10, and 11 fixable in one
place instead of ~15 separate call sites.

83
DOCS-free-days.md Normal file
View File

@ -0,0 +1,83 @@
# Free days — the phone picker for the shared pool
The pool itself is `~/src/utils/freedays` (Python): one global set of days on
which every gate app stands down, 35 per calendar year, declared for today or
later, never backdated, refunded only while still in the future. Read its
README for the rules. This file covers the phone half, which lives in this
repo because the alarm is the one gate where standing down is a physical
event — the phone stays silent — rather than an absent dialog.
## Where things are
| | |
|---|---|
| Picker | `phone_app/lib/screens/free_days_screen.dart` (+ `free_days_body.dart`, the shared `day_calendar.dart`), the calendar icon on the home screen |
| Rules, Dart port | `phone_app/lib/services/free_day_pool.dart` — same record shape as the Python package, byte for byte |
| Sync | `phone_app/lib/services/free_day_sync.dart` — Firebase only, `freedays-sync/devices/<uuid>/free_days.json` |
| Ring path | `android/.../FreeDays.kt` + the check at the top of `AlarmReceiver.onReceive` |
## The calendar
A Monday-first month grid (adapted from punchme's, whose own free days are a
separate concept and are not read here). One tap per future date: an empty day
is booked with no reason prompt, a booked day is released and refunded. Today
and the past are read-only — releasing a day that has started still spends
it. Tue/Wed/Thu (`workdays`, mirroring `freedays.WORKDAYS`) are shaded; past
free days stay visible, faded. Months run from January of this year to
December of next. The "Booked ahead" list below keeps reasons from PC marks
and its own Release buttons.
## Why there is a native cache
The alarm fires from Kotlin with no Flutter engine running, so at 08:00 the
Dart pool is unreadable. Dart hands the current free dates to
`FreeDays.store` (channel method `setFreeDays`) after **every** mark, release
and sync; `AlarmReceiver` reads that set before starting `AlarmService`. On a
free day it logs `free day: not ringing; re-armed for tomorrow` and returns —
nothing rings, nothing is shown, and the next morning is normal.
**Fail closed.** An unreadable or missing cache is "not a free day", matching
`freedays.is_free_day()` on the PC: a corrupt pool restores the normal rules,
it never silences the alarm. Verified on the `wake_alarm_api36` AVD
(2026-09-11, `adb root` + `am broadcast --include-stopped-packages -n
…/.AlarmReceiver`): today in the set → skip line, no service; a different
date → service start; a garbage XML file → service start.
## What reaches the phone when
- **Marked on the phone:** immediate. The cache is rewritten before the sync
even runs, so an offline phone still stands down on a day it marked itself.
- **Marked on the PC (`freedays mark …`):** on the phone's next sync: app
launch, either day picker opening, or the **pre-alarm sync** (21:00 and
A − 30 min, app closed; `DOCS-sick-days.md`). That sync needs network at
its slot; if it fails the cache keeps its last sync and the phone rings.
A date is never both free and sick: this picker syncs the sick-day pool on
open and refuses a sick date (`… is a sick day — clear it in Sick days
first.`), and refuses every booking if that pool cannot be read.
## Cross-language check
The Dart port is a second implementation of the rules, so it is verified
against the Python one rather than against itself:
`scripts/free_days_interop/check.sh` (a pre-commit hook on both inputs)
writes one pool through `FreeDayPool` — mark, mark today, mark+release a
future day, mark+release after arrival — replays the same edits through
`freedays.mark`/`release` into a scratch pool, and fails unless the free set,
spent set, `remaining` and `is_free_day` verdicts agree. Dart's own numbers
are never the reference: comparing them to what Python reads from Dart's
file cannot see a drift in what Dart *writes*. Proved on 2026-09-11 by
dropping the sticky `consumed` from `release` — the gate reported
`remaining: dart=33 python=32`. Needs the freedays venv
(`~/src/utils/freedays/install.sh`).
## Do NOT
- Don't give this namespace a GitHub mirror. The alarm record keeps its
mirror because un-migrated installs depend on it; this pool never had one.
- Don't tombstone a date to un-mark it. crdt tombstones are monotonic; a
deleted date could never be marked again. Flip `state` to `cleared`.
- Don't write `consumed` back to `false`. It is the sticky flag that stops
two devices either side of midnight from refunding a day already used.
- Don't add a warning, a notification or a ring-time prompt. The pool is
consulted silently; the count is shown only when the picker is opened.

145
DOCS-morning-session-pc.md Normal file
View File

@ -0,0 +1,145 @@
# The morning session on the PC — the carrot, and what it costs to skip
Companion to `DOCS-morning-session.md` (the phone side). This is how the
phone's morning turns into "no workout lock, no LeetCode lock" on the PC, and
why an aborted morning turns into neither.
## Why
On 2026-09-19 the alarm rang, the full dismiss ran, the session reached the
bathroom tag — and the phone was powered off. Nothing on the PC noticed: the
phone was publishing every finished session and nothing read it, the
workout-lock "carrot" was a hardcoded 05:00–08:30 window in screen-locker
with no link to getting up, and leetcode-guard locked at login regardless. So
finishing the morning was worth at most 30 minutes, and aborting it cost
nothing. Powering the phone off cannot be prevented (device-owner
provisioning, and a 10 s hardware off still wins); it can be *noticed*.
## The rule
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` | 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.
## The plumbing
**wake-alarm is the only Firebase reader.** `wake-alarm-session.timer`
(`*-*-* 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
`morning_sessions` plus `current_session` when it is live, ranked by
`(date, finished-before-live, HLC, device_id)`. **By content, never by
comparing the two fields' stamps**: a phone that lost the network at
finish and never cleared `current_session` still resolves to the finished
morning. The phone's `active` becomes `in_progress`.
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` 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
`today_str`; a UTC date would miss by a day every evening).
**Consumers apply one predicate**: signature verifies ∧ `date == local today`
∧ `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 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
mint an unlocked day). `leetcode-guard.timer` gained 09:30 and 11:00 slots
so a deferred run is re-decided at both boundaries. `--check` prints a
`morning` line.
**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 05:00–11:00, and only when the file is not
today's, both consumers retry for ≤ 180 s (5 s steps) and then proceed as
normal with a WARNING. Status paths never wait; tests pin the retry to 0.
The refresher itself retries an unreadable backend every 5 s for 150 s
(`REFRESH_RETRY_SECONDS`) before exiting 1 with a WARNING: a PC booted at
07:48 had no DNS for its first seconds, and the old single try left the next
chance at the 07:50 tick (2026-11-07).
**`next_step`** (signed with the rest): while the session is `in_progress`,
the label of the first leg not in the phone's `passed` map, else `null`.
Names and labels live in `_session_legs.py` and are pinned to the phone's
`SessionLeg` by `wake_alarm/tests/fixtures/session_legs.json`, asserted by a
Python and a Dart test.
## Known limits (v1, deliberate)
- 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. (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.
## The workday stick (2026-09-23)
The carrot above only pulls on a day the PC is actually being used to enjoy
it — a weekend. On a workday the user leaves for the office regardless, so
losing/keeping the PC's lock was worth nothing, and powering the phone off
at ring time (which stops the alarm dead — nothing left to sync, no session
ever recorded) cost nothing either.
On **Tuesday/Wednesday/Thursday** — `wake_alarm._constants.STICK_DAYS`, the
same weekdays screen-locker already calls "relaxed"
(`_weekly_check.is_relaxed_day`) and leetcode-guard already prices as cheap
(`Pricing.doubled_days`) — a genuine miss (`failed`, or `none` past its own
`SESSION_NONE_GRACE`; a *late* `completed` is not a miss, the walk still
happened) costs tomorrow's leniency in both apps instead of just resetting
to normal. `wake_alarm._workday_penalty.maybe_apply()` runs at the end of
every `_session.refresh()` and, when a stick-day miss is detected and today
is not a free day, signs and writes
`~/.local/state/wake_alarm/workday_penalty.json` (`{"penalty_date":
"<tomorrow>", "issued_date": "<today>"}`) — deliberately a separate file
from `morning_session.json`, since that one always describes *today* and is
overwritten at the date rollover, so it cannot carry a marker forward.
screen-locker and leetcode-guard each read it with the same HMAC + date
predicate they already use for `morning_session.json`.
A phone-side stick (locking down distracting apps on the phone itself,
signalled to `phone-focus-mode`'s `focus-owner`) is the other half of this
and lives in `phone_app/`, not here — see its own commit/doc for the exact
signal shape.
## Commands
```sh
python -m wake_alarm._session --refresh # fetch, select, rewrite the file
python -m wake_alarm._session --show # the verified file + a verdict line
python -m wake_alarm._energy # {"date", "level"} or exit 1
systemctl --user list-timers | grep wake-alarm-session
journalctl --user -u wake-alarm-session.service -n 20
leetcode-guard --check # the "morning" line
```

184
DOCS-morning-session.md Normal file
View File

@ -0,0 +1,184 @@
# The morning session — what happens after the ring stops
The ring proved you stood up. It did not stop you lying back down: the
2026-09-16 observation was "I do the tags, the walk and the questions, and
then go back to sleep". So since that day **the dismiss does not end the
morning**. It hands over, inside the same `AlarmActivity`, to a silent
checklist that only ends when you are showered, dressed and sitting at the
desk — and the alarm comes back if a step is missed or the phone lies still.
Owner: `phone_app/lib/services/morning_session.dart` (the record),
`session_rules.dart` (what moves it), `screens/session_screen.dart` (the
driver), `session_handoff.dart` (how the ring reaches it).
## The legs
```
weigh in -> bathroom tag (≤ 2 min later) -> shower -> bathroom tag again
-> wardrobe tag -> desk tag -> done
```
| leg | passes when | window (re-ring at) | notes |
|---|---|---|---|
| `bathroomIn` | bathroom tag with a *pending* weight ≤ 2 min old | start + 10 min | the typed weight is not a leg; the tag is what proves you walked to the scale |
| `showerDone` | bathroom tag **≥ 8 min** after `bathroomIn` | `bathroomIn` + 18 min | its own window: 10 min composed with the 8-min floor would be a two-minute target, hit wet |
| `dressed` | wardrobe tag | previous + 10 min | |
| `atDesk` | desk tag | previous + 10 min | |
**A later tag catches up a forgotten one** (`LegPass.caughtUp`, 2026-11-01:
shower tag forgotten, re-rung while dressing). The weigh-in never catches
up, and the shower's 8-minute floor still applies.
Legs latch like the ring's stages. A leg whose tag is not registered is
**skipped at start** (`LegPass.skipped`), so the feature is usable before it
is configured: with no session tags at all it is a weigh-in and nothing
else. Away from home (`RingSkip.away`) there is no session.
**Weight and energy.** The weight is typed, 30–250 kg; more than 3 kg from
the last confirmed value must be typed twice (`weight_entry.dart`). The
energy is one of five chips, 1–5, and is required before the weight submits
(`session_checkin.dart`): not proof of anything, just the one number worth a
tap while standing at the scale. Without a bathroom tag the check-in passes
the first leg by itself — there is nothing to walk to.
## What rings, and how
- **A missed window** re-rings through an **AlarmManager alarm**
(`AlarmScheduler.scheduleReRing`, request code 1003, `setAlarmClock` like
the daily one). Not a Dart timer: the session screen can be killed, paused
or rebooted away, and the deadline has to survive all three. `BootReceiver`
restores it; `restoreReRing` drops an instant that has already passed
(see *Gotchas*).
- **No still-phone check.** An accelerometer watch (`MotionMonitor.kt`, 4 min
without motion) existed for one day and was deleted on 2026-09-17: it only
ran while the session screen was in front, and the real routine leaves the
app on purpose (a podcast before the shower), so it was off for most of the
session and never rang on the one morning it was watched. The deadlines are
the only re-ring. Do not bring it back as a foreground service without a
morning that shows a lie-in the ≤ 10-minute windows missed.
- When Dart rings a deadline itself it routes to `/ring` afterwards, in case
the full-screen intent lands on the live `singleInstance` activity instead
of recreating it.
- **Silencing a re-ring is the full dismiss sequence**: tag 1, the walk,
tag 2, three questions. The ring screen's `_finishDismiss` sees a live
session for today and resumes it with `reRings + 1`.
- **A silent buzz 3 min before each deadline** (`SessionWarn.kt`, request
code 1004), armed and cleared only with the re-ring.
- **One re-ring per leg.** After a deadline re-ring is dismissed the leg is
in `deadlineRung`; 5 min after its deadline (`bypassGrace`) it passes as
`LegPass.bypassed` — the dead-tag hatch, paid for with one full ring.
- **Three re-rings per morning** (`maxReRings`). A window missed with none
left ends the session as `failed`, silently. This is the agreed cap and the
known weakness: three rings of misery buy silence.
- The Dart tick also rings a deadline the native alarm should have fired
(20 s grace) — ringing twice is harmless, missing it is not.
Everything is **persisted after every change** (`session_store.dart`,
`session.current`) and driven by wall-clock instants, because a re-ring
replaces the whole Flutter engine and resumes from the store.
## Leaving the app, and coming back
The checklist lives in `AlarmActivity` (NFC reader mode and the kept-on
screen are asserted there), and the launcher starts `MainActivity`. Until
2026-09-17 a home gesture or a recents swipe therefore lost the screen for
good: the re-ring still fired, but the app opened on the home screen with no
way back to the leg. Now **every launch while the morning is live lands in
`AlarmActivity`**, and the home screen is unreachable until the session is
over:
- `MainActivity.resumeMorning()` runs in `onCreate` *and* `onResume` (the
activity is `singleTop`; a warm instance never re-runs `onCreate`), before
any Dart and before the permission prompt — a permission dialog must never
come up over a ring. It starts `AlarmActivity` with the `route` extra and
finishes itself.
- It decides natively, from `SessionNotice.kt`: a cache Dart rewrites on
every leg change (`updateSessionNotice`, always paired with `armReRing` in
`session_notice.dart`) holding the session's **date** and the leg label.
A cache dated any other day is ignored, never resumed — the phone dying
mid-morning must not open a dead checklist the next evening. Flutter's
own preferences file is deliberately not parsed from Kotlin.
- **A sounding ring wins.** `AlarmService.running` routes the launch — and
`AlarmActivity.getInitialRoute()` — to `/ring` whatever the extra says,
so a swiped-away ring reopened from the launcher gets the dismiss
sequence, not the home screen or a checklist over the noise.
- **An ongoing notification** ("Morning session — Tap the bathroom tag",
counting down to the re-ring) is one tap back to the leg. Silent channel,
`setOnlyAlertOnce`, native chronometer, so Dart posts it per leg, not per
tick. `finishSession` is the only thing that cancels it. The launcher
redirect is the guarantee; the notification is the convenience.
- `main_session_probe.dart` asks `morningLive` before its test ring, so a
relaunch of the probe during a session resumes rather than rings.
## History and sync
Finished sessions go to `session.history` (30 kept). The home screen shows
the last seven (`home_history_card.dart`) with weight deltas. The record
rides on the synced `alarm.json` like the ring tags do
(`session_sync.dart`): `session_tag_ids`, `morning_sessions` (14),
`latest_weight_kg` (`{date, kg}`), `latest_energy` (`{date, level}`) and
`current_session` — the live session while one runs, `{}` once it is over.
The PC reads the two numbers with `python -m wake_alarm._weight` /
`_energy` (Firebase only, same device discovery as the alarm); diet-guard's
`sync` imports the weight lazily for its protein target. The PC alarm parser
ignores every field it does not name. Sessions merge per date, newest
`updatedAt` wins, so a reinstall gets its history back; `current_session` is
never applied from a peer — a live session in history would stop
`SessionHandoff.afterDismiss` starting the morning it belongs to.
**The session is published twice**: once when it starts (`SessionScreen._init`,
strictly after the session is saved and on screen — a publish racing the load
stages nothing, and the PC would then lock an honest morning) and once when
it finishes. That is what lets the PC tell "started, not finished" from
"never started" and defer the workout and LeetCode locks only while the
morning is actually being earned: **`DOCS-morning-session-pc.md`**.
## Gotchas — each one cost a real run
- **Route replacement runs the new screen's `initState` before the old
screen's `dispose`.** The ring screen's dispose used to clear the NFC
handler the session had just registered, so the session never heard a tag
(Pixel, 2026-09-16). `AlarmScheduler.clearNfcListener` now clears only if
*that instance* registered the handler. The emulator harness gives each
screen its own instance for the same reason.
- **Android replays `BOOT_COMPLETED` to a force-stopped app on its next
launch.** After `am force-stop` during a test, a plain launch delivered
BOOT_COMPLETED (`WakeAlarmBoot` log), `restoreReRing` re-armed a
nine-minute-old deadline, and the phone rang in the evening with no session
running. A stored instant in the past is now dropped, never fired.
- **`ValueKey<int>(syncEpoch)` twice in one `Column`** — the history card and
the presence line — mis-reconciled silently in release and painted the old
presence element in the card's slot. Keys in one child list must differ.
- **The steps stage's 2-minute floor** now applies only under bypass (no tag
proved the walk). On the normal path tag 1 has already banked the steps,
so the floor was two minutes of ringing nothing could shorten.
- **`developer.log` is invisible in release logcat.** Session and challenge
logs use `debugPrint` (`WakeAlarmSession:`, `WakeAlarmRing:`), which is
what the emulator harness and a bad morning are debugged from.
- The volume ramp is ten minutes to full, not one.
## Testing it without a bathroom
`lib/main_session_probe.dart` runs the real app on `FileDrivenScheduler`
(`lib/probe/`), which replaces NFC and the step count with files under
`/sdcard/Android/data/com.kuhy.wake_alarm_sync/files/`.
`phone_app/scripts/emu_morning.py` drives it:
```sh
flutter run -d emulator-5554 --debug -t lib/main_session_probe.dart > run.log
scripts/emu_morning.py --log run.log dismiss # ring1, 30 steps, ring2, answers
scripts/emu_morning.py energy 3 # one of the five chips
scripts/emu_morning.py weight 72.4
scripts/emu_morning.py tag bath # then wait 8 min, tag bath again
scripts/emu_morning.py home; scripts/emu_morning.py launch # back on the leg
scripts/emu_morning.py rering # the deadline broadcast, now
scripts/emu_morning.py --log run.log dismiss # resumes at the same leg, 1/3
scripts/emu_morning.py tag ward; scripts/emu_morning.py tag desk
```
Verified this way on 2026-09-16 (API 36 AVD): the whole morning including a
re-ring and the resume; on 2026-09-17 the home-and-relaunch round trip on a
leg and during a ring. `flutter build apk --debug --target`
produced an APK that ran `main.dart` instead; `flutter run -t` did not.
The phone remains the only test of the AlarmManager deadline with the
screen off and the app swiped away.

249
DOCS-phone-alarm.md Normal file
View File

@ -0,0 +1,249 @@
# The phone half — how it rings, and what breaks it
Split out of `AGENTS.md` to keep that file under the repo's 250-line
gate. Read this before changing anything under `phone_app/android/` or
the ring/dismiss path in `phone_app/lib/`.
## Hand-written Kotlin, one MethodChannel
`phone_app/` is no longer just a time picker. It arms and rings its own alarm
(items 1/4) through five Kotlin files behind **one** MethodChannel
(`AlarmChannel.kt`) on `MainActivity`/`AlarmActivity`:
`AlarmScheduler` (arm/cancel/re-arm) · `AlarmReceiver` (fires) ·
`AlarmService` (foreground service: wakelock, sound, vibration, full-screen
intent) · `AlarmActivity` (dismiss screen over the lockscreen) ·
`BootReceiver` (re-arm after reboot) · `StepCounter` (item 3 fallback).
Free/sick days and the pre-alarm pool sync: `DOCS-sick-days.md`.
**Never replace any of this with a pub plugin.** The stack is AGP 9.0.1 /
Gradle 9.1 / Kotlin 2.3.20; a plugin that will not compile against AGP 9 breaks
the build outright rather than degrading, and this is the one path that must
not break. Third-party plugins are acceptable only for droppable extras —
never for the ring path, and never for NFC or the step counter, both of which
the dismiss sequence now hard-depends on.
Things that are a hard crash or a silent no-ring, not a warning:
- **`STREAM_ALARM` is load-bearing — but it does not beat *every* DND mode.**
`AlarmService` sets `AudioAttributes.USAGE_ALARM`; never
`USAGE_MEDIA`/`STREAM_MUSIC`, which would be muted exactly when the alarm
matters most. Measured on the Pixel 6a (2026-08-27), the muted-stream mask
from `dumpsys audio` differs by zen mode:
| DND mode | `zen_mode` | `STREAM_ALARM` |
|---|---|---|
| priority (`ZEN_MODE_IMPORTANT_INTERRUPTIONS`) | 1 | **not muted** (mask `0x1a6`) |
| total silence (`ZEN_MODE_NO_INTERRUPTIONS`) | 2 | **MUTED** (mask `0x9be`) |
The confirmed ring was under **priority DND** (`zen_mode=1`): player
`state:started`, `usage=USAGE_ALARM` → `STREAM_ALARM(4)`, `mutedState:none`.
**Total silence mutes the alarm stream system-wide**, and no audio flag
escapes it — so "ignores DND" means priority DND, not total silence. If that
gap ever matters, the fix is a zen-policy check at arm time, not an audio
change. `raiseAlarmVolume()` does run on this hardware (observed raising
`oldIndex:0` → 7, no `SecurityException`), which recovers a stream turned
down to zero but not one muted by total silence.
- **The ring fades in; the stream still goes to max.** Two different knobs,
and merging them trades a gentle start for a silent alarm.
`raiseAlarmVolume()` fixes the *system stream* — a stream left at 0 would
silence the alarm outright. `startVolumeRamp()` climbs the *player's own
gain* from `RAMP_START_GAIN` (0.04) to full over `RAMP_DURATION_MS` (60 s),
quadratically, because perceived loudness is not linear in amplitude.
Measured on the Pixel 6a (2026-08-31) from `dumpsys media.audio_flinger`
track gain: −28 dB at 3 s, −21 dB at 15 s, −12 dB at 30 s, 0 dB at 62 s.
Every step re-reads `player`, and `stopSound()` drops the queue before
releasing it, so a dismissal mid-ramp cannot touch a released `MediaPlayer`.
- **`android:foregroundServiceType="mediaPlayback"` must be on the `<service>`
in the manifest AND passed to `startForeground()`.** Omitting either is a
hard crash the moment the alarm fires on API 34+ — and it is invisible on an
API 33 device, which is why the API 36 AVD exists.
- **`setAlarmClock()`, not `setExactAndAllowWhileIdle()`.** It is Doze-exempt,
needs no `SCHEDULE_EXACT_ALARM` prompt (`USE_EXACT_ALARM` covers an
alarm-clock app), and it is what grants the receiver its foreground-service
exemption when it fires with the screen off.
- **`FLAG_IMMUTABLE` on every `PendingIntent`** — mandatory since API 31; a
mutable one throws at arm time.
- **`canUseFullScreenIntent()` gates, it does not warn.** From API 34 the grant
can be revoked; `_armOwnAlarm()` in `home_screen.dart` refuses to report
success and tells the user to grant it, because without it the alarm posts a
notification the sleeping user never sees.
- **`min/target/compileSdk` are pinned explicitly** (28/36/36) in
`android/app/build.gradle.kts`. They used to be delegated to the Flutter
Gradle plugin, so there was no floor to reason about. minSdk 28 is what makes
`android:showWhenLocked`/`turnScreenOn` plain manifest attributes.
**Re-arm has three hooks, and needs all three.** `LogStore` has **no change
stream** (the plan claimed one; it does not exist in `crdt_sync_dart`), so the
picker's save is only one of them: `main()`'s startup `rearm()`,
`BOOT_COMPLETED`, and the dismiss handler. Drop any one and the alarm rings
once and then silently stops.
**The phone rings daily**, matching the PC's `ALARM_DAYS` (all seven days).
The two are deliberately not synced — a shared day set is item 8's shape, and
diverging defaults would have the halves firing on different days.
`lib/services/challenge.dart` owns the four challenge kinds. **Every kind
must keep its prompt on screen until it is answered.** A memorise-then-hide
kind existed once and was deleted outright: the ring screen is reached by
walking in from another room, so anything already gone by the time the user
looks at it is unsolvable, not merely hard.
Room proof is now a **strict, latched sequence**, owned by
`lib/services/dismiss_gate.dart`:
tag 1 -> 25 steps + 2 min -> tag 2 -> 3 challenges
Every stage is required, they must happen **in that order**, and a stage once
passed **never reverts** — an unknown or out-of-order tag is ignored rather
than clearing progress. `room_proof.dart` answers only "did this one check
pass just now"; the ordering lives in the gate. Two *distinct* tags are
required: the same id in both slots is refused at registration, because one
tag satisfying both stages removes the walk that is the entire point.
Steps still require elapsed time as well as a count — the phone is stationary
while you walk to it, so a bare count can be faked by shaking it in bed. That
pair is unchanged from when steps were a fallback; it is only its role that
changed, from alternative to prerequisite.
**The bypass is the only fallback, and it is deliberately narrow.** After
`DismissGate.bypassAfter` (5 minutes) of ringing, or immediately when NFC is
off or fewer than two distinct tags are registered, the two *tag* stages are
skipped and the challenge count rises to 6. **The walk is never skipped** —
jumping straight to the challenges would let someone lie in bed for five
minutes and answer questions without standing up, which is weaker than the
gate this replaced. Without some such hatch a dead tag at 06:00 leaves an
alarm that literally cannot be switched off.
## Home presence — the alarm knows where it is
Away from home the two tags are screwed to walls in another city, so the
sequence is unsatisfiable. `HomePresence.read` (Kotlin) reports raw
observations and `lib/services/home_presence.dart` decides; away skips the two
*tag* stages and **keeps the normal 3 challenges**. The walk still counts.
- **Never "modernise" `WifiManager.getConnectionInfo()`.** It is deprecated at
API 31 in favour of `NetworkCapabilities.getTransportInfo()`, and that
replacement does not work here: the *synchronous*
`ConnectivityManager.getNetworkCapabilities()` redacts every
location-sensitive field, so `transportInfo` is null and the BSSID silently
vanishes. Measured on the Pixel 6a (API 36, 2026-08-31) — connected to a
known AP, fine location granted, location services on — the capabilities
route returned `ssid=null bssid=null` while the GPS fallback quietly covered
for it. Un-redacted `transportInfo` needs a `registerNetworkCallback`.
- **A redacted BSSID is `02:00:00:00:00:00`, not null and not an error.**
Android returns it when fine location is missing *or* location services are
off. Untreated it is a valid-looking MAC that never matches, so every
morning reads "away" and the ritual silently stops happening.
- **Unreadable means away** — the user's explicit choice. A revoked permission
therefore weakens the alarm rather than breaking it loudly, which is why
`HomePresenceLine` puts the verdict *and its cause* on the home screen.
**Unconfigured is not unreadable:** an install that never captured a home
keeps the strict sequence, or shipping this would have deleted the gate.
- **Presence resolves before the missing-tags bypass** (`ring_startup.dart`).
Both skips latch one-way, so whichever fires first fixes the count; the
other order would give every away morning with NFC off the punitive 6.
Equally, `activateBypass()` is refused after `activateAwayProfile()` — the
ring screen's 5-minute timer fires unconditionally and an away morning
crosses 5 minutes routinely.
- **Registration passes `withFix: true`; the ring screen does not.** A Wi-Fi
answer short-circuits GPS, which is what makes the verdict instant at home —
but it also meant capture never recorded a coordinate, so the GPS fallback
could only ever be configured with Wi-Fi off, i.e. never.
- **BSSIDs are a list, and the SSID matches too.** A dual-band router answers
to a different BSSID per band and the phone roams overnight; one stored
address would call a band switch "travelling".
- The read runs from `AlarmActivity` (foregrounded, so while-in-use location
suffices). **Do not move it into `AlarmService`** — that would mean
`foregroundServiceType="mediaPlayback|location"` plus
`FOREGROUND_SERVICE_LOCATION`, on the one path that must not break.
**`ringNow` + `lib/main_ring_probe.dart` are a deliberate manual test
handle**, the phone-side equivalent of `wake-alarm.service` on the PC: the
normal arm path needs a sync backend connected, so there is no other way to
fire the ring on an emulator. The probe runs the **real** app widget and
pushes `/ring` — an earlier version rendered its own UI and so proved nothing
about the route. `flutter build apk` uses `lib/main.dart`, so the probe is
never the shipped entrypoint; `ringNow` is reachable only over this app's own
channel and arms nothing. Do not "clean these up" without replacing the
capability.
Emulator: `wake_alarm_api36` (Pixel 6a profile, API 36). The SDK tools are at
`~/sdk/Android/Sdk` but **not on PATH** — export `ANDROID_HOME` and add
`cmdline-tools/latest/bin`, `emulator` and `platform-tools` yourself. The
phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so
`phone_deploy.sh` needs `--release` or the install fails with
`INSTALL_FAILED_UPDATE_INCOMPATIBLE`.
**Never pass `--build-number` by hand**, including for the probes: use
`phone_deploy.sh <app> --release --target lib/main_ring_probe.dart` and let it
pick. Android compares versionCode only upward, so a hand-picked number puts
the phone above what CI will mint and locks CI out until the commit count
catches up — the only other escape is an uninstall, which wipes the sync
identity (the tags and home come back from sync since 2026-09-11, see
below). This happened on 2026-08-31 (probe
builds at 200/201 stranded the phone at 207 against a ceiling of 156).
`.versioncode-offset` at the repo root is the recovery valve, read by **both**
`release-apk.yml` and the local gate so the two can only move together; it is
currently 101. `hooks/build_number_guard_pretool.sh` now blocks the bypass.
**The ring screen must close itself on dismiss.** `AlarmActivity` handles
`closeRingScreen` (the shared `AlarmChannel` holds `applicationContext` and
cannot finish an activity). Without it the dismiss screen stays up over the
lockscreen forever — back is disabled by design in both halves — and the live
instance would carry a satisfied room proof and the solved answer into the
next ring.
## Tags and home location survive a reinstall
Both used to live only in SharedPreferences, and a reinstall on 2026-09-11
lost them. They are properties of the flat, not of one install, so
`lib/services/settings_sync.dart` carries them as two extra per-field entries
on the same `alarm.json` record the PC reads (`nfc_tag_ids`,
`home_location`); the PC parser reads only the hour/minute fields and ignores
the rest. `AlarmSyncService.pushWith` is a real `syncLog` tick now — pull every
device directory, merge per field by HLC, push — and `AlarmPublisher.publish`
wraps it: stage local edits → sync → apply the winners back into prefs. That
last step is the restore. Verified 2026-09-11 on a fresh `wake_alarm_api36`
install: both tags and the home appeared with zero taps after Google sign-in.
- **Last-writer-wins by wall time, from the local `editedAt`** stamps
(`roomProof.editedAt`, `homeLocation.editedAt`). A value applied *from* the
log is stamped with the log's wall time, and comparisons are on wall time
only — comparing counter/node id on that tie would push the same value
straight back every tick.
- A value from before stamps existed is staged at epoch+1 ms: pushed when
nothing else is known, loses to any real edit.
- **Registering a tag pushes on the Back to the home screen** — the Settings
pop now runs `_syncToPc()`, not just `_loadSyncState()`. Without that the
push waited for the next cold start, which is the same "it vanished" again.
- `setLocal` merges into the existing record; a whole-record upsert there
would drop the settings fields from every push. `HomeBody.syncEpoch`
remounts the presence line after each sync so a restored home shows at once.
- The emulator is a real peer: its device directory outranks the phone by
HLC while it exists. Delete `wake-alarm-sync/devices/<emulator-uuid>` after
a restore test.
## The home screen's startup order, and the ring's clock
Moved here from `CLAUDE.md` on 2026-09-16 for its line cap; nothing below
has changed.
**`HomeScreen.initState` must stay strictly sequential.** It runs
`_applyPolicy()` → `_loadSyncState()` → `_syncToPc()` through one
`_bootstrapSync()`, because the last reads what the first two write and
`AlarmPublisher.publish` takes the service as a *parameter* — captured by
value, so a later assignment can never reach it. Running them concurrently
(as they once were) meant the startup publish always passed `null`, and since
that was the only publish site, **nothing published for three weeks** while
the PC honoured a record from 2026-08-09. `_pickEarlier` must publish too, or
the one schedule edit the app offers never reaches the PC.
Relatedly: `publish()` reports a missing *backend* and a missing *store*
differently on purpose. One string for both is what made the above look like a
configuration the user had never done, while Firebase was connected the whole
time.
`RingScreen` takes an injectable `clock`. `Stopwatch` reads the wall clock,
which `tester.pump()` does not advance, so without that seam no widget test
can reach the two-minute floor or the five-minute bypass.

39
DOCS-ramp.md Normal file
View File

@ -0,0 +1,39 @@
# The wake-time ramp ("cooking the frog")
The alarm starts at 08:00 and moves one **earned** minute earlier at a time,
down to a permanent 07:00. Owned entirely by the phone
(`phone_app/lib/services/alarm_ramp.dart`, `ramp_progress.dart`).
## The rule
- A **Monday, Friday, Saturday or Sunday** whose alarm rang and was dismissed
that same day earns one minute (`RampProgress.recordDismiss`, called from the
ring screen's dismiss before it re-arms).
- **Tuesday–Thursday** (`freedays.WORKDAYS`) earn nothing and ring at the time
of the most recent non-workday: a minute earned on Monday first shows on
Friday.
- A **free day** never rings, so it earns nothing. A **missed** alarm (rang,
never dismissed) earns nothing.
- Ring time for day D = 08:00 − |earned dates before the latest non-workday
≤ D|, floored at 07:00.
## Why a set of dates, not a counter
The earned dates are a grow-only set: each date counts once, so a re-run, a
duplicate sync or a double dismiss cannot move the alarm twice, and nothing can
run it away. It rides the synced `alarm.json` record (`settings_sync.dart`,
field `ramp_earned_dates`) as a union, so a reinstall gets every minute back.
`rampSeedDates` holds the three mornings earned before dates were recorded
(2026-09-25/26/27).
## Where it is *not*
The PC no longer computes a ramp: it trusts the time the phone publishes,
clamped to ≤ 08:00, and falls back to 08:00. The Kotlin side has no ramp
either: the alarm only moves when a Dart dismiss earns a minute and re-arms, so
the native re-arm after a free day, a missed ring, a boot or the watchdog is
already the right time by re-using the stored one.
`workdays` in `alarm_ramp.dart` and `STICK_DAYS` in `WorkdayStick.kt` are
literal copies of `freedays.WORKDAYS`;
`wake_alarm/tests/test_workday_mirrors.py` fails when either drifts.

136
DOCS-sick-days.md Normal file
View File

@ -0,0 +1,136 @@
# Sick days — the phone picker, the silent ring, the pre-alarm sync
The pool itself is `~/src/utils/sickdays` (Python): every day is normal until
it is marked sick, today or later only, no cap, no reason, never also a free
day. Read its README for the rules and the RTDB wire format. This file covers
the phone half.
On a sick day the phone does not ring, the stick does not judge the day, and
nothing ring-related is recorded -- **unless the day keeps the alarm**.
Since sickdays 0.2.0 a sick day carries a per-locker `keep` set (README
"keep (0.2.0)"): a kept locker behaves exactly as on a normal day, every other
one stands down. This app is the `alarm` locker (ring, PC fallback ring, RTC
self-wake, missed-alarm penalty / stick, morning routine). It is **not** a free day: separate pool,
separate RTDB node (`sickdays-sync/devices`), separate native cache, separate
screen, and every log line and event says `sick_day`.
## Where things are
| | |
|---|---|
| Picker | `phone_app/lib/screens/sick_days_screen.dart` (+ `sick_days_body.dart`, the shared `day_calendar.dart`); the sick-face icon on the home screen |
| Rules, Dart port | `phone_app/lib/services/sick_day_pool.dart`: records `{state: sick/cleared, actor, keep}`, one HLC per mark/clear, never a tombstone; keep read rules in `sick_day_keep.dart` |
| Per-locker sheet | `phone_app/lib/screens/sick_day_sheet.dart` (+ the dot in `day_cell.dart`) |
| Sync | `phone_app/lib/services/sick_day_sync.dart` (shared tick: `day_pool_sync.dart`), Firebase only |
| Ring path | `android/.../SickDays.kt` (+ `DayCache.kt`), read in `AlarmReceiver` through `RingDecision.kt` |
| Stick | `StickCheck.kt`: verdict `sick_day`; the streak skips sick days like free days |
| Pre-alarm sync | `PoolSyncAlarm.kt`, `PoolSyncSchedule.kt`, `PoolSyncEngine.kt` → `poolSyncMain` → `day_pool_refresh.dart` |
## The picker
Same Monday-first grid as the free days, in `cat-2` blue (`DayMarkColors`
in `ui/theme.dart`) rather than the accent gold, under its own title and
icon. **Today is tappable** (unlike the free-day grid); the past is inert.
No count, no reason.
Tapping a normal day opens a bottom sheet: one switch per locker (Workout
lock, LeetCode, Book, Diet, Wake alarm), **all off** (off = stands down), and
"Mark sick". Tapping a sick day reopens it with the day's switches, "Save"
and "Clear sick day". Save is a keep-only edit: it re-stamps `keep` and
`actor`, never `state`, so it cannot re-assert "sick" over a concurrent
clear; an unchanged Save writes nothing. A sick day keeping any locker shows
a dot (in `on-fill` on the `cat-2` cell) and a `Kept: ...` line in the list.
## A date is never in both pools
Each picker syncs the *other* pool on open and refuses a date it holds, naming
the pool: `2026-10-20 is a free day — release it in Free days first.` /
`2026-10-20 is a sick day — clear it in Sick days first.` If the other pool
cannot be opened, every mark is refused ("could not check" never counts as
"not in it"), as `sickdays`' `ConflictCheckUnavailableError` does.
`free_day_pool.dart` itself is untouched: the check lives in the callers,
exactly as the Python README prescribes.
## The ring
**The native cache holds only the days on which the alarm stands down** --
sick and `alarm` not kept, past days included (`SickDaySync.publishToNative`
-> `SickDayPool.standDownIsoDates(SickLocker.alarm)`, the one place the keep
set is applied for Kotlin). A sick day keeping the alarm is simply absent, so
it rings, the stick judges it and the stakes card shows its stakes; Kotlin
never sees the keep set. The pre-alarm sync goes through the same publish.
The `Alarm cache:` line on the picker reads this cache back, so a kept-alarm
sick day is (correctly) not listed there.
`AlarmReceiver` asks `RingDecision.skip(free, sick)`. On a sick day it logs
`sick day: not ringing; re-armed for tomorrow`, appends `alarm_fired` with
`reason: "sick_day"`, re-arms and returns: no `AlarmService`, no
`RingWatch.markFired`, no headless `ring_started`. The stick's checks at
A + 15, boot and watchdog return `sick_day` for that date, so there is no
miss, no streak change and no lockdown; the stakes card says
`Sick day — no alarm, nothing at stake.`
**Fail closed.** An unreadable or missing cache is "not a sick day"
(`DayCache`), so the phone rings, matching `sickdays.is_sick_day()`.
## PC → phone before the ring, with the app closed
`sickdays add` on the PC writes locally; its sync timer pushes to RTDB. The
phone pulls from RTDB. A **pre-alarm sync** does that pull with no screen
open, so a PC mark reaches the native cache before the ring:
- `PoolSyncAlarm` arms an allow-while-idle exact alarm (request code 1006;
inexact fallback if exact alarms are refused, never `setAlarmClock`, so it
is never shown as the next alarm) at the earliest of **21:00** and
**A − 30 min**. It is armed from `AlarmScheduler.schedule()`, the funnel
every arm path uses (boot included), and re-arms itself.
- `PoolSyncReceiver` holds the broadcast open with `goAsync()` (it keeps the
process out of the cached/frozen state) while `PoolSyncEngine` runs a
headless Flutter engine on `poolSyncMain`. That pulls **both** pools and
rewrites both native caches through `AlarmChannel`. Dart says `done`; a
25 s timeout stops it regardless (the broadcast limit is 60 s).
- The ring decision stays a cache read. A network call inside
`AlarmReceiver` would spend the alarm-clock exemption that lets
`AlarmService` start, and a missed ring cannot be failed closed.
The guarantee is precisely this: **a day marked on the PC, and pushed by its
sync timer before 21:00 (or before A − 30), is honoured if the phone has
network at that slot.** The evening slot is the dependable one. The morning
slot usually runs in Doze, where an allow-while-idle alarm gets only a short
network window. If both fail, the cache keeps its last sync and the phone
rings. Launching the app or opening either picker also syncs both pools. The free-day pool rides along, which closes the "PC mark overnight can
miss the ring" gap `DOCS-free-days.md` used to admit.
Known edge: a sick mark that lands *after* the morning was dismissed does not
stop that session's re-rings (`REASON_RERING` is not gated); no pre-alarm
sync runs between A and the session's end anyway.
## Checks
- Dart: `test/services/sick_day_pool_test.dart` (rules + a log written by the
real Python package), `sick_day_sync_test.dart`, `day_pool_refresh_test.dart`
(an RTDB log from the PC reaches `setSickDays` through `runHeadlessPoolSync`),
`test/sick_days_screen_test.dart`, `test/free_days_sick_conflict_test.dart`,
`test/services/today_stakes_sick_test.dart`.
- Kotlin (JVM, `android/app/src/test`): `DayCacheTest`, `RingDecisionTest`,
`PoolSyncScheduleTest`, `StickCheckSickTest`. Run with
`cd phone_app/android && ./gradlew :app:testDebugUnitTest`, after one
`flutter build apk` has written `gradlew` and `local.properties`.
- Keep: `test/services/sick_day_keep_test.dart` (wire, read rules 1-5, a
keep edit after a future PC tick, concurrent clear), `test/sick_day_sheet_test.dart`,
`test/sick_day_apply_test.dart`.
- Cross-language, both ways: `phone_app/scripts/sick_days_interop/check.sh`.
Dart writes (incl. keep and a keep-only edit) and Python 0.2.0 reads and
replays it; then Python writes (incl. a 0.1.0 record with no keep, a stale
keep and a malformed one) and Dart's verdicts are compared with Python's.
Needs `SICKDAYS_PYTHON` or the sickdays venv; Python runs with `HOME`
pointed at a scratch dir.
## Do NOT
- Don't fold sick days into `FreeDays`/`isFree`, or log them as `free_day`.
- Don't sync inside `AlarmReceiver`. Don't tombstone a date to clear it.
- Don't add a count, a reason prompt or a warning. There is no budget.
- Don't put a non-alarm-stand-down date in the native cache, and don't teach
Kotlin the keep set: filter in `publishToNative` only.
- Don't re-stamp `state` on a keep edit.

90
DOCS-vmbox.md Normal file
View File

@ -0,0 +1,90 @@
# Testing wake_alarm in a disposable VM
`scripts/vmbox/harness.sh` is this repo's default gate for the shell and
system pieces — `install.sh`, the systemd units, `shutdown-wrapper.sh`, the
power-key inhibitor and the re-fire path. It provisions a throwaway Arch guest
(`~/src/utils/vmbox`), installs this repo into it exactly the way a real machine
does, runs the cases, and returns a host-side verdict.
```bash
bash scripts/vmbox/harness.sh # the gate
bash scripts/vmbox/harness.sh --window # also screenshot the real alarm window
bash scripts/vmbox/harness.sh --keep # leave the sandbox up to poke at
```
Exit codes: `0` everything passed, `1` a case failed, `2` the harness itself
could not run.
## Why a VM at all
Every one of these touches something a test on the host cannot safely touch:
`install.sh` writes systemd user units, a sudoers entry and
`/usr/local/bin/shutdown`; the shutdown wrapper's whole job is to hibernate the
machine; the inhibitor takes a logind lock on the power button. Getting any of
those wrong on the host is not a failed test, it is a broken machine.
## What it actually covers
| Case | What a pass means |
|---|---|
| `imports-from-system-python` | `wake_alarm` and `gatelock` import under `/usr/bin/python3`, the interpreter the units really use — not a venv |
| `trigger-timer-enabled` | `wake-alarm-trigger.timer` is enabled after `install.sh`. Writing the unit file is not the same as systemd running it, and a timer that is present but disabled fails silently every morning |
| `trigger-dry-run` | one tick reaches a decision without crashing |
`install.sh` itself running to completion is a precondition of all of them: if
it fails, the harness stops with exit 2 and dumps the log.
## What it cannot cover — do not read a pass as covering these
- **The phone.** The entire dismiss sequence — two NFC tags, the step counter,
the challenges, the 5-minute bypass — lives in `phone_app/` and is verified
on the Pixel 6a, never here. This harness knows nothing about it.
- **The bootloader and the real firmware.** The harness guest is BIOS/GRUB
(`vm new --uefi` exists since 2026-10-01, OVMF, but is not this board's
firmware). `vm wake` emulates the RTC power-on from poweroff/hibernate, so
the arming and the boot/resume units are testable; whether *this* board
wakes is host-only (S4 verified 2026-10-01, `DOCS-wake-enforcement.md`).
- **The ring's audio.** The guest gate plays to `snd-dummy`; the speakers,
and a card held busy by the user's PipeWire, are host-only.
- **A green run is not host verification.** Report it as "passed in vmbox, not
verified on the host", always.
## Guest provisioning, and why
The stock guest image is missing exactly one thing this package needs:
- **`tk`** — without it `import tkinter` fails with `libtk8.6.so: cannot open
shared object file` and the alarm cannot open its window at all.
`gatelock` is not installed separately: it is a `pyproject.toml` dependency, so
`install.sh`'s `pip install -e` pulls it from its pinned tag. That is
deliberate — the harness runs the real install path rather than a hand-rolled
approximation, so a break in `install.sh` fails the gate.
## Two traps worth knowing before editing the harness
- **`vm run` does not propagate the guest command's exit code.** It reports the
*VM's* verdict (clean / dirty / rebooted / crashed / hung), so a guest script
exiting 1 still returns 0 on the host. A gate built on that exit code fails
*open*, which is worse than no gate. `guest_cases.sh` therefore prints
`ALL-CASES-PASSED` only when every case passed, and the harness greps for it.
- **`vm share` and `vm repo` key off the path's basename**, so the repo path
must be absolute and symlink-resolved. A relative `scripts/vmbox/../..`
makes rsync write into `/home` and fail with permission errors that look
like a guest problem.
## Cases this VM found that the host could not (historical)
Both were live bugs, both passed the unit suite:
1. **The inhibitor claimed a block it did not have.** `Popen` succeeding only
means the binary launched; logind can still refuse. The alarm logged "power
key inhibited" while `systemd-inhibit` had already exited 1.
`take_power_key_inhibitor()` now waits briefly and confirms the child
survived.
2. **An unsigned session record was written and then rejected on read.** With
no HMAC key on the machine (`/etc/gatelock` absent, as in the guest),
`verify_entry_hmac` returns False, so every session record was unreadable
and the power-off defence silently did not exist. An entry with *no* `hmac`
field is now honoured with a loud warning, while a *present but wrong*
signature is still rejected — that one really is tampering.

217
DOCS-wake-enforcement.md Normal file
View File

@ -0,0 +1,217 @@
# Wake enforcement v2 — PC fallback alarm, immediate stick, escape hatch
Agreed with kuhy on 2026-10-01. This file is the **contract** between the
phone app, the PC package, focus-owner (`~/src/phone-focus-mode`) and the
daily audit. Change a name here and in every reader in the same commit.
## Why
The carrot (`DOCS-morning-session-pc.md`) pulls only on days the PC is used
in the morning — Fri–Mon. On Tue/Wed/Thu kuhy leaves for work, so the only
lever is something that bites *today*. Two holes made skipping cheap:
1. **A phone switched off before the alarm escaped everything.**
`RingWatch.markFired` never ran, so `WorkdayStick` saw no abandoned ring.
2. **Nothing rang if the phone was off.** The PC's waking role was deleted on
2026-08-30; this brings back exactly one piece of it because the phone
*cannot* ring while powered off — the reason AGENTS.md asks for.
## Behaviour
### PC fallback alarm (every ringing day)
Let `A` be today's alarm (`_sync.get_alarm()`, clamped ≤ 08:00 like the
trigger). Not on a free day, not on a sick day (below). Per-minute tick, `A-5min .. A+45min`:
| condition (first match wins) | action |
|---|---|
| escape recorded for today, or a session started today | stop / do not ring |
| ring already ran 30 min today (`FALLBACK_RING_CAP`) | never again today |
| `now ≥ A + 2 min` and no `ring_started` for today | ring — `phone_silent` |
| `now ≥ A + 15 min` (`SESSION_NONE_GRACE`) | ring — `no_session` |
A ring stops on: session start, escape, or the 30-min cap. Firebase
unreachable counts as "no ping, no session" (fail toward ringing) and is
logged as `firebase_unreachable`. While ringing, stop conditions are polled
every 20 s.
**Sound.** 100 %, unmuted, a tone that rises over the first 60 s.
- Active graphical session on seat0 → user PipeWire (`wpctl` + `pw-play`).
- Otherwise (night lockdown: lightdm masked, nobody logged in; kuhy is not in
`audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
to the speakers' card (`ALC897 Analog`, card name `Generic_1`) via `aplay`.
### PC wakes itself (nights before Tue/Wed/Thu)
`wake-alarm-rtc.timer` (evenings + on boot) arms the RTC for
`A − 10 min` of the next stick-day morning with
`sudo -n /usr/sbin/rtcwake -m no -t <epoch>` (already NOPASSWD). The alarm
lives in CMOS, so it survives however the PC goes down.
`~/.config/wake_alarm/pc_wake.json` `{"mode": "hibernate" | "poweroff"}`:
- `hibernate` (default): a logind drop-in makes the **power key** hibernate.
Verified on the host 2026-10-01: two `rtcwake -m disk` cycles resumed
29–44 s after the alarm (FADT: "RTC can wake system from S4 = 1").
A typed `shutdown` stays a real poweroff.
- `poweroff`: no logind change; relies on the firmware waking from S5.
Unverified until the host S5 test runs.
### Phone stick (Tue/Wed/Thu, not free days)
A **miss** = no dismiss by `A + 15 min` and no escape for today. Detected by
an exact alarm at `A + 15` *and* at boot (stored alarm `A` passed by ≥ 15 min,
not dismissed today) — the boot path is what closes hole 1.
Lockdown length stacks over **consecutive stick-day misses** (free days are
skipped, they neither break nor extend the streak; a dismissed or escaped
stick day resets it to 0):
| streak after this miss | locked through |
|---|---|
| 1 | today + 1 day |
| 2 | today + 2 days |
| n | today + min(n, 4) days (5 calendar days max) |
During a workday lockdown focus-owner applies its **lockdown allowlist**
(calls, SMS, Signal, maps, transit/ticket, banking + authenticator,
wake-alarm, todo) — narrower than the night list.
### Sick days (PC side, 2026-10-16)
A sick day (that does not keep `alarm`, see below) is a date in the shared `sickdays` pool (`~/src/utils/sickdays`):
uncapped, no reason, today or later, and **not a free day** -- its own pool,
its own reason strings (`sick_day` / `sick day`). On a sick day `D` (the
alarm's day, so the RTC asks about *tomorrow* the evening before):
| piece | on a sick day |
|---|---|
| fallback ring | never starts; a ring in progress stops (`stop_reason` `sick_day`) |
| RTC self-wake | not armed for `D`; an alarm we armed for `D` is disarmed (`rtc_skip` / `rtc_disarmed`, reason `sick day`) |
| trigger | `morning-routine.service` is not started (`sick day`), like a free day |
| workday penalty | never written for `D`; one *issued* on `D` before `D` was marked is deleted (`penalty_cancelled`, `cause: sick_day`) by the next `_session --refresh` or `_rtc --arm` |
| `morning_session.json` | unchanged: it only *grants* exemptions, and every locker stands down on a sick day by its own check |
| audit | RTC / up-by-A / ring / lockdown checks are n/a; a penalty for `D` on disk or a `lockdown_sent` for a miss on `D` is flagged |
All of it lives behind `wake_alarm/_sick.py`. **Fail closed:** an
unreadable pool, or `sickdays` not importable under `/usr/bin/python`, is
"not sick" -- enforcement runs.
**Sync.** The decisions read the local pool, and the act modes pull it from
Firebase first (`sickdays.sync_quietly()`), because the sickdays sync timer
alone cannot be trusted at the moment that matters: it is a monotonic
15-minute timer, paused during hibernate and with no `Persistent` catch-up,
so right after the RTC resume the pool can be an interval stale. Pulled:
`_rtc --arm` when the target is a stick day that is not free; the fallback
tick whenever it already goes to the network (`A-5 .. A+45`, and every poll
of a ring in progress, so a day marked sick mid-ring stops it); the day's
first penalty write. The trigger reads only the local file -- the fallback
has pulled from `A-5`. `--dry-run` / `--show` never pull (a pull rewrites
the pool file).
**Other readers of `workday_penalty.json`** (screen-locker, leetcode-guard)
must treat the file as void when **either** its `issued_date` is a day the
*alarm* stands down on (`sickdays.stands_down(sickdays.LOCKER_ALARM,
date.fromisoformat(issued_date))`) **or** its `penalty_date` is a day *their
own* locker stands down on (`stands_down(LOCKER_WORKOUT, ...)` for
screen-locker, `LOCKER_LEETCODE` for leetcode-guard). `issued_date` covers a
miss at 08:15 marked sick at 14:00 -- the deletion runs on the next RTC tick
(<= 15 min) or the next morning's refresh, and a reader must not depend on
that; the ring day belongs to the alarm switch, the penalty day to whatever
the penalty charges.
**Keeping the alarm (`sickdays` 0.2.0).** A sick day may keep lockers
(`sickdays add --keep alarm`). Everything in the table above is the single
`alarm` switch (`_sick.alarm_stands_down`): on a sick day that keeps `alarm`
the fallback ring, RTC self-wake, trigger, workday penalty (written, and not
retracted) and audit behave exactly as on a normal stick day.
**Phone, assumed name:** the phone's `alarm_fired` on a sick day carries
`data.reason = "sick_day"` (by analogy with `free_day`); the audit treats
it as not the morning's ring.
### Escape hatch (until 2026-10-15 inclusive)
Home screen button "That was a bug". Needs a typed reason ≥ 40 characters.
It lifts the phone lockdown, clears the streak, cancels today's PC penalty,
stops a ringing PC alarm, and writes everything into the incident report.
Unlimited uses — every use is listed at the top of that day's report.
After `escapeHatchLastDay` the button is gone (constant, not a setting).
### Stakes shown in the app
Home card: today's stakes (stick day or carrot day), the carrot cutoff, any
pending lockdown/penalty and the streak. Ring screen: one line. Every number
shown comes from Dart constants mirrored against the Python ones by
`wake_alarm/tests/test_stakes_mirrors.py`.
## Data contract
### Firebase — fields on the phone's `alarm.json` (`stageField`)
| field | value |
|---|---|
| `ring_started` | `{"date": "YYYY-MM-DD", "at": "<ISO-8601 with offset>"}` — set when the ring screen opens (Dart). |
| `escapes` | list, newest first, ≤ 30: `{"id", "date", "at", "reason"}` — `date` is the morning being excused. |
| `stick_state` | `{"streak": n, "locked_through": "YYYY-MM-DD" \| null, "last_miss": "YYYY-MM-DD" \| null}` |
| `phone_events` | list, newest first, ≤ 400 entries and ≤ 14 days: `{"at", "kind", "data": {…}}` |
### focus-owner broadcasts (signature permission `SIGNAL_LOCKDOWN`)
- `com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD` — extra `until`
(`YYYY-MM-DD`, inclusive). Missing extra = today (old senders keep working).
- `com.kuhy.focus_owner.action.LIFT_LOCKDOWN` — clears any lockdown now.
### PC files (`~/.local/state/wake_alarm/`)
- `events.jsonl` — every PC event (`_log_sink`), `event` key names below.
- `fallback_ring.json` — today's latch: `{"date", "started_at", "stopped_at",
"reason", "stop_reason"}`.
- `workday_penalty.json` — unchanged shape; not written for an escaped day
or a sick day, and removed when an escape arrives for the day it was
issued or that day is marked sick.
### Event names
Phone (`phone_events.kind`): `alarm_fired` (data: `reason` =
`daily`|`rering`|`free_day`|`sick_day` — only `daily` is the morning's ring),
`ring_screen_opened`, `ring_started_published` (data: `date`, `source` =
`alarm`|`ring_screen`), `dismissed`, `stick_check` (data: `trigger` =
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `lockdown_sent` (data:
`until`, `streak`), `lift_sent`, `escape_used`, `boot`.
`ring_started` is published twice over: a headless Dart engine started by
`AlarmReceiver` at the fire (so a full-screen intent downgraded to a heads-up
on an unlocked phone still counts) and the ring screen; first of the day wins.
The A+15 check uses `setExactAndAllowWhileIdle` (falls back to
`setAlarmClock` only when exact alarms are refused), so it never shows as the
system's next alarm. Boot/watchdog catch up on up to 5 unchecked past days.
PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
`fallback_ring_start`, `fallback_ring_stop`, `ring_backend`, `rtc_armed`,
`rtc_skip`, `firebase_unreachable`, `escape_seen`, `penalty_written`,
`penalty_cancelled` (field `cause`: `escape` | `sick_day`), `audit_written`.
## Verification status (2026-10-01)
- vmbox gate (`scripts/vmbox/harness.sh`, `guest_cases_v2.sh`): install,
timers, root ring unit on `snd-dummy`, sudoers merge, power-key drop-in,
a real `rtcwake` arm, uninstall — all pass. Passed in vmbox, then installed
on the host.
- Host: S4 RTC wake verified twice; both ring backends start and stop. The
root ALSA ring got `Device or resource busy` while PipeWire still held the
card seconds after a PipeWire ring — at night the card is idle and opens
(a silent root `aplay` passed), but a stream left open overnight would
keep it busy. **Open:** what the root ring does about a held card is
kuhy's call (killing the holder was refused by the auto-mode classifier).
- Emulator (`wake_alarm_api36`): exact A+15 check hidden from the system
next-alarm, headless `ring_started` on a heads-up ring, boot-path miss
(phone off before the alarm) → lockdown through tomorrow, escape hatch.
Not yet on the Pixel: the real focus-owner reaction and Firebase publish.
## Evidence for Claude
`python -m wake_alarm._audit [YYYY-MM-DD]` and the 11:05 timer write
`~/data/wake-alarm/incidents/<date>.md`: a merged phone + PC timeline, then
expected-vs-observed checks (alarm known, RTC armed the night before, PC up
by `A`, ring/fallback, penalty, lockdown), mismatches and escape uses first.
Outside the repo on purpose: it holds personal data.

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Krzysztof Rudnicki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,89 +0,0 @@
# Migration: GitHub Gist → shared `crdt_sync`
`phone_app`'s alarm sync was moved off a bespoke GitHub Gist onto the shared
[`crdt_sync`](https://github.com/kuhyx/utils/tree/main/crdt_sync_dart) library
(pinned tag `crdt_sync_dart-v0.2.0` — see `phone_app/pubspec.yaml`, which is
the authority; `pubspec.lock` resolves it to `5be99ab`), matching how the other
companion apps sync. A `crdt_sync_dart-v0.3.0` tag also exists upstream and is
*not* in use here — bumping to it is an untaken decision, not a drift to fix.
## What changed
- **phone_app (Dart):** `gist_service.dart` is gone. `AlarmSyncService` stores
the alarm locally in a `crdt_sync` `LogStore` (one HLC-stamped `Record`) and
pushes it to `wake-alarm-sync/devices/phone/alarm.json` in `kuhyx/syncs` via
`crdt_sync`'s `GitHubClient`. The device-flow OAuth scope moved `gist` →
`repo` (the Contents API needs private-repo access).
- **shutdown-wrapper.sh (PC, Bash):** now reads that alarm from the Contents
API (`Accept: application/vnd.github.raw`, so no base64) and parses the
`crdt_sync` `Record` log with `jq` (`.alarm.fields.alarm_hour[0]`). Config
moved from `~/.config/wake_alarm/gist_sync.json` `{token, gist_id}` to
`~/.config/wake_alarm/sync.json` `{token}` (repo-scoped).
## Setup after pulling this
1. On the phone: Settings → **Connect GitHub** (now requests `repo` scope; the
old gist-scoped token won't reach the Contents API).
2. On the PC: `~/.config/wake_alarm/sync.json` → `{ "token": "<repo-scoped>" }`,
then re-run `install.sh` so `/usr/local/bin/shutdown` picks up the new
reader.
## Surprises / non-obvious decisions
- **The consumer is a Python-less Bash reader** (`shutdown-wrapper.sh` runs at
shutdown, when a Python runtime may not be available), so it can't use the
`crdt_sync` library — it parses the log with `jq`. What makes that tractable:
`Hlc.toStr()` is **lexicographically sortable == chronological**, so
"latest wins" across device dirs is a plain string max, no date math.
- **The phone is push-only** (sole writer); there is no pull/merge. Its local
`LogStore` is always the source of truth.
- Any parse miss still falls back to `WAKE_AFTER_HOURS`, so a bad read can
never brick the morning wake.
# Migration: hibernate-scheduled → per-minute trigger timer
The PC is no longer shut down at night, which broke the whole scheduling
model: the wake time used to be decided once, at hibernate, and baked into the
RTC. With no shutdown there is no resume, so nothing fired the alarm at all —
and `wake-alarm.service` was `WantedBy=graphical-session.target`, so on an
always-on machine it fired at *login* time instead (`_should_run_alarm()` has
no time gate).
## What changed
- **New `wake-alarm-trigger.timer`** ticks every minute and runs
`wake_alarm._trigger`, which fires `morning-routine.service` when the
current local time is inside
`[phone alarm, phone alarm + TRIGGER_CATCHUP_MINUTES)`. This is now the
primary path; the phone can move the alarm at any hour and the PC follows.
- **New `wake_alarm/_sync.py`** — a Python reader for the same alarm file
`shutdown-wrapper.sh` parses with `jq`, plus an on-disk cache
(`~/.config/wake_alarm/alarm_cache.json`).
- **`wake-alarm.service` lost its `[Install]` section** and is no longer
enabled; `install.sh` disables it to clear stale symlinks.
- **Token resolution gained a fallback** to the sibling apps'
`~/.config/{diet_guard,screen_locker}/sync_token`, in both readers.
- `shutdown-wrapper.sh` and `sleep-hook.sh` keep working unchanged, now as the
PC-is-powered-down fallback rather than the main mechanism.
## Surprises / non-obvious decisions
- **A timer, not a resident scheduler.** Each tick is a fresh process, so
there is no daemon to die silently and no wall-clock jump to reason about
across suspend/resume. `Persistent=true` plus the catch-up window is what
makes a suspended PC still fire on resume.
- **Per-minute ticks, but a 5-minute cache.** Ticking every 5 minutes would
also quantise *firing* to 5 minutes (07:03 → 07:05). Ticking every minute
and only hitting the network when the cache is stale gives exact-minute
firing at ~288 GitHub reads/day.
- **Degraded reads log at INFO.** At one tick a minute, a WARNING on a
persistent condition is 1440 journal lines a day. The single WARNING that
survives is `_trigger`'s "firing now on a degraded source".
- **The sync had been dead since the crdt_sync migration.** `wake-alarm-sync/`
did not exist in `kuhyx/syncs` at all — the phone had never successfully
pushed, and `~/.config/wake_alarm/sync.json` was never created, so the
hibernate path had been silently using the `+8h` fallback. The phone app
needs one successful "Set Alarm & Sync" to create that path.
- **Still open:** alarms edited directly in the Android Clock app do not reach
the sync. Closing that needs an `ACTION_NEXT_ALARM_CLOCK_CHANGED` receiver
in the phone app — planned, not yet built.

View File

@ -1,52 +1,78 @@
# wake_alarm
A phone-driven wake alarm for an always-on PC. The alarm time is whatever the
companion phone app last synced (via the shared `crdt_sync` transport over a
private GitHub repo); a per-minute systemd user timer fires at exactly that
time, showing a fullscreen, challenge-dismissed alarm with fan ramp and
optional TP-Link Tapo P110 smart-plug control.
**The phone is the alarm.** `phone_app/` arms and rings it, and getting past it
means walking between two NFC tags and answering three questions. This repo's
Python half no longer wakes anyone: all it does is read the alarm time the
phone published and start the morning routine (the workout lock) at that time.
Change the alarm on the phone at any hour and the PC follows within ~5
minutes. If the PC does happen to be powered down, a `shutdown` wrapper
hibernates with `rtcwake` set to the same synced time, as a fallback.
## The dismiss sequence
Strict, ordered, and latched — every stage required, and a stage once passed
never reverts:
```
tag 1 -> 25 steps + 2 min -> tag 2 -> 3 challenges
```
The two tags must be *distinct* and live in different rooms; the same id in
both slots is refused at registration. Answers are cumulative, so a wrong one
costs the attempt and nothing else.
**One fallback, deliberately narrow.** After 5 minutes of ringing — or
immediately if NFC is off or fewer than two tags are registered — the two *tag*
stages are skipped and the challenge count rises to 6. The walk is never
skipped. Without a hatch of some kind, a dead tag at 06:00 leaves an alarm that
cannot be switched off at all.
Details, and the things that are a hard crash or a silent no-ring:
**`DOCS-phone-alarm.md`**.
## The PC half
A per-minute systemd user timer (`wake-alarm-trigger.timer`) reads the alarm
the phone published through the shared `crdt_sync` transport, and at that time
starts `morning-routine.service`, which runs the workout lock. It records a
once-per-day latch so the rest of the catch-up window does not restart it.
That is all it does. There is no alarm window, no audio, no smart plug, no
`rtcwake`, and no `shutdown` wrapper.
## Install
```bash
bash install.sh
bash install.sh # trigger timer
bash uninstall.sh # removes it, and any retired waking machinery
```
This installs the package + dependencies into system Python's user
site-packages (the systemd units run `/usr/bin/python` directly, not a venv —
see `CLAUDE.md`), installs and enables the per-minute trigger timer, the
systemd-sleep resume hook, the `shutdown` wrapper that hibernates with
`rtcwake` as a fallback, the fan-ramp script, and (optionally) `python-kasa`
for smart-plug control.
`install.sh` installs the package into system Python's user site-packages (the
units run `/usr/bin/python` directly, not a venv — see `CLAUDE.md`) and enables
the timer. It also clears the retired pieces an older install left behind,
notably `/usr/local/bin/shutdown`, which is root-owned and would otherwise keep
turning `shutdown now` into a hibernate forever.
Reading the phone's alarm needs a GitHub token with `repo` scope, at
`~/.config/wake_alarm/sync.json` as `{"token": "..."}`. If that file is
absent, a sibling app's `~/.config/{diet_guard,screen_locker}/sync_token` is
used instead, so one token covers every app syncing through `kuhyx/syncs`.
Reading the phone's alarm uses the shared `~/.config/crdt-sync/firebase.json`.
The GitHub mirror (fallback only) needs a `repo`-scoped token at
`~/.config/wake_alarm/sync.json` as `{"token": "..."}`.
## Usage
```bash
python -m wake_alarm._alarm --demo # test the alarm window (safe, closeable)
python -m wake_alarm._sync --show # what alarm time the PC resolves
python -m wake_alarm._sync --show # what alarm time the PC resolves
python -m wake_alarm._trigger --dry-run # what the next tick would do
journalctl --user -fu wake-alarm-trigger.service # watch it live
```
The alarm fires automatically once installed; no manual invocation is needed
in normal operation.
## Development
```bash
python -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/pre-commit install && .venv/bin/pre-commit install --hook-type pre-push
.venv/bin/python -m pytest wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-fail-under=100
cd phone_app && flutter test && flutter analyze
```
See `CLAUDE.md` for scheduling details, the hibernate/`rtcwake` mechanism,
the cross-repo `workout_log.json` read, and production deployment gotchas.
The dev venv lacks `gatelock`, so anything importing `_state` (including
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.
See `CLAUDE.md` for the sync resolution chain, the cross-repo coupling to
`morning_routine`, and production deployment gotchas.

View File

@ -1,29 +1,37 @@
#!/bin/bash
# Install the weekend wake alarm systemd user service and sudoers entry.
# Install the wake-alarm trigger timer.
#
# Usage: bash install.sh
#
# The phone is the alarm. The PC starts the morning routine at the time the
# phone last synced, and -- wake enforcement v2, DOCS-wake-enforcement.md --
# rings itself only when the phone stays silent, and wakes itself (RTC)
# before a Tue/Wed/Thu alarm.
#
# What it does:
# 1. Installs wake_alarm + dependencies for /usr/bin/python
# 2. Installs system dependencies (alsa-utils, ddcutil)
# 3. Installs the systemd user units and enables the per-minute trigger timer
# (which fires the alarm at the time the phone synced)
# 4. Installs the systemd-sleep hook (restarts alarm after hibernate resume)
# 5. Adds a sudoers entry for passwordless rtcwake
# 6. Installs shutdown wrapper so "shutdown now" also hibernates on alarm nights
# 7. Installs fan-control script so alarm can max fans on wake
# 8. Installs python-kasa (AUR) so the alarm can toggle a Tapo P110 smart plug
# 9. Installs ddcutil and grants /dev/i2c-* access for DDC/CI monitor control
# 2. Installs the systemd user units and enables their timers (trigger,
# session, strip, fallback, rtc, audit)
# 3. Installs the root pieces of the fallback alarm: the ring WAVs, the
# ALSA ring script + system unit, the sudoers lines that let the user
# start/stop that unit, and (pc_wake.json "hibernate" mode only) the
# logind drop-in that makes the power key hibernate
# 4. Removes the retired waking machinery from earlier installs
#
# Deliberately NOT done, and why:
# - no shutdown wrapper and no sleep hook: the RTC alarm lives in CMOS and
# survives however the PC goes down, so neither is needed
# - systemd-logind is never restarted (that kills the graphical session);
# the drop-in is applied with a HUP reload
set -euo pipefail
# Refuse to run under sudo. This script must run as the logged-in user: it
# installs *user* systemd units and calls `sudo` itself for the few root-owned
# pieces. Under sudo, XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS are stripped,
# so `systemctl --user` fails at step 3 and every later step -- including the
# shutdown wrapper at step 6 -- is silently skipped while the earlier pip output
# still looks like success. It also runs pip as root, which leaves root-owned
# files in ~/.cache/pip. Failing loudly here beats a half-finished install.
# so `systemctl --user` fails and later steps are silently skipped while the
# earlier pip output still looks like success. It also runs pip as root, which
# leaves root-owned files in ~/.cache/pip. Failing loudly beats half-finishing.
if [[ -n "${SUDO_USER:-}" || $EUID -eq 0 ]]; then
echo "Error: do not run this script with sudo." >&2
echo "Run it as your normal user: bash $0" >&2
@ -35,139 +43,147 @@ fi
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
readonly SCRIPT_DIR
readonly REPO_DIR="$SCRIPT_DIR"
SERVICE_FILE="$SCRIPT_DIR/wake-alarm.service"
TRIGGER_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-trigger.service"
TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer"
SLEEP_HOOK_SRC="$SCRIPT_DIR/sleep-hook.sh"
SHUTDOWN_WRAPPER_SRC="$SCRIPT_DIR/shutdown-wrapper.sh"
FANS_SCRIPT_SRC="$SCRIPT_DIR/wake-alarm-fans.sh"
FANS_SCRIPT_DST="/usr/local/bin/wake-alarm-fans.sh"
SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
SLEEP_HOOK_DST="/usr/lib/systemd/system-sleep/wake-alarm.sh"
SHUTDOWN_WRAPPER_DST="/usr/local/bin/shutdown"
SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
RTCWAKE_BIN="/usr/sbin/rtcwake"
readonly TRIGGER_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-trigger.service"
readonly TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer"
readonly SESSION_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-session.service"
readonly SESSION_TIMER_SRC="$SCRIPT_DIR/wake-alarm-session.timer"
readonly STRIP_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-strip.service"
readonly STRIP_PATH_SRC="$SCRIPT_DIR/wake-alarm-strip.path"
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
# Enforcement v2 user units (service + timer each).
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
# Root pieces of the fallback alarm.
readonly PC_DIR="$SCRIPT_DIR/scripts/pc"
readonly WAV_DIR="/usr/local/share/wake-alarm"
readonly RING_SCRIPT_DST="/usr/local/lib/wake-alarm/ring_alsa.sh"
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
readonly SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
readonly POWERKEY_DST="/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf"
INSTALL_USER="$(id -un)"
readonly INSTALL_USER
readonly SUDOERS_LINES=(
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $ALSA_UNIT"
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl stop $ALSA_UNIT"
)
echo "=== Weekend Wake Alarm Installer ==="
TEMP_DIR=""
cleanup() {
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf "$TEMP_DIR"
fi
}
trap cleanup EXIT
# 1. Install this package + its dependencies into system Python -------------
echo "[1/9] Installing wake_alarm + dependencies for /usr/bin/python..."
install_ring_audio() {
# Generated, never committed: the binary hook forbids WAVs in the repo.
/usr/bin/python3 -m wake_alarm._ring_wav --write "$TEMP_DIR/wav" >/dev/null
sudo install -D -m 0644 "$TEMP_DIR/wav/ring.wav" "$WAV_DIR/ring.wav"
sudo install -D -m 0644 "$TEMP_DIR/wav/ring_loop.wav" "$WAV_DIR/ring_loop.wav"
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
sudo install -m 0644 "$PC_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
sudo systemctl daemon-reload
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
}
install_sudoers() {
# Merge, never clobber: the file also holds the rtcwake entry the RTC
# arming relies on. Validated with visudo before it replaces anything.
local merged="$TEMP_DIR/sudoers" line
# The file is root-only (0440); a missing one starts the merge empty.
sudo cat "$SUDOERS_FILE" 2>/dev/null | tee "$merged" >/dev/null || : >"$merged"
if ! grep -q '/usr/sbin/rtcwake' "$merged"; then
echo "$INSTALL_USER ALL=(root) NOPASSWD: /usr/sbin/rtcwake" >>"$merged"
fi
for line in "${SUDOERS_LINES[@]}"; do
grep -qxF "$line" "$merged" || echo "$line" >>"$merged"
done
sudo visudo -cf "$merged" >/dev/null
sudo install -m 0440 -o root -g root "$merged" "$SUDOERS_FILE"
echo " $SUDOERS_FILE: rtcwake + start/stop $ALSA_UNIT (validated)."
}
install_powerkey_dropin() {
local mode
mode="$(/usr/bin/python3 -m wake_alarm._pc_wake_mode)"
if [[ "$mode" == "hibernate" ]]; then
if sudo cmp -s "$PC_DIR/wake-alarm-powerkey.conf" "$POWERKEY_DST"; then
echo " Power key already hibernates (mode: $mode)."
return 0
fi
sudo install -D -m 0644 "$PC_DIR/wake-alarm-powerkey.conf" "$POWERKEY_DST"
elif sudo test -f "$POWERKEY_DST"; then
sudo rm -f "$POWERKEY_DST"
else
echo " Power key untouched (mode: $mode)."
return 0
fi
# Reload, NEVER restart: restarting logind kills the graphical session.
sudo systemctl kill -s HUP systemd-logind
echo " logind drop-in updated for mode $mode and reloaded."
}
echo "=== Wake Alarm Trigger Installer ==="
echo "[1/4] Installing wake_alarm for /usr/bin/python..."
# Editable, and from this clone: a later `git pull` here then updates the
# running production code with no reinstall. A non-editable snapshot taken
# from a scratch directory silently stops tracking this repo.
/usr/bin/python3 -m pip install --user --break-system-packages -e "$REPO_DIR"
echo " Installed. Verifying import..."
/usr/bin/python3 -c "import wake_alarm; import gatelock" \
&& echo " wake_alarm and gatelock import cleanly from the system interpreter."
/usr/bin/python3 -c "import wake_alarm; import gatelock"
echo " wake_alarm and gatelock import under /usr/bin/python."
# 2. Install system dependencies
echo "[2/9] Checking system dependencies..."
if ! command -v speaker-test &>/dev/null; then
echo " Installing alsa-utils (required for speaker-test)..."
sudo pacman -S --noconfirm alsa-utils
else
echo " alsa-utils already installed"
fi
# 3. Install systemd user units (alarm + the trigger timer that fires it)
echo "[3/9] Installing systemd user units..."
echo "[2/4] Installing systemd user units..."
mkdir -p "$SYSTEMD_USER_DIR"
cp "$SERVICE_FILE" "$SYSTEMD_USER_DIR/wake-alarm.service"
cp "$TRIGGER_SERVICE_SRC" "$SYSTEMD_USER_DIR/wake-alarm-trigger.service"
cp "$TRIGGER_TIMER_SRC" "$SYSTEMD_USER_DIR/wake-alarm-trigger.timer"
cp "$TRIGGER_SERVICE_SRC" "$TRIGGER_TIMER_SRC" \
"$SESSION_SERVICE_SRC" "$SESSION_TIMER_SRC" \
"$STRIP_SERVICE_SRC" "$STRIP_PATH_SRC" "$SYSTEMD_USER_DIR/"
for unit in "${V2_UNITS[@]}"; do
cp "$SCRIPT_DIR/$unit.service" "$SCRIPT_DIR/$unit.timer" "$SYSTEMD_USER_DIR/"
done
systemctl --user daemon-reload
echo " Installed wake-alarm.service, wake-alarm-trigger.{service,timer}"
# wake-alarm.service must NOT auto-start: the PC is always on, so
# graphical-session.target is reached on every login and the alarm has no time
# gate — it would fire at login time. The timer owns firing (via
# morning-routine.service). Both guards matter under `set -euo pipefail`:
# a unit with no [Install] can't be enabled, and disabling a never-enabled unit
# can also return non-zero.
systemctl --user disable wake-alarm.service 2>/dev/null || true
echo " wake-alarm.service left disabled (started only by the trigger)"
systemctl --user enable --now wake-alarm-trigger.timer
echo " Trigger timer enabled and started (ticks once a minute)"
echo " Trigger timer enabled and started (ticks once a minute)."
systemctl --user enable --now wake-alarm-session.timer
echo " Session timer enabled (07:00-11:00, every 2 min)."
systemctl --user enable --now wake-alarm-strip.path
echo " Strip path enabled (corner reminder while the morning is in progress)."
for unit in "${V2_UNITS[@]}"; do
systemctl --user enable --now "$unit.timer"
done
echo " Fallback (04-09, every min), RTC (every 15 min + boot) and audit"
echo " (11:05) timers enabled."
# 4. Install systemd-sleep hook (restarts alarm after hibernate resume)
echo "[4/9] Installing systemd-sleep hook..."
sudo cp "$SLEEP_HOOK_SRC" "$SLEEP_HOOK_DST"
sudo chmod 0755 "$SLEEP_HOOK_DST"
echo " Installed to $SLEEP_HOOK_DST"
echo "[3/4] Installing the fallback alarm's root pieces (sudo)..."
TEMP_DIR="$(mktemp -d)"
install_ring_audio
install_sudoers
install_powerkey_dropin
# 5. Add sudoers entry for rtcwake (requires root)
echo "[5/9] Setting up sudoers for rtcwake..."
SUDOERS_LINE="$USER ALL=(root) NOPASSWD: $RTCWAKE_BIN"
if [[ -f "$SUDOERS_FILE" ]] && grep -qF "$SUDOERS_LINE" "$SUDOERS_FILE"; then
echo " Sudoers entry already exists"
echo "[4/4] Removing retired waking machinery from earlier installs..."
# Opportunistic, and deliberately NOT fatal. This script runs under `set -e`
# and the cleanup needs root, so on a machine without cached/passwordless sudo
# a hard call would abort the install *after* the package and timer are
# already in place -- reporting failure for an install that actually worked.
# `sudo -n` rather than plain sudo so it cannot hang on a password prompt in a
# non-TTY context either.
if sudo -n true 2>/dev/null; then
bash "$SCRIPT_DIR/uninstall.sh" --retired-only ||
echo " Cleanup incomplete — run: bash uninstall.sh --retired-only"
else
echo " Adding sudoers entry (requires sudo)..."
echo "$SUDOERS_LINE" | sudo tee "$SUDOERS_FILE" > /dev/null
sudo chmod 0440 "$SUDOERS_FILE"
echo " Added: $SUDOERS_LINE"
fi
# 6. Install shutdown wrapper (/usr/local/bin/shutdown shadows /usr/bin/shutdown)
echo "[6/9] Installing shutdown wrapper..."
sudo cp "$SHUTDOWN_WRAPPER_SRC" "$SHUTDOWN_WRAPPER_DST"
sudo chmod 0755 "$SHUTDOWN_WRAPPER_DST"
echo " Installed to $SHUTDOWN_WRAPPER_DST"
echo " 'shutdown now' will now hibernate (not poweroff) on alarm nights."
# 7. Install fan-control script and its sudoers entry
echo "[7/9] Installing fan-control script..."
sudo cp "$FANS_SCRIPT_SRC" "$FANS_SCRIPT_DST"
sudo chmod 0755 "$FANS_SCRIPT_DST"
FANS_SUDOERS_LINE="$USER ALL=(root) NOPASSWD: $FANS_SCRIPT_DST"
if [[ -f "$SUDOERS_FILE" ]] && grep -qF "$FANS_SUDOERS_LINE" "$SUDOERS_FILE"; then
echo " Fan sudoers entry already exists"
else
# Append to existing file (or create)
echo "$FANS_SUDOERS_LINE" | sudo tee -a "$SUDOERS_FILE" > /dev/null
sudo chmod 0440 "$SUDOERS_FILE"
echo " Added fan sudoers entry"
fi
# 8. Install python-kasa (AUR) for TP-Link Tapo P110 smart-plug control
echo "[8/9] Installing python-kasa (AUR)..."
if python -c 'import kasa' 2>/dev/null; then
echo " python-kasa already installed"
elif command -v yay &>/dev/null; then
yay -S --noconfirm --needed python-kasa
else
echo " WARNING: yay not found; install python-kasa manually for smart-plug support" >&2
fi
if [[ ! -f "$HOME/.config/wake_alarm/tapo.json" ]]; then
echo " NOTE: ~/.config/wake_alarm/tapo.json not found — smart-plug control is disabled."
echo " Create it (mode 0600) with keys: host, email, password."
fi
# 9. Install ddcutil for DDC/CI monitor power control
# ddcutil lets the alarm force the G27Q on via DDC/CI even when the monitor
# was physically powered off (power button), bypassing DPMS limitations.
echo "[9/9] Installing ddcutil (DDC/CI monitor power control)..."
if command -v ddcutil &>/dev/null; then
echo " ddcutil already installed"
else
sudo pacman -S --noconfirm ddcutil
echo " ddcutil installed"
fi
# ddcutil needs access to /dev/i2c-* — add user to i2c group if it exists.
if getent group i2c &>/dev/null; then
if ! id -nG "$USER" | grep -qw i2c; then
sudo usermod -aG i2c "$USER"
echo " Added $USER to i2c group (re-login required for group to take effect)"
else
echo " $USER already in i2c group"
fi
else
echo " i2c group not found — ddcutil will run via sudo"
echo " Needs root and sudo would prompt; skipping."
echo " Run it yourself: bash uninstall.sh --retired-only"
echo " This matters: /usr/local/bin/shutdown otherwise keeps turning"
echo " 'shutdown now' into a hibernate."
fi
echo
echo "=== Installation complete ==="
echo "The trigger timer ticks once a minute and fires the alarm at the time"
echo "the phone last synced (needs ~/.config/wake_alarm/sync.json with a"
echo "repo-scoped GitHub token — see MIGRATION.md)."
echo "Check what it resolves right now: python -m wake_alarm._sync --show"
echo "If the PC is powered down instead, the shutdown wrapper hibernates with"
echo "rtcwake set to the same alarm, and the sleep hook runs it on resume."
echo "Fans will ramp to 100% while the alarm is active, then restore automatically."
echo "To test now: python -m wake_alarm._alarm --demo"
echo "The timer ticks once a minute and starts morning-routine.service at the"
echo "time the phone last synced."
echo "Check what it resolves right now: python -m wake_alarm._sync --show"
echo "Check what the next tick would do: python -m wake_alarm._trigger --dry-run"
echo "Watch it live: journalctl --user -fu wake-alarm-trigger.service"
echo "Fallback alarm: python -m wake_alarm._fallback --dry-run"
echo "RTC plan: python -m wake_alarm._rtc --show"
echo "Audit a morning: python -m wake_alarm._audit --dry-run [YYYY-MM-DD]"

View File

@ -10,6 +10,14 @@ analyzer:
unnecessary_null_comparison: error
dead_code: error
invalid_annotation_target: error
exclude:
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:

View File

@ -18,7 +18,15 @@ val keystoreProperties = Properties().apply {
android {
namespace = "com.kuhy.wake_alarm_sync"
compileSdk = flutter.compileSdkVersion
// Pinned explicitly rather than delegated to the Flutter Gradle plugin:
// full-screen-intent and foreground-service semantics both changed at
// API 34/35, and the alarm path cannot be reasoned about without a floor.
// Pinned above `flutter.compileSdkVersion` (36 on Flutter 3.47.2):
// flutter_secure_storage 11.0.0, which arrives with crdt_sync_flutter
// v0.3.1, publishes AAR metadata demanding API 37 or later. That in
// turn needs AGP > 9.1.0, which needs Gradle >= 9.5.0 -- see
// settings.gradle.kts and gradle-wrapper.properties.
compileSdk = 37
ndkVersion = flutter.ndkVersion
compileOptions {
@ -27,11 +35,14 @@ android {
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.kuhy.wake_alarm_sync"
// flutter_secure_storage requires API 23+ (Android Keystore).
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
// 28 is the floor for android:showWhenLocked / android:turnScreenOn as
// plain manifest attributes, which the ring activity relies on; it also
// clears flutter_secure_storage's API 23 (Android Keystore) requirement
// and Flutter's own default of 24.
minSdk = 28
// Matches the target phone. Keep in step with compileSdk above.
targetSdk = 36
versionCode = flutter.versionCode
versionName = flutter.versionName
}
@ -66,3 +77,10 @@ kotlin {
flutter {
source = "../.."
}
dependencies {
// JVM unit tests (src/test) for the pure decision code -- StickCheck,
// DayCache, RingDecision, PoolSyncSchedule. No Robolectric: anything
// that needs a Context stays out of them.
testImplementation("junit:junit:4.13.2")
}

View File

@ -1,8 +1,42 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<!-- Alarm-clock app: USE_EXACT_ALARM is granted at install with no user
prompt, unlike SCHEDULE_EXACT_ALARM. setAlarmClock() is what earns it. -->
<uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- The full-screen intent is what puts the dismiss screen over the
lockscreen; from API 34 this permission gates it and can still be
revoked, so the app checks canUseFullScreenIntent() at schedule time. -->
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.TURN_SCREEN_ON"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<!-- Room proof (item 3): steps are the fallback, NFC the real proof. -->
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.NFC"/>
<!-- Home presence: the BSSID of the connected Wi-Fi is redacted to
02:00:00:00:00:00 without fine location, so this gates the Wi-Fi
check as much as the GPS fallback. While-in-use only: the read
runs from AlarmActivity, which is foregrounded over the
lockscreen, so no ACCESS_BACKGROUND_LOCATION and no change to
AlarmService's foregroundServiceType. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Install-time, no prompt. WifiManager/ConnectivityManager throw
SecurityException without these, which would look exactly like
"not at home". -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Lets WorkdayStick reach focus-owner's signature-protected receiver;
both apps are signed with the same release key. -->
<uses-permission android:name="com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"/>
<application
android:label="wake_alarm_sync"
android:label="WakeAlarm"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
@ -23,6 +57,54 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- The dismiss screen, launched by the full-screen intent. Not
exported: only this app's own PendingIntent may start it. -->
<activity
android:name=".AlarmActivity"
android:exported="false"
android:launchMode="singleInstance"
android:taskAffinity=".alarm"
android:excludeFromRecents="true"
android:showWhenLocked="true"
android:turnScreenOn="true"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"/>
<!-- foregroundServiceType must ALSO be passed to startForeground(); on
API 34+ omitting either is a hard crash the moment the alarm fires. -->
<service
android:name=".AlarmService"
android:exported="false"
android:foregroundServiceType="mediaPlayback"/>
<receiver
android:name=".AlarmReceiver"
android:exported="false"/>
<!-- Daily check that the alarm is still armed; not exported, only
this app's own repeating PendingIntent reaches it. -->
<receiver
android:name=".WatchdogReceiver"
android:exported="false"/>
<!-- The stick's exact check at A + 15 (StickAlarm.kt); not exported,
only this app's own PendingIntent reaches it. -->
<receiver
android:name=".StickCheckReceiver"
android:exported="false"/>
<!-- The pre-alarm sync of the free/sick day pools (PoolSyncAlarm.kt);
not exported, only this app's own PendingIntent reaches it. -->
<receiver
android:name=".PoolSyncReceiver"
android:exported="false"/>
<!-- The silent buzz before a session deadline (SessionWarn.kt). -->
<receiver
android:name=".SessionWarnReceiver"
android:exported="false"/>
<receiver
android:name=".BootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<meta-data
android:name="flutterEmbedding"
android:value="2" />

View File

@ -0,0 +1,154 @@
package com.kuhy.wake_alarm_sync
import android.app.KeyguardManager
import android.content.Context
import android.os.Bundle
import android.view.WindowManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
/**
* The dismiss screen, launched by the full-screen intent over the lockscreen.
*
* A separate FlutterActivity from [MainActivity] so the ring UI can never be
* confused with the normal app task: it is launched with CLEAR_TASK and routes
* straight to the Dart ring screen.
*/
class AlarmActivity : FlutterActivity() {
/** Dart route the ring screen is registered under in main.dart. */
private val ringRoute = "/ring"
/**
* The ring by default; the session checklist only when asked for by
* [SessionNotice.resumeIntent] (the launcher redirect or the ongoing
* notification) AND nothing is sounding. A ring always wins: an intent
* that opened the checklist over a live alarm would leave the sound
* running with no dismiss sequence in front of it. Read once, at
* creation -- a live `singleInstance` instance just comes forward on
* whatever screen Dart is showing, which is the right thing.
*/
override fun getInitialRoute(): String {
if (AlarmService.running) return ringRoute
return intent?.getStringExtra(SessionNotice.EXTRA_ROUTE) ?: ringRoute
}
override fun onCreate(savedInstanceState: Bundle?) {
// showWhenLocked/turnScreenOn are also set as manifest attributes; the
// programmatic calls cover the case where the activity is re-created
// while the device is already locked.
setShowWhenLocked(true)
setTurnScreenOn(true)
super.onCreate(savedInstanceState)
// The morning session lives in this activity for half an hour after
// the ring stops. With the screen allowed to sleep the activity
// pauses and NFC stops polling, so a tag tap would need a wake and
// an unlock first, every leg.
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
dismissKeyguard()
}
/**
* Asks the system to take the keyguard down for the ring screen.
*
* Load-bearing for the NFC room proof, not cosmetic. Showing *over* the
* keyguard leaves the device locked, and NFC reports `mScreenState=
* ON_LOCKED` in that state: the controller stops polling for tags even
* though `enableReaderMode` was accepted (measured on the Pixel 6a — the
* same tag that registered fine while unlocked was never discovered while
* the ring screen was up). Without this the only satisfiable proof at
* 06:00 is steps, which is exactly the single-mechanism dependency the
* room-proof redundancy exists to avoid.
*
* On a secured device this surfaces the PIN/biometric prompt, which is an
* acceptable trade for an alarm the user must get up for.
*/
private fun dismissKeyguard() {
val keyguard = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (!keyguard.isKeyguardLocked) return
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
// NFC only starts polling once the screen state leaves
// ON_LOCKED, so reader mode has to be re-asserted after
// the unlock rather than only in onResume.
alarmChannel?.let { NfcReader.start(this@AlarmActivity, it) }
}
},
)
}
/** Kept so NFC reader mode can push tag ids back to the ring screen. */
private var alarmChannel: MethodChannel? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
AlarmChannel.register(this, flutterEngine)
val channel = channel(flutterEngine)
alarmChannel = channel
// AlarmChannel deliberately holds applicationContext, so it cannot
// finish an activity. Without this the dismiss screen stays up over
// the lockscreen forever after a correct answer — back is disabled,
// and the live instance would carry _inRoom=true and the solved
// answer into the next ring.
channel.setMethodCallHandler { call, result ->
if (call.method == "closeRingScreen") {
finishAndRemoveTask()
result.success(null)
} else {
AlarmChannel.handleCall(applicationContext, call, result)
}
}
}
override fun onResume() {
super.onResume()
// Reader mode only works while this activity is in the foreground, so
// it is started here rather than at engine-configure time.
//
// Re-asserted on every resume, not just the first: anything that comes
// up over the ring screen (the launcher activity, a system dialog)
// pauses this one and takes reader mode down with it, and the tag tap
// must keep working once the ring screen is back in front.
alarmChannel?.let { NfcReader.start(this, it) }
// The user can still lock the phone mid-session with the power
// button. Coming back, the keyguard is up again and NFC is back in
// ON_LOCKED -- the same dead state onCreate handles.
dismissKeyguard()
}
override fun onPause() {
// Deliberately does NOT disable reader mode. enableReaderMode is
// per-activity but disableReaderMode is effectively global, so
// stopping here killed polling for the ring screen whenever another
// activity briefly came in front — measured on the Pixel, where the
// NfcService log showed `flags: 271` immediately followed by
// `flags: 0`. onDestroy is the right place: by then the ring really
// is over.
super.onPause()
}
override fun onDestroy() {
NfcReader.stop(this)
super.onDestroy()
}
/**
* Dismissing is the only way out: the ring screen owns the challenge, so
* back must not silently drop the user onto the lockscreen with the alarm
* still sounding.
*/
@Suppress("MissingSuperCall")
override fun onBackPressed() = Unit
companion object {
/** Channel name shared with [MainActivity]; one channel for the whole feature. */
const val CHANNEL: String = "com.kuhy.wake_alarm_sync/alarm"
/** Convenience for tests and callers that need the MethodChannel type. */
fun channel(engine: FlutterEngine): MethodChannel =
MethodChannel(engine.dartExecutor.binaryMessenger, CHANNEL)
}
}

View File

@ -0,0 +1,178 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
/**
* The single MethodChannel this feature exposes to Dart.
*
* One channel rather than a plugin: the stack is AGP 9 / Gradle 9.1 /
* Kotlin 2.3.20, and a plugin that fails to compile breaks the build outright
* instead of degrading. Everything the alarm needs is here.
*/
object AlarmChannel {
/** Wires [engine]'s Dart side to the scheduler and the ring service. */
fun register(context: Context, engine: FlutterEngine) {
val app = context.applicationContext
MethodChannel(engine.dartExecutor.binaryMessenger, AlarmActivity.CHANNEL)
.setMethodCallHandler { call, result -> handleCall(app, call, result) }
}
fun handleCall(context: Context, call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"schedule" -> schedule(context, call, result)
// No "cancel": the alarm cannot be switched off. Removing the
// handler (rather than just the Dart wrapper) is what makes that
// real — otherwise the capability is one invokeMethod away.
// Called from the Dart init seam and after a dismiss: with no
// change-stream in the store, these are the only re-arm hooks
// besides BOOT_COMPLETED.
"rearm" -> result.success(AlarmScheduler.rearmFromStorage(context))
// Arms the fixed schedule and (re)starts the daily check. Called
// from the Dart init seam on every launch, so the alarm is armed
// by opening the app at all rather than by tapping anything.
"armSchedule" -> {
val hour = call.argument<Int>("hour")
val minute = call.argument<Int>("minute")
if (hour == null || minute == null) {
result.error("bad_args", "hour and minute are required", null)
} else {
AlarmScheduler.schedule(context, hour, minute)
AlarmWatchdog.schedule(context)
result.success(null)
}
}
"canUseFullScreenIntent" ->
result.success(AlarmScheduler.canUseFullScreenIntent(context))
"dismiss" -> {
AlarmService.stop(context)
// Re-arm immediately so the alarm rings again tomorrow.
AlarmScheduler.rearmFromStorage(context)
result.success(null)
}
// Fires the ring immediately, so the foreground-service and
// full-screen-intent path can be exercised on an emulator without
// waiting for a real alarm instant. Reachable only over this app's
// own channel; it arms nothing and changes no stored time.
"ringNow" -> {
AlarmService.start(context)
result.success(null)
}
// The Dart pool's free dates, cached where AlarmReceiver can
// read them with no engine running. Dart calls this after every
// mark, release and sync; see FreeDays.kt.
"setFreeDays" -> {
val dates = call.argument<List<String>>("dates")
if (dates == null) {
result.error("bad_args", "dates is required", null)
} else {
FreeDays.store(context, dates)
result.success(null)
}
}
// The sick-day twin of setFreeDays; see SickDays.kt.
"setSickDays" -> {
val dates = call.argument<List<String>>("dates")
if (dates == null) {
result.error("bad_args", "dates is required", null)
} else {
SickDays.store(context, dates)
result.success(null)
}
}
// Read-back for the picker: what AlarmReceiver will see.
"getSickDays" -> result.success(SickDays.dates(context))
"hasNfc" -> result.success(NfcReader.isAvailable(context))
// Raw observations only; home_presence.dart decides what they mean.
// Lives here rather than in MainActivity's override (as NfcReader
// does) because WifiManager/LocationManager need no Activity, and
// the ring screen must be able to reach it through AlarmActivity.
"readPresence" -> HomePresence.read(
context,
call.argument<Double>("homeLat"),
call.argument<Double>("homeLon"),
call.argument<Boolean>("withFix") ?: false,
) { observations -> result.success(observations) }
// Handled by AlarmActivity, which owns the window; reaching here
// means the picker asked, where there is no ring screen to close.
"closeRingScreen" -> result.success(null)
"stepCount" -> result.success(StepCounter.stepsSinceRingStart(context))
// The morning session's one live deadline, as an absolute epoch
// instant; null drops it (a leg with its re-ring spent must not
// inherit the previous leg's alarm). Dart ints cross the channel
// as Int when they fit and Long when they do not; an epoch in
// millis never fits.
"armReRing" -> {
val at = call.argument<Number>("atMillis")?.toLong()
if (at == null) {
AlarmScheduler.clearReRing(context)
} else {
AlarmScheduler.scheduleReRing(context, at)
}
result.success(null)
}
// The session's finish path, and the only thing that drops a
// pending re-ring. Not named "cancel" and not reachable from any
// screen but the session's own: the wake alarm itself still has
// no off switch.
"finishSession" -> {
AlarmScheduler.clearReRing(context)
SessionNotice.clear(context)
result.success(null)
}
// The live leg, for the launcher redirect and the ongoing
// notification; see SessionNotice.kt. Called on every leg
// change, never per tick.
"updateSessionNotice" -> {
val date = call.argument<String>("date")
val label = call.argument<String>("label")
if (date == null || label == null) {
result.error("bad_args", "date and label are required", null)
} else {
val at = call.argument<Number>("deadlineMillis")?.toLong()
SessionNotice.update(context, date, label, at)
result.success(null)
}
}
// Whether a launch right now would be redirected into the
// morning; the probes ask before starting a test ring.
"morningLive" ->
result.success(AlarmService.running || SessionNotice.isLiveToday(context))
// Whether the ring is sounding; the session screen polls this so
// a deadline that rang while it sat in the background puts the
// dismiss sequence in front the moment it is looked at.
"isRinging" -> result.success(AlarmService.running)
"beginStepCount" -> {
StepCounter.markRingStart(context)
result.success(null)
}
// The dismiss gate actually completed -- see RingWatch. Called
// once, from the same spot `afterDismiss` starts or resumes a
// session, regardless of outcome: reaching afterDismiss at all
// means the ring was dismissed.
"markRingDismissed" -> {
RingWatch.markDismissed(context)
StickRunner.onDismissed(context)
EventLog.append(context, "dismissed")
result.success(null)
}
else -> if (!EnforcementChannel.handleCall(context, call, result)) {
result.notImplemented()
}
}
}
private fun schedule(context: Context, call: MethodCall, result: MethodChannel.Result) {
val hour = call.argument<Int>("hour")
val minute = call.argument<Int>("minute")
if (hour == null || minute == null) {
result.error("bad_args", "hour and minute are required", null)
return
}
AlarmScheduler.schedule(context, hour, minute)
result.success(null)
}
}

View File

@ -0,0 +1,55 @@
package com.kuhy.wake_alarm_sync
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* Receives the exact alarm and hands straight off to [AlarmService].
*
* Deliberately does no work of its own: a receiver gets ~10s and no wakelock,
* so anything that must outlive it (sound, the wakelock, the full-screen
* intent) belongs to the foreground service. Starting that service from here
* is legal with the screen off only because setAlarmClock grants an
* alarm-clock exemption to the broadcast.
*/
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// A session deadline: the user dismissed the alarm and then stalled.
// No free/sick-day check (neither ever starts a session) and no daily
// re-arm -- that is the wake alarm's business, not this one's.
if (intent.getStringExtra(AlarmScheduler.EXTRA_REASON) == AlarmScheduler.REASON_RERING) {
Log.i(TAG, "session deadline missed: re-ringing")
EventLog.append(context, "alarm_fired", mapOf("reason" to "rering"))
AlarmService.start(context)
return
}
// A shared free or sick day means the alarm does not ring -- not
// later, not quieter, not at all -- and nothing ring-related is
// recorded: no markFired (the stick's own check skips the day too)
// and no ring_started for the PC. Re-arm for tomorrow (the armed
// instant has passed, so it rolls over) so the day after is normal.
// Both caches fail closed: unreadable means ring.
val skip = RingDecision.skip(FreeDays.isToday(context), SickDays.isToday(context))
if (skip != null) {
Log.i(TAG, "${skip.label}: not ringing; re-armed for tomorrow")
EventLog.append(context, "alarm_fired", mapOf("reason" to skip.wire))
AlarmScheduler.rearmFromStorage(context)
return
}
// The one fresh (non-re-ring) daily alarm. Recorded here, not in
// Dart, so a poweroff mid-ring can never race it: setAlarmClock has
// already woken the CPU by the time this line runs.
RingWatch.markFired(context)
AlarmService.start(context)
EventLog.append(context, "alarm_fired", mapOf("reason" to "daily"))
// After the sound is started, never before: tells the PC the phone
// is ringing even when the ring screen never opens.
HeadlessRingStart.start(context)
}
private companion object {
const val TAG = "WakeAlarmReceiver"
}
}

View File

@ -0,0 +1,220 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.time.LocalTime
import java.util.Calendar
/**
* Arms and cancels the one exact alarm this app owns.
*
* Uses [AlarmManager.setAlarmClock] rather than setExactAndAllowWhileIdle: it is
* the only API that is Doze-exempt *and* needs no SCHEDULE_EXACT_ALARM user
* prompt (USE_EXACT_ALARM covers an alarm-clock app), and it is what grants the
* receiver its brief foreground-service exemption when it fires with the screen
* off. Everything else about the ring path depends on that exemption.
*/
object AlarmScheduler {
/** Request code for the single alarm PendingIntent; reused so re-arming replaces. */
private const val REQUEST_CODE = 1001
/**
* Request code for the morning session's re-ring.
*
* Distinct from [REQUEST_CODE] on purpose: a PendingIntent is keyed by
* request code, so arming the re-ring under 1001 would silently replace
* tomorrow's wake alarm with a one-shot twenty minutes from now.
*/
private const val RERING_REQUEST_CODE = 1003
/** Intent extra naming why the receiver fired; absent on the daily alarm. */
const val EXTRA_REASON = "reason"
/** [EXTRA_REASON] value for a session deadline. */
const val REASON_RERING = "rering"
/** SharedPreferences file holding the armed time, so boot can re-arm it. */
private const val PREFS = "wake_alarm_scheduler"
private const val KEY_HOUR = "hour"
private const val KEY_MINUTE = "minute"
/** Epoch millis of the armed re-ring, so a reboot mid-session restores it. */
private const val KEY_RERING_AT = "rering_at"
/** Sentinel for "no alarm stored", distinguishable from a valid 0. */
private const val NONE = -1
/**
* Arms the alarm for the next occurrence of [hour]:[minute] in local time,
* and persists it so [rearmFromStorage] can restore it after a reboot.
*/
fun schedule(context: Context, hour: Int, minute: Int) {
persist(context, hour, minute)
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val at = nextOccurrence(hour, minute)
// showIntent is what the system Clock surfaces; the fire intent is separate.
manager.setAlarmClock(
AlarmManager.AlarmClockInfo(at, showIntent(context)),
firePendingIntent(context),
)
// Every arm path (picker, boot, dismiss, free-day skip, watchdog)
// ends here, so the stick's own check can never be left unarmed.
StickAlarm.schedule(context, LocalTime.of(hour, minute))
// Same funnel for the pre-alarm day-pool sync (PoolSyncAlarm.kt).
PoolSyncAlarm.schedule(context, LocalTime.of(hour, minute))
}
/** Cancels the armed alarm and forgets the stored time. */
fun cancel(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(firePendingIntent(context))
StickAlarm.cancel(context)
PoolSyncAlarm.cancel(context)
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(KEY_HOUR).remove(KEY_MINUTE).apply()
}
/**
* Re-arms from the persisted time, returning false when nothing was stored.
*
* Called on BOOT_COMPLETED and after a dismiss: an alarm clock that only
* armed on user edit would ring exactly once.
*/
fun rearmFromStorage(context: Context): Boolean {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val hour = prefs.getInt(KEY_HOUR, NONE)
val minute = prefs.getInt(KEY_MINUTE, NONE)
if (hour == NONE || minute == NONE) return false
schedule(context, hour, minute)
return true
}
/** The stored daily time `A`, or null when none was ever armed. */
fun storedAlarm(context: Context): LocalTime? {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val hour = prefs.getInt(KEY_HOUR, NONE)
val minute = prefs.getInt(KEY_MINUTE, NONE)
if (hour == NONE || minute == NONE) return null
return LocalTime.of(hour, minute)
}
/**
* Arms the morning session's re-ring for the absolute instant [atMillis].
*
* Same [AlarmManager.setAlarmClock] path as the daily alarm: it is the
* one this repo has proved starts the foreground service with the screen
* off. Replaces any earlier re-ring — the session has exactly one live
* deadline at a time.
*/
fun scheduleReRing(context: Context, atMillis: Long) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putLong(KEY_RERING_AT, atMillis).apply()
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.setAlarmClock(
AlarmManager.AlarmClockInfo(atMillis, showIntent(context)),
reRingPendingIntent(context),
)
SessionWarn.arm(context, atMillis)
}
/**
* Drops the pending re-ring. Reached only from the session's own finish
* path (`finishSession`); there is no Dart-facing cancel for the alarm
* itself.
*/
fun clearReRing(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(reRingPendingIntent(context))
SessionWarn.clear(context)
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(KEY_RERING_AT).apply()
}
/**
* Re-arms a stored re-ring after a reboot; false when none is still due.
*
* A past instant is dropped, never fired: a session whose deadline
* passed while the phone was off is over, and a stale instant is not
* confined to reboots -- Android re-delivered BOOT_COMPLETED to a
* force-stopped app on its next launch (Pixel 6a, 2026-09-16), which
* fired a nine-minute-old deadline into an evening with no session.
*/
fun restoreReRing(context: Context): Boolean {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val at = prefs.getLong(KEY_RERING_AT, NONE.toLong())
if (at == NONE.toLong()) return false
if (at <= System.currentTimeMillis()) {
prefs.edit().remove(KEY_RERING_AT).apply()
return false
}
scheduleReRing(context, at)
return true
}
/**
* Whether the system will actually honour a full-screen intent.
*
* Requires BOTH the API 34 full-screen-intent grant AND notifications
* being enabled at all: with notifications blocked the post is dropped
* before the full-screen intent is ever considered, so the alarm rings
* with no dismiss screen. Measured on the API 36 AVD, where a freshly
* installed app sits at importance=NONE and the op logs a rejectTime.
*
* The caller must treat a false here as a hard failure rather than
* logging and continuing — the sleeping user never sees a notification.
*/
fun canUseFullScreenIntent(context: Context): Boolean {
val notifications =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (!notifications.areNotificationsEnabled()) return false
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return true
return notifications.canUseFullScreenIntent()
}
private fun persist(context: Context, hour: Int, minute: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.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
}
/** FLAG_IMMUTABLE is mandatory from API 31; without it this throws at arm time. */
private fun firePendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, AlarmReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** The re-ring's own PendingIntent; the extra is how the receiver tells them apart. */
private fun reRingPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
RERING_REQUEST_CODE,
Intent(context, AlarmReceiver::class.java).putExtra(EXTRA_REASON, REASON_RERING),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** Tapping the clock's alarm chip opens the app rather than the ring screen. */
private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity(
context,
REQUEST_CODE + 1,
Intent(context, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}

View File

@ -0,0 +1,214 @@
package com.kuhy.wake_alarm_sync
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import android.util.Log
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
/**
* Foreground service that actually makes noise until the alarm is dismissed.
*
* Holds a PARTIAL_WAKE_LOCK so the CPU keeps running with the screen off (it
* does **not** wake the screen — [AlarmActivity]'s turnScreenOn does that), and
* posts a full-screen-intent notification that launches the dismiss screen over
* the lockscreen.
*/
class AlarmService : Service() {
private var player: MediaPlayer? = null
/** Drives the volume ramp; cleared in [stopSound]. */
private val rampHandler = Handler(Looper.getMainLooper())
private var wakeLock: PowerManager.WakeLock? = null
private var vibrator: Vibrator? = null
companion object {
private const val TAG = "AlarmService"
private const val CHANNEL_ID = "wake_alarm_ring"
private const val NOTIFICATION_ID = 42
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */
private val VIBRATION_PATTERN = longArrayOf(0, 1000, 1000)
/**
* Whether the ring is sounding right now. Same process as both
* activities, so a launch during a ring can route to the dismiss
* screen instead of the home screen or a session checklist.
*/
@Volatile
var running: Boolean = false
private set
/** Starts the ring. Safe to call when already ringing — start is idempotent. */
fun start(context: Context) {
val intent = Intent(context, AlarmService::class.java)
context.startForegroundService(intent)
}
/** Stops the ring and releases every resource it holds. */
fun stop(context: Context) {
// Cleared here, not only in onDestroy: stopService is
// asynchronous, and the session screen that follows a dismiss
// polls this flag from its first tick -- a stale true would
// re-ring the alarm it had just silenced.
running = false
context.stopService(Intent(context, AlarmService::class.java))
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createChannel()
// The type must be passed here AND declared on the <service> in the
// manifest; omitting either is a hard crash at ring time on API 34+.
startForeground(
NOTIFICATION_ID,
buildNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,
)
acquireWakeLock()
startSound()
startVibration()
running = true
// START_STICKY: if the system kills us under memory pressure while the
// user is still asleep, the alarm comes back rather than going silent.
return START_STICKY
}
override fun onDestroy() {
running = false
stopSound()
stopVibration()
releaseWakeLock()
super.onDestroy()
}
private fun createChannel() {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// IMPORTANCE_HIGH is required for a full-screen intent to be honoured.
val channel = NotificationChannel(
CHANNEL_ID,
"Wake alarm",
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = "The ringing wake alarm"
// The service owns sound and vibration, so the channel must not add
// its own — a channel sound would play on the notification stream
// and be silenced by DND, unlike STREAM_ALARM.
setSound(null, null)
enableVibration(false)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
}
manager.createNotificationChannel(channel)
}
private fun buildNotification(): Notification {
val fullScreen = PendingIntent.getActivity(
this,
0,
Intent(this, AlarmActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
},
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
return Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Wake alarm")
.setContentText("Tap to dismiss")
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setCategory(Notification.CATEGORY_ALARM)
.setOngoing(true)
.setFullScreenIntent(fullScreen, true)
.build()
}
private fun acquireWakeLock() {
val power = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = power.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"wake_alarm_sync:ring",
).apply { acquire() }
}
private fun releaseWakeLock() {
wakeLock?.takeIf { it.isHeld }?.release()
wakeLock = null
}
private fun startSound() {
if (player != null) return
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
?: return
// USAGE_ALARM maps to STREAM_ALARM, which is what ignores DND and
// silent mode. Never USAGE_MEDIA here — it would be muted exactly when
// the alarm matters most.
player = MediaPlayer().apply {
setDataSource(this@AlarmService, uri)
setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build(),
)
isLooping = true
prepare()
// Start almost silent. The stream still goes to max below, so a
// stream muted to zero cannot silence the alarm -- it is the
// player's own gain that climbs.
setVolume(AlarmVolume.RAMP_START_GAIN, AlarmVolume.RAMP_START_GAIN)
start()
}
AlarmVolume.raiseStream(this)
AlarmVolume.startRamp(rampHandler) { player }
}
private fun stopSound() {
// Before releasing the player: a queued step that runs afterwards
// would touch a released MediaPlayer.
rampHandler.removeCallbacksAndMessages(null)
player?.run {
if (isPlaying) stop()
release()
}
player = null
}
private fun startVibration() {
val service = resolveVibrator() ?: return
vibrator = service
service.vibrate(
VibrationEffect.createWaveform(VIBRATION_PATTERN, 0),
)
}
private fun stopVibration() {
vibrator?.cancel()
vibrator = null
}
private fun resolveVibrator(): Vibrator? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as? VibratorManager)
?.defaultVibrator
} else {
@Suppress("DEPRECATION")
getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
}
}

View File

@ -0,0 +1,86 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Handler
import android.util.Log
/**
* How loud the alarm is, and how it gets there.
*
* Split out of [AlarmService] for the repo's 250-line cap, along a real seam:
* the service owns the ring's lifecycle, this owns its loudness.
*
* **Two knobs, deliberately not merged.** [raiseStream] fixes the *system
* stream*, which must be at max or a stream someone left at zero silences the
* alarm outright. [startRamp] shapes the *player's own gain* within it.
* Collapsing them into one would trade a gentle start for a silent alarm.
*/
object AlarmVolume {
private const val TAG = "AlarmVolume"
/** Player gain the ring starts at: audible in a quiet room, not a jolt. */
const val RAMP_START_GAIN = 0.04f
/**
* How long the climb from [RAMP_START_GAIN] to full takes.
*
* Ten minutes, up from one on 2026-09-16: a minute to full blast is a
* jolt, not a wake-up, and with the dismiss walk taking a few minutes
* the whole sequence was done at maximum volume.
*/
private const val RAMP_DURATION_MS = 600_000L
/** Gap between ramp steps; 300 steps over the full duration. */
private const val RAMP_STEP_MS = 2_000L
/**
* An alarm stream turned down to zero must not silence the alarm.
*
* Guarded: setStreamVolume can throw under an active zen rule, and by the
* time this runs startForeground() has already posted — an exception here
* would take the whole ring down over a volume bump that is only an
* improvement, not the mechanism.
*/
fun raiseStream(context: Context) {
try {
val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM)
audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0)
} catch (e: SecurityException) {
Log.w(TAG, "could not raise the alarm volume; ringing anyway", e)
}
}
/**
* Climbs the player gain from [RAMP_START_GAIN] to full over
* [RAMP_DURATION_MS].
*
* Waking someone at full blast is not more effective, only harsher. The
* climb is quadratic because perceived loudness is not linear in
* amplitude: a linear ramp lurches at the start and crawls at the end.
* Measured on the Pixel 6a at the old one-minute duration: -28 dB at
* 3s, -21 dB at 15s, -12 dB at 30s, 0 dB at 62s; the shape is the same,
* stretched tenfold.
*
* [player] is re-read every step and a null one ends that step, so a
* dismissal mid-ramp cannot touch a released MediaPlayer — provided the
* caller also clears [handler] before releasing it, which
* `AlarmService.stopSound` does.
*/
fun startRamp(handler: Handler, player: () -> MediaPlayer?) {
val steps = (RAMP_DURATION_MS / RAMP_STEP_MS).toInt()
for (step in 1..steps) {
handler.postDelayed({
val live = player() ?: return@postDelayed
val progress = step.toFloat() / steps
val gain =
RAMP_START_GAIN + (1f - RAMP_START_GAIN) * progress * progress
runCatching { live.setVolume(gain, gain) }
.onFailure { Log.w(TAG, "volume ramp step failed", it) }
}, RAMP_STEP_MS * step)
}
}
}

View File

@ -0,0 +1,79 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* Keeps the alarm armed without the user ever opening the app.
*
* The ring path already re-arms on boot and on dismiss, but both are *events*:
* if the app is force-stopped, or an update clears the pending intent, or a
* re-arm silently fails, nothing notices until the morning it does not ring.
* This is the periodic check that closes that gap — it runs daily, asks
* whether an alarm is actually scheduled, and schedules one if not.
*
* Deliberately self-rescheduling rather than WorkManager: the ring path takes
* no third-party dependency (see AlarmChannel), and AlarmManager is already
* present and understood here.
*/
object AlarmWatchdog {
private const val TAG = "WakeAlarmWatchdog"
/** Request code for the watchdog's own repeating wake-up. */
private const val REQUEST_CODE = 1002
/** How often to verify the alarm is still armed. */
private const val INTERVAL_MS = AlarmManager.INTERVAL_DAY
/** Starts (or refreshes) the periodic check. Safe to call repeatedly. */
fun schedule(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Inexact on purpose: this only has to happen *sometime* each day, and
// an inexact repeat costs no exact-alarm budget and survives Doze by
// being deferred rather than dropped.
manager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + INTERVAL_MS,
INTERVAL_MS,
pendingIntent(context),
)
}
/**
* Re-arms the alarm if nothing is currently scheduled.
*
* Re-arming unconditionally would be simpler, but would also reset a
* legitimately pending alarm every day; `rearmFromStorage` is idempotent
* for an unchanged time, so this stays cheap either way.
*/
fun verify(context: Context) {
val rearmed = AlarmScheduler.rearmFromStorage(context)
Log.i(TAG, "daily check: rearmed=$rearmed")
// Third net behind the exact check and boot: within a day, whatever
// dropped the other two, today's miss is still caught here.
StickRunner.run(context, "watchdog")
}
private fun pendingIntent(context: Context): PendingIntent =
PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, WatchdogReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Receives the daily watchdog tick. */
class WatchdogReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AlarmWatchdog.verify(context)
// Re-assert the repeat: setInexactRepeating does not survive a reboot,
// and BootReceiver is the only other thing that would restore it.
AlarmWatchdog.schedule(context)
}
}

View File

@ -0,0 +1,37 @@
package com.kuhy.wake_alarm_sync
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* Re-arms the stored alarm after a reboot.
*
* AlarmManager drops every alarm across a reboot, so without this the phone
* silently stops being an alarm clock until the user next edits the time.
*/
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
val rearmed = AlarmScheduler.rearmFromStorage(context)
// A reboot mid-session must not end the session silently: the live
// leg's deadline is stored alongside the daily time. Not only after
// a reboot, either -- see restoreReRing for the launch-time replay.
val rering = AlarmScheduler.restoreReRing(context)
Log.i(TAG, "boot: rearmed=$rearmed rering=$rering")
EventLog.append(context, "boot", mapOf("rearmed" to rearmed, "rering" to rering))
// setInexactRepeating does not survive a reboot, so the daily check
// has to be re-established here or it silently stops after the first
// restart — exactly when a watchdog is most needed.
AlarmWatchdog.schedule(context)
// A phone switched off before the alarm and back on after A + 15 has
// missed: this is the path that closes that hole (rearmFromStorage
// above has already armed the exact check for a phone back earlier).
StickRunner.run(context, "boot")
}
private companion object {
const val TAG = "WakeAlarmBoot"
}
}

View File

@ -0,0 +1,31 @@
package com.kuhy.wake_alarm_sync
import android.content.SharedPreferences
import java.time.LocalDate
/**
* A bounded set of ISO dates in one SharedPreferences key: "on which days
* did X happen". The stick's backlog judges days up to
* [StickCheck.BACKLOG_DAYS] back, so a single "last date" is not enough --
* a dismiss on Tuesday would be forgotten by Wednesday's.
*/
object DateHistory {
/** Kept comfortably longer than the backlog. */
private const val KEEP_DAYS = 14L
/** Adds [day] and drops entries older than [KEEP_DAYS]; `commit()`s. */
fun add(prefs: SharedPreferences, key: String, day: LocalDate) {
val floor = day.minusDays(KEEP_DAYS)
val kept = read(prefs, key).filter { iso ->
runCatching { !LocalDate.parse(iso).isBefore(floor) }.getOrDefault(false)
}.toSet() + day.toString()
prefs.edit().putStringSet(key, kept).commit()
}
fun contains(prefs: SharedPreferences, key: String, day: LocalDate): Boolean =
day.toString() in read(prefs, key)
// A copy: the set SharedPreferences returns must not be modified.
private fun read(prefs: SharedPreferences, key: String): Set<String> =
prefs.getStringSet(key, emptySet())?.toSet() ?: emptySet()
}

View File

@ -0,0 +1,27 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDate
/**
* The one rule both native day caches ([FreeDays], [SickDays]) answer by,
* as a pure function so it is checkable without a device.
*
* Fail closed: a read that throws or finds nothing means "not in the set",
* so a corrupt or missing cache restores the normal rules (the alarm rings,
* the stick applies) rather than standing everything down. That matches
* `freedays.is_free_day()` and `sickdays.is_sick_day()` on the PC.
*/
object DayCache {
/** Whether [day] (as `yyyy-MM-dd`) is in the set [read] returns. */
fun contains(
day: LocalDate,
onError: (RuntimeException) -> Unit = {},
read: () -> Set<String>?,
): Boolean = try {
read()?.contains(day.toString()) ?: false
} catch (e: RuntimeException) {
onError(e)
false
}
}

View File

@ -0,0 +1,75 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.time.LocalDate
/**
* The wake-enforcement methods on the one alarm channel ([AlarmChannel]
* delegates its unknown methods here, so that file stays under the cap).
*
* Dart reads the stick and the event log through this, appends its own
* events to the same log, and uses the escape hatch. Nothing here can lock
* or arm anything: the stick is decided natively by [StickRunner].
*/
object EnforcementChannel {
/** Handles [call] if it is one of ours; false leaves it unanswered. */
fun handleCall(context: Context, call: MethodCall, result: MethodChannel.Result): Boolean {
when (call.method) {
"appendEvent" -> {
val kind = call.argument<String>("kind")
if (kind == null) {
result.error("bad_args", "kind is required", null)
} else {
val data = call.argument<Map<String, Any?>>("data") ?: emptyMap()
EventLog.append(context, kind, data)
result.success(null)
}
}
"readEvents" -> result.success(EventLog.readJson(context))
"enforcementState" -> result.success(state(context))
// False once the hatch has closed; see EscapeHatch.
"escapeToday" -> result.success(EscapeHatch.use(context))
else -> return false
}
return true
}
/**
* Everything the stakes card and the ring line show, as plain values.
*
* `lockIfMiss*` comes from [StickCheck.afterMiss] -- the same function
* the enforcement runs -- so the date the screen promises is the date a
* miss would actually send.
*/
private fun state(context: Context): Map<String, Any?> {
val today = LocalDate.now()
val tomorrow = today.plusDays(1)
val stick = StickStore.load(context)
val alarm = AlarmScheduler.storedAlarm(context)
val isFree = { day: LocalDate -> FreeDays.isFree(context, day) }
val isSick = { day: LocalDate -> SickDays.isSick(context, day) }
val standsDown = { day: LocalDate -> isFree(day) || isSick(day) }
return mapOf(
"today" to today.toString(),
"alarmHour" to alarm?.hour,
"alarmMinute" to alarm?.minute,
"dismissedToday" to RingWatch.dismissedOn(context, today),
"escapedToday" to StickStore.escapedOn(context, today),
"freeToday" to isFree(today),
"freeTomorrow" to isFree(tomorrow),
"sickToday" to isSick(today),
"sickTomorrow" to isSick(tomorrow),
"streak" to stick.streak,
"lockedThrough" to stick.lockedThrough?.toString(),
"lastMiss" to stick.lastMiss?.toString(),
"updatedAt" to StickStore.updatedAt(context),
"lockIfMissToday" to
StickCheck.afterMiss(today, stick, standsDown).lockedThrough?.toString(),
"lockIfMissTomorrow" to
StickCheck.afterMiss(tomorrow, stick, standsDown).lockedThrough?.toString(),
)
}
}

View File

@ -0,0 +1,35 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.util.Log
import java.time.LocalDate
/**
* "That was a bug": excuses today's morning on the phone side.
*
* Marks today escaped (so no trigger can penalise it), clears the streak and
* any lockdown, tells focus-owner to lift, and logs both. The PC side reads
* the `escapes` field Dart publishes afterwards. Refused natively after
* [Stakes.escapeHatchLastDay] as well -- hiding the button is not the only
* guard.
*/
object EscapeHatch {
private const val TAG = "WakeAlarmEscape"
fun isOpen(today: LocalDate): Boolean = !today.isAfter(Stakes.escapeHatchLastDay)
/** False when the hatch has closed; nothing is changed then. */
@Synchronized
fun use(context: Context): Boolean {
val today = LocalDate.now()
if (!isOpen(today)) {
Log.w(TAG, "escape refused: the hatch closed after ${Stakes.escapeHatchLastDay}")
return false
}
StickStore.markEscaped(context, today)
EventLog.append(context, "escape_used", mapOf("date" to today.toString()))
WorkdayStick.sendLift(context)
EventLog.append(context, "lift_sent")
return true
}
}

View File

@ -0,0 +1,77 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.util.Log
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
/**
* The phone's bounded event log: `{"at", "kind", "data"}`, newest first,
* at most [MAX_ENTRIES] entries and [MAX_AGE_DAYS] days.
*
* Native, so the receivers that run with no Flutter engine (the alarm, the
* stick check, boot) can write it; Dart appends to the same log over the
* alarm channel and stages it as `phone_events` on every sync. This is the
* evidence the daily incident report merges with the PC's -- a morning that
* went wrong is reconstructed from here, not from memory.
*/
object EventLog {
private const val TAG = "WakeAlarmEvents"
private const val PREFS = "wake_alarm_events"
private const val KEY_EVENTS = "events"
const val MAX_ENTRIES = 400
const val MAX_AGE_DAYS = 14L
/** Seconds precision with an explicit offset, which `toString()` drops at :00. */
private val FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")
fun nowIso(): String = OffsetDateTime.now().format(FORMAT)
/** Appends one event stamped now. Never throws: logging must not break a ring. */
@Synchronized
fun append(context: Context, kind: String, data: Map<String, Any?> = emptyMap()) {
try {
val entry = JSONObject()
.put("at", nowIso())
.put("kind", kind)
.put("data", JSONObject(data.filterValues { it != null }))
val kept = JSONArray().put(entry)
val cutoff = OffsetDateTime.now().minusDays(MAX_AGE_DAYS)
val old = read(context)
for (i in 0 until old.length()) {
if (kept.length() >= MAX_ENTRIES) break
val event = old.optJSONObject(i) ?: continue
if (isAfter(event.optString("at"), cutoff)) kept.put(event)
}
prefs(context).edit().putString(KEY_EVENTS, kept.toString()).commit()
} catch (e: JSONException) {
Log.w(TAG, "event $kind not logged", e)
}
}
/** The whole log as a JSON array string, newest first. */
@Synchronized
fun readJson(context: Context): String = read(context).toString()
private fun read(context: Context): JSONArray = try {
JSONArray(prefs(context).getString(KEY_EVENTS, "[]") ?: "[]")
} catch (e: JSONException) {
// A corrupt log is replaced, not fatal: losing history beats losing
// every event from here on.
Log.w(TAG, "event log unreadable; starting over", e)
JSONArray()
}
private fun isAfter(at: String, cutoff: OffsetDateTime): Boolean = try {
OffsetDateTime.parse(at).isAfter(cutoff)
} catch (e: DateTimeParseException) {
false
}
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}

View File

@ -0,0 +1,48 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.util.Log
import java.time.LocalDate
/**
* The native copy of the shared free-day pool: the ISO dates on which the
* alarm must not ring.
*
* The alarm fires with no Flutter engine running, so the Dart-side pool
* (`free_day_pool.dart`) is unreadable at 08:00. Dart rewrites this cache
* after every local change and every sync; [AlarmReceiver] reads it before
* making any noise.
*
* Fail closed ([DayCache]): anything unreadable means "not a free day", so
* a corrupt or missing cache restores the normal rules rather than silencing
* the alarm. That matches `freedays.is_free_day()` on the PC.
*/
object FreeDays {
private const val TAG = "WakeAlarmFreeDays"
private const val PREFS = "wake_alarm_freedays"
private const val KEY_DATES = "free_dates"
/** Replaces the cached set with [isoDates] (`yyyy-MM-dd` each). */
fun store(context: Context, isoDates: List<String>) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putStringSet(KEY_DATES, isoDates.toSet())
.apply()
}
/** Whether today (local calendar day) is in the cached set. */
fun isToday(context: Context): Boolean = isFree(context, LocalDate.now())
/**
* Whether [day] is in the cached set. Past free days stay in it (Dart
* hands over every free record), which is what lets the stick's streak
* skip them.
*/
fun isFree(context: Context, day: LocalDate): Boolean = DayCache.contains(
day,
onError = { Log.w(TAG, "free-day cache unreadable; ringing as normal", it) },
) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet(KEY_DATES, emptySet())
}
}

View File

@ -0,0 +1,71 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
/**
* Publishes `ring_started` the moment the daily alarm fires, with no screen.
*
* The ring screen used to be the only source, and it does not always open:
* on an unlocked phone in use the full-screen intent is downgraded to a
* heads-up notification. Then no `ring_started` reached the PC, which rang
* `phone_silent` at a user who was awake and holding the phone. So the
* alarm itself starts a headless Flutter engine running `ringStartedMain`
* (`lib/main.dart` → `headless_ring_start.dart`), which records and pushes
* through the same `RingStartRecorder` as the screen. The first ring of the
* day wins; the screen's later publish is skipped once this one landed.
*
* The engine lives while [AlarmService] holds the process in the
* foreground. Dart says `done` on [CHANNEL]; [TIMEOUT_MS] destroys it
* regardless, so a hung network call cannot keep a second engine forever.
* Never throws: a failure here must never touch the ring.
*/
object HeadlessRingStart {
private const val TAG = "WakeAlarmHeadless"
const val CHANNEL = "com.kuhy.wake_alarm_sync/headless"
private const val ENTRYPOINT = "ringStartedMain"
private const val TIMEOUT_MS = 90_000L
private val handler = Handler(Looper.getMainLooper())
private var engine: FlutterEngine? = null
/** Starts the engine unless one is already running. Main thread only. */
fun start(context: Context) {
if (engine != null) return
try {
val app = context.applicationContext
val created = FlutterEngine(app)
engine = created
AlarmChannel.register(app, created)
MethodChannel(created.dartExecutor.binaryMessenger, CHANNEL)
.setMethodCallHandler { call, result ->
result.success(null)
// Posted: destroying an engine inside its own callback
// would tear the messenger down under the reply.
if (call.method == "done") handler.post { stop("done") }
}
val bundle = FlutterInjector.instance().flutterLoader().findAppBundlePath()
created.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint(bundle, ENTRYPOINT),
)
handler.postDelayed({ stop("timeout") }, TIMEOUT_MS)
Log.i(TAG, "headless ring_started engine started")
} catch (e: RuntimeException) {
Log.w(TAG, "headless engine failed; the ring screen still publishes", e)
stop("failed")
}
}
private fun stop(reason: String) {
handler.removeCallbacksAndMessages(null)
engine?.destroy()
engine = null
Log.i(TAG, "headless engine stopped: $reason")
}
}

View File

@ -0,0 +1,179 @@
package com.kuhy.wake_alarm_sync
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.net.wifi.WifiManager
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.content.ContextCompat
import java.util.concurrent.atomic.AtomicBoolean
/**
* Where the phone is right now, as raw observations only.
*
* Hand-written on the existing MethodChannel for the same reason the ring path
* is: the stack is AGP 9 / Gradle 9.1 / Kotlin 2.3.20 and a pub plugin that
* fails to compile breaks the build outright instead of degrading.
*
* **This decides nothing.** It reports a BSSID, a fix, and a distance; whether
* that means "home" is `home_presence.dart`'s job, so the policy stays unit
* testable without a device. The one exception is [distanceMeters], computed
* here because [Location.distanceBetween] is already on hand and putting the
* trig in Dart would mean hand-rolling Haversine in the file under test.
*
* Wi-Fi is tried first and, when it answers, GPS is never touched: at home the
* BSSID is instant and indoors a fix may take 30s or never arrive at all.
*/
object HomePresence {
private const val TAG = "WakeAlarmPresence"
/** What Android hands back instead of a real BSSID when it redacts one. */
private const val REDACTED_BSSID = "02:00:00:00:00:00"
/** A second redaction sentinel seen on some OEM builds. */
private const val ZERO_BSSID = "00:00:00:00:00:00"
/** What WifiManager reports for an SSID it will not disclose. */
private const val UNKNOWN_SSID = "<unknown ssid>"
/**
* Reads presence and hands the observations to [callback] on the main
* thread.
*
* Asynchronous because a fix can take seconds and this is called from the
* ring screen: blocking the platform thread there is an ANR while the
* alarm is sounding.
*/
fun read(
context: Context,
homeLat: Double?,
homeLon: Double?,
withFix: Boolean,
callback: (Map<String, Any?>) -> Unit,
) {
val main = Handler(Looper.getMainLooper())
val answered = AtomicBoolean(false)
fun done(payload: Map<String, Any?>) {
if (!answered.compareAndSet(false, true)) return
Log.i(TAG, "presence $payload")
main.post { callback(payload) }
}
if (!hasLocationPermission(context)) {
done(unreadable("no-permission"))
return
}
val manager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
// Location services off redacts the BSSID *and* kills every provider,
// so this single toggle is enough to make presence unreadable.
if (manager == null || !manager.isLocationEnabled) {
done(unreadable("location-disabled"))
return
}
val wifi = readWifi(context)
// At ring time a Wi-Fi answer ends it: GPS is skipped entirely, which
// is the whole reason the verdict is instant at home. Registration
// passes withFix so it captures a coordinate too — otherwise the GPS
// fallback could only ever be configured with Wi-Fi turned off, which
// means in practice never.
if (wifi != null && !withFix) {
done(observation(wifi = wifi, fix = null, homeLat, homeLon, "ok"))
return
}
val cached = LocationFix.freshestLastKnown(manager)
if (cached != null) {
done(observation(wifi = wifi, fix = cached, homeLat, homeLon, "ok"))
return
}
LocationFix.requestSingle(manager, main) { fix ->
if (fix == null && wifi == null) {
done(unreadable("no-fix"))
} else {
done(observation(wifi = wifi, fix = fix, homeLat, homeLon, "ok"))
}
}
}
private fun hasLocationPermission(context: Context): Boolean =
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
/**
* SSID and BSSID of the connected Wi-Fi, or null when neither can be
* trusted.
*
* Android redacts these to [REDACTED_BSSID] and [UNKNOWN_SSID] rather
* than failing when the fine-location grant or location services is
* missing — a redacted value looks exactly like a successful read, so it
* must be filtered here or every morning silently reads "away".
*
* Both are returned because a router hands out a *different* BSSID per
* band and a mesh node one per box, and the phone roams between them
* overnight. Matching on the BSSID alone would call a band switch
* "travelling".
*/
private fun readWifi(context: Context): Pair<String?, String?>? {
// getConnectionInfo() is deprecated at API 31 in favour of
// NetworkCapabilities.getTransportInfo(). Do NOT "modernise" this:
// the *synchronous* ConnectivityManager.getNetworkCapabilities()
// redacts every location-sensitive field, so transportInfo comes back
// null and the BSSID silently vanishes. Measured on the Pixel 6a
// (API 36, 2026-08-31): connected to a known AP, fine location
// granted, location services on, and the capabilities route still
// returned ssid=null bssid=null while the GPS fallback masked it.
// Un-redacted transportInfo needs a registerNetworkCallback, which is
// asynchronous and buys nothing here.
@Suppress("DEPRECATION")
val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE)
as? WifiManager
@Suppress("DEPRECATION")
val info = wm?.connectionInfo
val bssid = info?.bssid?.lowercase()?.takeUnless {
it.isBlank() || it == REDACTED_BSSID || it == ZERO_BSSID
}
val ssid = info?.ssid?.trim('"')?.takeUnless {
it.isBlank() || it == UNKNOWN_SSID
}
return if (bssid == null && ssid == null) null else Pair(ssid, bssid)
}
private fun observation(
wifi: Pair<String?, String?>?,
fix: Location?,
homeLat: Double?,
homeLon: Double?,
reason: String,
): Map<String, Any?> = mapOf(
"ssid" to wifi?.first,
"bssid" to wifi?.second,
"lat" to fix?.latitude,
"lon" to fix?.longitude,
"accuracy" to fix?.accuracy?.toDouble(),
"distanceMeters" to distanceMeters(fix, homeLat, homeLon),
"reason" to reason,
)
private fun distanceMeters(fix: Location?, homeLat: Double?, homeLon: Double?): Double? {
if (fix == null || homeLat == null || homeLon == null) return null
val out = FloatArray(1)
Location.distanceBetween(fix.latitude, fix.longitude, homeLat, homeLon, out)
return out[0].toDouble()
}
private fun unreadable(reason: String): Map<String, Any?> = mapOf(
"ssid" to null,
"bssid" to null,
"lat" to null,
"lon" to null,
"accuracy" to null,
"distanceMeters" to null,
"reason" to reason,
)
}

View File

@ -0,0 +1,94 @@
package com.kuhy.wake_alarm_sync
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.CancellationSignal
import android.os.Handler
import android.os.Looper
import java.util.concurrent.atomic.AtomicBoolean
/**
* A single location fix, hand-written on LocationManager.
*
* Split out of [HomePresence] to hold both files under the repo's 250-line
* cap, and because the two halves fail differently: the Wi-Fi read is
* instant and synchronous, a fix is neither.
*
* Everything here is best-effort — every path can hand back null, which
* [HomePresence] reports as unreadable.
*/
object LocationFix {
/** How long a single fix may take before the read gives up. */
private const val FIX_TIMEOUT_MS = 5_000L
/** How stale a cached fix may be and still count as "where we are". */
private const val LAST_KNOWN_MAX_AGE_MS = 10 * 60 * 1000L
/** The newest cached fix across every provider, if recent enough. */
fun freshestLastKnown(manager: LocationManager): Location? {
val cutoff = System.currentTimeMillis() - LAST_KNOWN_MAX_AGE_MS
return providers(manager)
.mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }
.filter { it.time >= cutoff }
.maxByOrNull { it.time }
}
/**
* Asks for one fix, giving up after [FIX_TIMEOUT_MS].
*
* The timeout is the point: without it a ring screen indoors waits on a
* GPS fix that is never coming, and the user waits with it.
*/
fun requestSingle(
manager: LocationManager,
main: Handler,
onResult: (Location?) -> Unit,
) {
val provider = providers(manager).firstOrNull { manager.isProviderEnabled(it) }
if (provider == null) {
onResult(null)
return
}
val settled = AtomicBoolean(false)
fun settle(fix: Location?) {
if (settled.compareAndSet(false, true)) onResult(fix)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val cancel = CancellationSignal()
main.postDelayed({
if (!settled.get()) cancel.cancel()
settle(null)
}, FIX_TIMEOUT_MS)
runCatching {
manager.getCurrentLocation(
provider,
cancel,
mainExecutor(main),
) { fix -> settle(fix) }
}.onFailure { settle(null) }
return
}
val listener = LocationListener { fix -> settle(fix) }
main.postDelayed({
manager.removeUpdates(listener)
settle(null)
}, FIX_TIMEOUT_MS)
runCatching {
@Suppress("DEPRECATION")
manager.requestSingleUpdate(provider, listener, Looper.getMainLooper())
}.onFailure { settle(null) }
}
/** Runs the fix callback on the main looper: one thread, no locking. */
private fun mainExecutor(main: Handler) = java.util.concurrent.Executor { main.post(it) }
/** Fused first (API 31+): it answers indoors where bare GPS does not. */
private fun providers(manager: LocationManager): List<String> = buildList {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) add(LocationManager.FUSED_PROVIDER)
add(LocationManager.NETWORK_PROVIDER)
add(LocationManager.GPS_PROVIDER)
}.filter { it in manager.allProviders }
}

View File

@ -1,5 +1,144 @@
package com.kuhy.wake_alarm_sync
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity()
/**
* The normal app entry point (the time picker).
*
* Registers the same alarm channel as [AlarmActivity] so the picker can arm,
* cancel and re-arm without going through the ring screen.
*/
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (resumeMorning()) return
requestAlarmPermissions()
}
/**
* Steps aside into [AlarmActivity] while the morning is live: a ring is
* sounding, or today's session is still on a leg.
*
* Decided here, natively, before any Dart runs: the home screen must
* never come up mid-session (a home gesture used to be a way out with
* no way back, 2026-09-17), and the permission prompt above must never
* appear over a ring. Checked on resume as well as create -- this
* activity is `singleTop`, and a warm instance brought back from the
* launcher never re-runs onCreate.
*/
private fun resumeMorning(): Boolean {
if (!AlarmService.running && !SessionNotice.isLiveToday(this)) return false
startActivity(SessionNotice.resumeIntent(this))
finishAndRemoveTask()
return true
}
/**
* Asks for the two runtime permissions the alarm cannot work without.
*
* POST_NOTIFICATIONS (API 33+): without the grant the app sits at
* importance=NONE, the full-screen intent is rejected before it is even
* considered, and the alarm rings with no dismiss screen. Measured on the
* API 36 AVD, where a freshly installed app is blocked by default.
*
* ACTIVITY_RECOGNITION (API 29+): TYPE_STEP_COUNTER delivers nothing
* without it, so the steps fallback would report "sensor unavailable"
* forever. That matters because a room proof that can never be satisfied
* makes the alarm undismissable, not merely degraded.
*
* ACCESS_FINE_LOCATION (API 23+): without it the connected Wi-Fi's BSSID
* comes back redacted and every provider is silent, so HomePresence can
* never answer. Unreadable means away, so a missing grant would drop the
* strict tag stages at home too. This is the ONLY place it is asked for:
* a permission dialog must never appear over a ringing alarm.
*/
private fun requestAlarmPermissions() {
val wanted = arrayOf(
Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.ACTIVITY_RECOGNITION,
Manifest.permission.ACCESS_FINE_LOCATION,
)
val missing = wanted.filter {
ContextCompat.checkSelfPermission(this, it) !=
PackageManager.PERMISSION_GRANTED
}
if (missing.isEmpty()) return
ActivityCompat.requestPermissions(
this,
missing.toTypedArray(),
NOTIFICATION_REQUEST_CODE,
)
}
/** Kept so NFC reader mode can push tag ids back to the Settings screen. */
private var alarmChannel: MethodChannel? = null
/** True while Settings is waiting for a tag to register. */
private var registeringTag = false
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
AlarmChannel.register(this, flutterEngine)
val channel = AlarmActivity.channel(flutterEngine)
alarmChannel = channel
// Registration needs an Activity for reader mode, which the shared
// channel handler cannot supply — it holds applicationContext.
channel.setMethodCallHandler { call, result ->
when (call.method) {
"startTagRegistration" -> {
registeringTag = NfcReader.start(this, channel)
result.success(registeringTag)
}
// Finishes the picker after starting a test ring, so it
// cannot sit on top of AlarmActivity — that pause used to
// tear NFC reader mode down for the whole ring.
"ringNow" -> {
AlarmChannel.handleCall(applicationContext, call, result)
// An unlocked, in-use device downgrades the full-screen
// intent to a heads-up notification (appops logs a
// rejectTime), so the ring screen would never appear on
// its own during a hardware test. Launch it directly and
// step out of the way: leaving the picker in front pauses
// AlarmActivity, which used to kill NFC reader mode.
startActivity(
Intent(this, AlarmActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
},
)
finishAndRemoveTask()
}
"stopTagRegistration" -> {
registeringTag = false
NfcReader.stop(this)
result.success(null)
}
else -> AlarmChannel.handleCall(applicationContext, call, result)
}
}
}
override fun onPause() {
if (registeringTag) NfcReader.stop(this)
super.onPause()
}
override fun onResume() {
super.onResume()
if (resumeMorning()) return
if (registeringTag) alarmChannel?.let { NfcReader.start(this, it) }
}
private companion object {
/** Request code for the notification permission prompt. */
const val NOTIFICATION_REQUEST_CODE = 2001
}
}

View File

@ -0,0 +1,74 @@
package com.kuhy.wake_alarm_sync
import android.app.Activity
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.util.Log
import io.flutter.plugin.common.MethodChannel
/**
* Reads NFC tag ids while the ring screen is up.
*
* Hand-written on the existing MethodChannel rather than `nfc_manager`, for
* the same reason the ring path is: nothing on the dismiss path may depend on
* a plugin compiling against AGP 9. If NFC and QR were both plugins and both
* failed, item 3 would have no working proof at all.
*
* Reader mode (rather than the foreground-dispatch intent flow) is what lets
* a tag be read without the activity being restarted, which matters because
* restarting the ring screen would reset the challenge.
*/
object NfcReader {
/** Dart method invoked with the scanned tag id. */
private const val ON_TAG = "onNfcTag"
/** Tag technologies to poll; covers the common cheap NTAG stickers. */
private const val FLAGS =
NfcAdapter.FLAG_READER_NFC_A or
NfcAdapter.FLAG_READER_NFC_B or
NfcAdapter.FLAG_READER_NFC_F or
NfcAdapter.FLAG_READER_NFC_V or
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS
/**
* Starts polling, pushing each tag id to Dart over [channel].
*
* Returns false when the device has no NFC or it is switched off, so the
* ring screen can say so rather than waiting on a tap that cannot come.
*/
fun start(activity: Activity, channel: MethodChannel): Boolean {
val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return false
if (!adapter.isEnabled) return false
adapter.enableReaderMode(
activity,
{ tag ->
val id = idOf(tag)
Log.i(TAG, "tag discovered: $id")
activity.runOnUiThread { channel.invokeMethod(ON_TAG, id) }
},
FLAGS,
null,
)
Log.i(TAG, "reader mode started on ${activity.javaClass.simpleName}")
return true
}
/** Logcat tag for diagnosing why a tap did or did not arrive. */
private const val TAG = "WakeAlarmNfc"
/** Whether this device can read NFC at all and has it switched on. */
fun isAvailable(context: android.content.Context): Boolean {
val adapter = NfcAdapter.getDefaultAdapter(context) ?: return false
return adapter.isEnabled
}
/** Stops polling; safe to call when [start] returned false. */
fun stop(activity: Activity) {
NfcAdapter.getDefaultAdapter(activity)?.disableReaderMode(activity)
}
/** Lower-case hex of the tag's id, which is what Settings registers. */
private fun idOf(tag: Tag): String =
tag.id.joinToString("") { "%02x".format(it) }
}

View File

@ -0,0 +1,88 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
/**
* The background sync of both day pools before the alarm ([PoolSyncSchedule]).
*
* The ring decision itself stays a cache read: [AlarmReceiver] spends its
* short alarm-clock exemption starting [AlarmService], and a network call
* there could cost the ring. So the network happens *earlier*, here, and
* the receiver keeps reading whatever the last sync left -- including a
* failed one's (fail closed: no cache entry means ring).
*
* [AlarmManager.setExactAndAllowWhileIdle], not setAlarmClock: a sync must
* never show as the "next alarm". Falls back to the inexact
* setAndAllowWhileIdle when exact alarms are refused -- a sync a few
* minutes late is fine. Own receiver and request code ([REQUEST_CODE]),
* never [AlarmReceiver], which would ring.
*
* Armed from [AlarmScheduler.schedule] (every arm path, boot included) and
* re-armed by its own receiver.
*/
object PoolSyncAlarm {
private const val REQUEST_CODE = 1006
private const val TAG = "WakeAlarmPoolSync"
fun schedule(context: Context, alarm: LocalTime?) {
val at = PoolSyncSchedule.next(LocalDateTime.now(), alarm)
val millis = at.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
Log.i(TAG, "pool sync armed for $at via ${arm(context, millis)}")
}
/** Arms [millis], exactly when permitted; returns which API did it. */
private fun arm(context: Context, millis: Long): String {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val exactAllowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
manager.canScheduleExactAlarms()
if (exactAllowed) {
try {
manager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
millis,
pendingIntent(context),
)
return "setExactAndAllowWhileIdle"
} catch (e: SecurityException) {
Log.w(TAG, "exact alarm refused; arming inexact", e)
}
}
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, millis, pendingIntent(context))
return "setAndAllowWhileIdle"
}
fun cancel(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(pendingIntent(context))
}
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, PoolSyncReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/**
* Receives [PoolSyncAlarm]: re-arms the next slot first (so a crash below
* cannot end the chain), then holds the broadcast open with goAsync while
* [PoolSyncEngine] syncs. Holding it keeps the process out of the cached
* state, where Android would freeze the Dart isolate mid-request.
*/
class PoolSyncReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
PoolSyncAlarm.schedule(context, AlarmScheduler.storedAlarm(context))
val pending = goAsync()
PoolSyncEngine.run(context) { pending.finish() }
}
}

View File

@ -0,0 +1,74 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
/**
* A headless Flutter engine running `poolSyncMain` (`lib/main.dart` ->
* `day_pool_refresh.dart`): pulls the free- and sick-day pools and rewrites
* [FreeDays] and [SickDays] through [AlarmChannel] -- the same Dart sync the
* screens use, so the RTDB wire format has one implementation on the phone.
*
* Same shape as [HeadlessRingStart]. Dart says `done` on [CHANNEL];
* [TIMEOUT_MS] destroys the engine regardless. That bound sits well inside
* the 60 s a background broadcast may stay open, since [PoolSyncReceiver]
* holds one for exactly this long. Never throws.
*/
object PoolSyncEngine {
private const val TAG = "WakeAlarmPoolSync"
const val CHANNEL = "com.kuhy.wake_alarm_sync/poolsync"
private const val ENTRYPOINT = "poolSyncMain"
private const val TIMEOUT_MS = 25_000L
private val handler = Handler(Looper.getMainLooper())
private var engine: FlutterEngine? = null
private var onFinished: (() -> Unit)? = null
private val timeout = Runnable { stop("timeout") }
/** Runs one sync, then calls [finished]. Main thread only. */
fun run(context: Context, finished: () -> Unit) {
if (engine != null) {
// One sync at a time; the running one covers this slot too.
finished()
return
}
onFinished = finished
try {
val app = context.applicationContext
val created = FlutterEngine(app)
engine = created
AlarmChannel.register(app, created)
MethodChannel(created.dartExecutor.binaryMessenger, CHANNEL)
.setMethodCallHandler { call, result ->
result.success(null)
// Posted: destroying an engine inside its own callback
// would tear the messenger down under the reply.
if (call.method == "done") handler.post { stop("done") }
}
val bundle = FlutterInjector.instance().flutterLoader().findAppBundlePath()
created.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint(bundle, ENTRYPOINT),
)
handler.postDelayed(timeout, TIMEOUT_MS)
Log.i(TAG, "pool sync engine started")
} catch (e: RuntimeException) {
Log.w(TAG, "pool sync engine failed; the caches keep their last sync", e)
stop("failed")
}
}
private fun stop(reason: String) {
handler.removeCallbacks(timeout)
engine?.destroy()
engine = null
Log.i(TAG, "pool sync engine stopped: $reason")
onFinished?.invoke()
onFinished = null
}
}

View File

@ -0,0 +1,35 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDateTime
import java.time.LocalTime
/**
* When [PoolSyncAlarm] fires, as a pure function of the clock and the
* stored alarm -- no Context, so every case is checkable in isolation.
*
* Two slots a day, so a free or sick day marked on the PC reaches the
* native caches before the morning ring without the app being opened:
* - [EVENING] (21:00): the phone is usually awake and online, which makes
* it the dependable slot for anything marked during the day.
* - A - [LEAD_MINUTES]: catches a mark made late at night. The phone is
* usually in Doze by then; an allow-while-idle alarm gets a short network
* window, enough for two small RTDB reads, but not a guarantee.
*/
object PoolSyncSchedule {
/** The evening slot. */
val EVENING: LocalTime = LocalTime.of(21, 0)
/** How long before the alarm the morning slot runs. */
const val LEAD_MINUTES = 30L
/** The earliest slot strictly after [now]; only [EVENING] when no alarm is stored. */
fun next(now: LocalDateTime, alarm: LocalTime?): LocalDateTime {
val times = listOfNotNull(EVENING, alarm?.minusMinutes(LEAD_MINUTES))
val today = now.toLocalDate()
return listOf(today, today.plusDays(1))
.flatMap { day -> times.map { day.atTime(it) } }
.filter { it.isAfter(now) }
.min()
}
}

View File

@ -0,0 +1,21 @@
package com.kuhy.wake_alarm_sync
/** Why the daily alarm stays silent; [wire] is the `alarm_fired` event's `reason`. */
enum class RingSkip(val wire: String, val label: String) {
FREE_DAY("free_day", "free day"),
SICK_DAY("sick_day", "sick day"),
}
/**
* Whether the daily alarm rings, as a pure function of the two native day
* caches, so the rule is checkable without a device. A date is never in
* both pools; if a sync race ever put it there, the free day is named.
*/
object RingDecision {
/** The reason to stay silent, or null to ring. */
fun skip(isFree: Boolean, isSick: Boolean): RingSkip? = when {
isFree -> RingSkip.FREE_DAY
isSick -> RingSkip.SICK_DAY
else -> null
}
}

View File

@ -0,0 +1,59 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.util.Calendar
import java.util.Locale
/**
* Tracks, natively, whether today's ring was ever dismissed.
*
* The dismiss gate (tag1 -> steps -> tag2 -> challenges) lives in Dart, but a
* phone powered off before touching any of it never runs Dart at all that
* morning -- there is no session, no store, nothing to ask. Two dates, set
* from opposite ends of the ring, are enough to answer "was this abandoned"
* with no engine required:
*
* - [markFired] -- called from [AlarmReceiver], the instant a *fresh*
* (non-re-ring) alarm fires. This runs well before a poweroff mid-ring
* could ever prevent it -- setAlarmClock has already woken the CPU.
* - [markDismissed] -- called from Dart over the alarm channel, the instant
* the initial dismiss gate actually completes (`session_handoff.dart`'s
* `afterDismiss`).
*
* The stick ([StickCheck]) reads only [dismissedOn]. It used to ask "did a
* ring fire and go undismissed", which needs the *fired* date -- and a phone
* switched off before the alarm never fires, so that escaped everything.
* The fired date stays as evidence for whoever debugs a morning.
*/
object RingWatch {
private const val PREFS = "wake_alarm_ring_watch"
private const val KEY_FIRED_DATE = "fired_date"
private const val KEY_DISMISSED_DATE = "dismissed_date"
private const val KEY_DISMISSED_DATES = "dismissed_dates"
fun markFired(context: Context) {
prefs(context).edit().putString(KEY_FIRED_DATE, today()).apply()
}
fun markDismissed(context: Context) {
prefs(context).edit().putString(KEY_DISMISSED_DATE, today()).apply()
DateHistory.add(prefs(context), KEY_DISMISSED_DATES, LocalDate.now())
}
/**
* Whether the dismiss gate completed on [day]; read by [StickRunner],
* which judges past days too. The single [KEY_DISMISSED_DATE] predates
* the history and still answers for its one day.
*/
fun dismissedOn(context: Context, day: LocalDate): Boolean =
DateHistory.contains(prefs(context), KEY_DISMISSED_DATES, day) ||
prefs(context).getString(KEY_DISMISSED_DATE, null) == day.toString()
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun today(): String =
SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Calendar.getInstance().time)
}

View File

@ -0,0 +1,108 @@
package com.kuhy.wake_alarm_sync
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import java.time.LocalDate
/**
* The native copy of the live morning session: which leg is waiting and when
* it re-rings, plus the ongoing notification that shows the same.
*
* Two jobs, one record. The launcher starts [MainActivity], and it has to
* know *before any Dart runs* whether to step aside into the session screen;
* the notification needs the leg text with no engine running behind it.
* Dart rewrites this cache on every leg change (`updateSessionNotice`) and
* `finishSession` clears it, so it is only ever as stale as the last change.
*
* The record carries the session's date and [isLiveToday] refuses any other:
* a cache left behind by a session that never finished (the phone died
* mid-morning) must not open a dead checklist the next evening -- the same
* class of bug as the re-ring instant `restoreReRing` drops.
*
* Fail closed: unreadable means "no session", so a corrupt cache costs the
* shortcut, never the home screen.
*/
object SessionNotice {
private const val TAG = "WakeAlarmSession"
private const val PREFS = "wake_alarm_session"
private const val KEY_DATE = "date"
private const val KEY_LABEL = "label"
private const val CHANNEL_ID = "wake_alarm_session"
private const val NOTIFICATION_ID = 43
/** Intent extra naming the Dart route [AlarmActivity] should open with. */
const val EXTRA_ROUTE = "route"
/** The session screen's route in main.dart. */
const val SESSION_ROUTE = "/session"
/** Records [label] for [date] and posts (or updates) the notification. */
fun update(context: Context, date: String, label: String, deadlineMillis: Long?) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_DATE, date)
.putString(KEY_LABEL, label)
.apply()
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(
NotificationChannel(CHANNEL_ID, "Morning session", NotificationManager.IMPORTANCE_LOW)
.apply { description = "The live morning checklist" },
)
manager.notify(NOTIFICATION_ID, build(context, label, deadlineMillis))
}
/** Drops the record and the notification; the session's finish path only. */
fun clear(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply()
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.cancel(NOTIFICATION_ID)
}
/** Whether a session dated today (local calendar day) is still live. */
fun isLiveToday(context: Context): Boolean = try {
val date = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_DATE, null)
date == LocalDate.now().toString()
} catch (e: RuntimeException) {
Log.w(TAG, "session cache unreadable; treating as no session", e)
false
}
/** Opens [AlarmActivity] on the session screen, or brings the live one forward. */
fun resumeIntent(context: Context): Intent =
Intent(context, AlarmActivity::class.java)
.putExtra(EXTRA_ROUTE, SESSION_ROUTE)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
private fun build(context: Context, label: String, deadlineMillis: Long?): Notification {
val tap = PendingIntent.getActivity(
context,
NOTIFICATION_ID,
resumeIntent(context),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val builder = Notification.Builder(context, CHANNEL_ID)
.setContentTitle("Morning session")
.setContentText(label)
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setCategory(Notification.CATEGORY_REMINDER)
.setContentIntent(tap)
.setOngoing(true)
// Re-posted on every leg change; a buzz each time would be noise.
.setOnlyAlertOnce(true)
if (deadlineMillis != null) {
// The system renders the countdown itself, so Dart never has to
// tick this notification: one post per leg is enough.
builder.setWhen(deadlineMillis)
.setUsesChronometer(true)
.setChronometerCountDown(true)
.setShowWhen(true)
}
return builder.build()
}
}

View File

@ -0,0 +1,85 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.os.Build
import android.os.VibrationAttributes
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
/**
* A silent buzz [LEAD_MS] before each morning-session deadline.
*
* Armed and cleared only alongside the re-ring in [AlarmScheduler], so it
* cannot outlive or drift from the deadline it warns about.
*/
object SessionWarn {
private const val TAG = "WakeAlarmSession"
/** Distinct from 1001 (daily) and 1003 (re-ring): PendingIntents key on it. */
private const val REQUEST_CODE = 1004
const val LEAD_MS = 3 * 60_000L
private val PATTERN = longArrayOf(0, 400, 200, 400, 200, 400)
/** The buzz instant, or null once it has passed (BOOT_COMPLETED replays). */
fun warnAt(deadlineMs: Long, nowMs: Long): Long? =
(deadlineMs - LEAD_MS).takeIf { it > nowMs }
fun arm(context: Context, deadlineMs: Long) {
val at = warnAt(deadlineMs, System.currentTimeMillis())
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (at == null) {
manager.cancel(pendingIntent(context))
return
}
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pendingIntent(context))
}
fun clear(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(pendingIntent(context))
}
internal fun buzz(context: Context) {
val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as? VibratorManager)
?.defaultVibrator
} else {
@Suppress("DEPRECATION")
context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
} ?: return
val effect = VibrationEffect.createWaveform(PATTERN, -1)
// Alarm usage, so Do Not Disturb and a backgrounded app still buzz.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
vibrator.vibrate(effect, VibrationAttributes.createForUsage(VibrationAttributes.USAGE_ALARM))
} else {
val audio = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
@Suppress("DEPRECATION")
vibrator.vibrate(effect, audio)
}
Log.i(TAG, "deadline warning buzzed")
}
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, SessionWarnReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Buzzes only while today's session is live; a stale alarm stays silent. */
class SessionWarnReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!SessionNotice.isLiveToday(context) || AlarmService.running) return
SessionWarn.buzz(context)
}
}

View File

@ -0,0 +1,71 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.util.Log
import java.time.LocalDate
/**
* The native copy of the shared sick-day pool (`~/src/utils/sickdays`): the
* ISO dates on which the alarm must not ring and the stick stands down.
*
* Not every sick day: since sickdays 0.2.0 a sick day may *keep* some
* lockers active, and Dart writes here only the days on which the `alarm`
* locker stands down (sick, alarm not kept; `SickDayPool.standDownIsoDates`
* in `sick_day_pool.dart`). A sick day that keeps the alarm is absent, so
* it rings, judges the stick and shows its stakes like a normal day. Every
* reader of this cache ([RingDecision], [StickCheck], the stakes card via
* [EnforcementChannel]) therefore means "the alarm stands down", and none
* of them needs to know the keep set exists.
*
* A separate cache from [FreeDays], with its own prefs file, because the
* pools are separate things: a sick day is never called a free day, in a
* log line or anywhere else. Dart rewrites it after every mark, clear and
* sync (`sick_day_sync.dart`), including the pre-alarm sync
* ([PoolSyncReceiver]) that brings a PC mark in with the app closed.
*
* Fail closed ([DayCache]): unreadable means "not a sick day", so the
* alarm rings.
*/
object SickDays {
private const val TAG = "WakeAlarmSickDays"
private const val PREFS = "wake_alarm_sickdays"
private const val KEY_DATES = "sick_dates"
/** Replaces the cached set with [isoDates] (`yyyy-MM-dd` each). */
fun store(context: Context, isoDates: List<String>) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putStringSet(KEY_DATES, isoDates.toSet())
.apply()
Log.i(TAG, "native cache stored: ${isoDates.sorted()}")
}
/**
* The cached dates, sorted, for the picker's read-back line (the only
* way to see this cache on a release build); null when unreadable,
* which the ring path treats as "not a sick day".
*/
fun dates(context: Context): List<String>? {
val dates = try {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet(KEY_DATES, emptySet())?.sorted()
} catch (e: RuntimeException) {
Log.w(TAG, "sick-day cache unreadable", e)
null
}
Log.i(TAG, "native cache read: $dates")
return dates
}
/** Whether today (local calendar day) is in the cached set. */
fun isToday(context: Context): Boolean = isSick(context, LocalDate.now())
/** Whether [day] is in the cached set; past sick days stay in it. */
fun isSick(context: Context, day: LocalDate): Boolean = DayCache.contains(
day,
onError = { Log.w(TAG, "sick-day cache unreadable; ringing as normal", it) },
) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet(KEY_DATES, emptySet())
}
}

View File

@ -0,0 +1,25 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDate
/**
* The native copies of the wake-enforcement numbers (`DOCS-wake-enforcement.md`).
*
* The stick decides with no Flutter engine running, so it cannot read
* `lib/services/stakes.dart`. `wake_alarm/tests/test_stakes_mirrors.py`
* fails when these drift from the Dart and Python copies -- keep each
* literal on one line so that test can parse it.
*/
object Stakes {
/** A ring not dismissed this long after the alarm is a miss (`SESSION_NONE_GRACE`). */
const val STICK_GRACE_MINUTES = 15L
/** A lockdown never spans more calendar days than this, today included. */
const val STICK_LOCKDOWN_MAX_DAYS = 5
/** The escape hatch's last usable day, inclusive. */
const val ESCAPE_HATCH_LAST_DAY = "2026-10-15"
/** [ESCAPE_HATCH_LAST_DAY] as a date. */
val escapeHatchLastDay: LocalDate = LocalDate.parse(ESCAPE_HATCH_LAST_DAY)
}

View File

@ -0,0 +1,145 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
/**
* Steps taken since the alarm started ringing.
*
* Hand-written on the existing MethodChannel rather than a pub plugin, for the
* same reason the ring path is: no plugin can break the build.
*
* TYPE_STEP_COUNTER reports steps since boot, so "since ring start" is the
* difference against a baseline captured when the alarm fires. Steps are the
* *fallback* room proof only — the phone is stationary while you walk to it, so
* steps alone can be faked by shaking it in bed. NFC or QR is the real proof.
*/
object StepCounter {
private const val PREFS = "wake_alarm_steps"
private const val KEY_BASELINE = "baseline"
/** Sentinel for "no baseline captured yet". */
private const val NONE = -1L
/** Most recent cumulative total seen, kept so reads never block. */
@Volatile
private var latest: Long? = null
/**
* Steps counted by TYPE_STEP_DETECTOR since [markRingStart].
*
* The detector fires once per step, so it needs no baseline and reports
* the very first stride. The counter (TYPE_STEP_COUNTER) is on-change and
* cumulative, so on its own it delivers nothing until the user has
* already walked — which is why a phone sitting still reported a step
* sensor that "does not work". The detector is now primary and the
* counter is the cross-check.
*/
@Volatile
private var detected: Long = 0
/** The single registered listener; kept so rings do not accumulate them. */
private var listener: SensorEventListener? = null
/**
* Starts listening and records the first reading as this ring's baseline.
*
* Registration is fire-and-forget: the sensor callback arrives on its own
* thread, so nothing here blocks the MethodChannel — this runs on the
* platform main thread, where a multi-second wait is an ANR.
*/
fun markRingStart(context: Context) {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
prefs.edit().remove(KEY_BASELINE).apply()
detected = 0
listen(context) { total ->
// Only the first sample after a ring starts becomes the baseline.
if (!prefs.contains(KEY_BASELINE)) {
prefs.edit().putLong(KEY_BASELINE, total).apply()
}
}
// TYPE_STEP_COUNTER is an on-change sensor: it reports only when the
// user actually steps, so registering alone can leave us with no
// sample for minutes. requestTriggerSensor is not available for it,
// but SENSOR_DELAY_FASTEST plus an immediate flush() asks the
// hardware FIFO to deliver the current cumulative total now, which is
// what makes the baseline correct from the first tap rather than
// silently swallowing the user's first strides.
flush(context)
}
/** Asks the sensor FIFO to deliver any batched sample immediately. */
private fun flush(context: Context) {
val manager =
context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return
listener?.let { manager.flush(it) }
}
/**
* Steps since [markRingStart], or -1 when unavailable.
*
* -1 (rather than 0) so the Dart side can tell "no step sensor / no
* baseline" apart from "hasn't moved yet" and fall back to another proof.
*/
fun stepsSinceRingStart(context: Context): Long {
// The detector is authoritative: it counts every stride since the ring
// started, with no baseline to miss. Only fall back to the cumulative
// counter when there is no detector on the device.
if (hasDetector) return detected
val baseline = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getLong(KEY_BASELINE, NONE)
if (baseline == NONE) return NONE
val current = latest ?: return NONE
return (current - baseline).coerceAtLeast(0)
}
/** Whether this device exposes TYPE_STEP_DETECTOR, set when listening starts. */
@Volatile
private var hasDetector: Boolean = false
/**
* Registers a step listener, keeping [latest] fresh for later reads.
*
* The listener is deliberately never unregistered while the alarm rings:
* the ring screen polls repeatedly, and re-registering per read would cost
* a fresh sensor warm-up each time.
*/
@Synchronized
private fun listen(context: Context, onFirst: (Long) -> Unit) {
val manager =
context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return
val counter = manager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
val detector = manager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
if (counter == null && detector == null) return
// One registration per process: markRingStart runs on every ring, and
// an unregistered listener per ring would accumulate for the lifetime
// of the app.
listener?.let { manager.unregisterListener(it) }
val fresh = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
when (event.sensor.type) {
// Fires once per stride; each event is exactly one step.
Sensor.TYPE_STEP_DETECTOR -> detected++
Sensor.TYPE_STEP_COUNTER -> {
val total = event.values.firstOrNull()?.toLong() ?: return
latest = total
onFirst(total)
}
else -> Unit
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
}
listener = fresh
hasDetector = detector != null
// FASTEST so the first stride registers immediately; these sensors are
// low-rate by nature, so this costs nothing meaningful.
detector?.let { manager.registerListener(fresh, it, SensorManager.SENSOR_DELAY_FASTEST) }
counter?.let { manager.registerListener(fresh, it, SensorManager.SENSOR_DELAY_FASTEST) }
}
}

View File

@ -0,0 +1,122 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeParseException
/**
* The exact alarm at A + [Stakes.STICK_GRACE_MINUTES] that runs the stick
* check (trigger `exact`).
*
* [AlarmManager.setExactAndAllowWhileIdle], not setAlarmClock: an alarm
* clock entry would show in the system clock as the "next alarm" between A
* and A + 15. This check rings nothing, so it needs no alarm-clock status;
* `USE_EXACT_ALARM` (declared for the daily alarm) grants exact alarms at
* install. Only if exact alarms are not permitted after all does it fall
* back to setAlarmClock -- a visible chip beats a check that never runs.
*
* Its own receiver and request code ([REQUEST_CODE]), never [AlarmReceiver]:
* anything that reached that receiver without the re-ring extra would be
* treated as the daily alarm and *ring*.
*
* Armed from [AlarmScheduler.schedule], i.e. by every arm path. The instant
* is the next occurrence of (A + 15) on its own, and an instant already
* armed for today is kept against a later one ([StickSchedule.choose]):
* otherwise a re-arm between A and A + 15 -- the dismiss, the free-day
* skip, opening the app, boot -- would push today's check to tomorrow,
* which is exactly the window a phone switched back on lands in.
*/
object StickAlarm {
private const val REQUEST_CODE = 1004
private const val SHOW_REQUEST_CODE = 1005
private const val PREFS = "wake_alarm_stick_alarm"
private const val KEY_PENDING_AT = "pending_at"
private const val TAG = "WakeAlarmStickAlarm"
fun schedule(context: Context, alarm: LocalTime) {
val now = LocalDateTime.now()
val at = StickSchedule.choose(
now,
StickSchedule.nextOccurrence(now, alarm),
pendingAt(context),
)
// Always re-set, even when the pending instant is kept: a reboot
// drops every AlarmManager alarm, and boot is one of the callers.
prefs(context).edit().putString(KEY_PENDING_AT, at.toString()).commit()
val millis = at.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
val how = arm(context, millis)
Log.i(TAG, "stick check armed for $at via $how")
}
/** Arms [millis] exactly; returns which API did it, for the log. */
private fun arm(context: Context, millis: Long): String {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val exactAllowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
manager.canScheduleExactAlarms()
if (exactAllowed) {
try {
manager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
millis,
firePendingIntent(context),
)
return "setExactAndAllowWhileIdle"
} catch (e: SecurityException) {
Log.w(TAG, "exact alarm refused; falling back to setAlarmClock", e)
}
}
manager.setAlarmClock(
AlarmManager.AlarmClockInfo(millis, showIntent(context)),
firePendingIntent(context),
)
return "setAlarmClock"
}
fun cancel(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(firePendingIntent(context))
prefs(context).edit().remove(KEY_PENDING_AT).commit()
}
private fun pendingAt(context: Context): LocalDateTime? = try {
prefs(context).getString(KEY_PENDING_AT, null)?.let { LocalDateTime.parse(it) }
} catch (e: DateTimeParseException) {
null
}
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun firePendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, StickCheckReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity(
context,
SHOW_REQUEST_CODE,
Intent(context, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Receives [StickAlarm]: runs the check, then arms tomorrow's. */
class StickCheckReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
StickRunner.run(context, "exact")
// After an undismissed ring nothing else re-arms until the watchdog
// or the next app launch, so the check re-arms itself. The instant
// that just fired is now in the past, so choose() drops it.
AlarmScheduler.storedAlarm(context)?.let { StickAlarm.schedule(context, it) }
}
}

View File

@ -0,0 +1,178 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
/** What one stick check concluded; [wire] is the `stick_check` event's `verdict`. */
enum class StickVerdict(val wire: String, val final: Boolean = true) {
NO_ALARM("no_alarm"),
NOT_STICK_DAY("not_stick_day"),
FREE_DAY("free_day"),
SICK_DAY("sick_day"),
ESCAPED("escaped"),
ALREADY_PENALISED("already_penalised"),
DISMISSED("dismissed"),
TOO_EARLY("too_early", final = false),
MISS("miss"),
}
/** The persisted stick: the streak and the lockdown it bought. */
data class StickState(
val streak: Int = 0,
val lockedThrough: LocalDate? = null,
val lastMiss: LocalDate? = null,
)
/** Everything one run reads; gathered by [StickRunner], decided here. */
data class StickInputs(
val now: LocalDateTime,
/** The stored daily alarm `A`, or null when none is stored. */
val alarm: LocalTime?,
val dismissedOn: (LocalDate) -> Boolean,
val escapedOn: (LocalDate) -> Boolean,
/** The native free-day cache; fail-closed, so unreadable is `false`. */
val isFree: (LocalDate) -> Boolean,
/** The native sick-day cache; fail-closed, so unreadable is `false`. */
val isSick: (LocalDate) -> Boolean,
val state: StickState,
/** The last day whose verdict was final, or null before the first run. */
val checkedThrough: LocalDate?,
)
/** One day's verdict within a run. */
data class DayVerdict(val day: LocalDate, val verdict: StickVerdict)
/**
* A run's result: each day judged, the state to persist, how far days are
* now settled, and the lockdown to signal (null when no miss in this run
* locks through today or later).
*/
data class StickRun(
val verdicts: List<DayVerdict>,
val state: StickState,
val checkedThrough: LocalDate,
val signalUntil: LocalDate?,
)
/**
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
* so every rule here is checkable in isolation.
*
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
* neither a free day nor a sick day, whose alarm passed by at least [Stakes.STICK_GRACE_MINUTES]
* with no dismiss and no escape, and that has not already been penalised.
* Nothing here needs the ring to have *fired*: a phone switched off before
* the alarm misses exactly like one left ringing (hole 1 of the contract).
*/
object StickCheck {
/** How many past days a run catches up on (a phone off for days). */
const val BACKLOG_DAYS = 5L
/** How far back [previousStickDay] looks before giving up. */
private const val LOOKBACK_DAYS = 60L
/**
* Judges every unchecked day, oldest first, then today.
*
* Past days run from the day after [StickInputs.checkedThrough], at most
* [BACKLOG_DAYS] back -- in order, so the streak builds exactly as if
* each day had been checked on time. A first run (no checkedThrough)
* judges today only: days from before this stick existed have no
* dismiss records and must not be punished.
*/
fun run(inputs: StickInputs): StickRun {
val today = inputs.now.toLocalDate()
val verdicts = mutableListOf<DayVerdict>()
var state = inputs.state
var signal: LocalDate? = null
val checked = inputs.checkedThrough
var day = if (checked == null) {
today
} else {
maxOf(checked.plusDays(1), today.minusDays(BACKLOG_DAYS))
}
if (day.isAfter(today)) day = today
while (!day.isAfter(today)) {
val at = if (day == today) inputs.now else day.atTime(LocalTime.MAX)
val (verdict, next) = decideDay(day, at, inputs, state)
verdicts += DayVerdict(day, verdict)
if (verdict == StickVerdict.MISS) {
signal = next.lockedThrough?.takeIf { !it.isBefore(today) }
}
state = next
day = day.plusDays(1)
}
val settled = if (verdicts.last().verdict.final) today else today.minusDays(1)
return StickRun(verdicts, state, maxOf(settled, checked ?: settled), signal)
}
/** One day's verdict and the state after it; [now] is when it is judged. */
fun decideDay(
day: LocalDate,
now: LocalDateTime,
inputs: StickInputs,
state: StickState,
): Pair<StickVerdict, StickState> {
val alarm = inputs.alarm ?: return StickVerdict.NO_ALARM to state
if (!isStickDay(day)) return StickVerdict.NOT_STICK_DAY to state
if (inputs.isFree(day)) return StickVerdict.FREE_DAY to state
// A sick day stands the stick down like a free day: no miss, no
// streak change, no lockdown -- and nothing carried to tomorrow.
if (inputs.isSick(day)) return StickVerdict.SICK_DAY to state
// A dismissed or escaped stick day breaks the chain: the streak
// shown and synced drops to 0 (a lockdown already sent stays).
if (inputs.escapedOn(day)) return StickVerdict.ESCAPED to state.copy(streak = 0)
if (state.lastMiss == day) return StickVerdict.ALREADY_PENALISED to state
if (inputs.dismissedOn(day)) return StickVerdict.DISMISSED to state.copy(streak = 0)
val due = day.atTime(alarm).plusMinutes(Stakes.STICK_GRACE_MINUTES)
if (now.isBefore(due)) return StickVerdict.TOO_EARLY to state
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown)
}
/**
* The state a miss on [day] would produce. Also what the UI shows as
* "locked through" before the miss happens, so the screen and the
* enforcement can never disagree about the date. Never shortens a
* lockdown already in force: a chain restarting at 1 must not report
* an earlier end than the one focus-owner was already sent.
*/
fun afterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): StickState {
val streak = streakAfterMiss(day, state, standsDown)
val computed = lockedThrough(day, streak)
val locked = state.lockedThrough?.let { maxOf(it, computed) } ?: computed
return StickState(streak = streak, lockedThrough = locked, lastMiss = day)
}
/**
* Consecutive stick-day misses including one on [day]: the chain
* continues only when the previous stick day (free and sick days
* skipped, per [standsDown]) is exactly the last miss.
*/
fun streakAfterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): Int {
val previous = previousStickDay(day, standsDown)
return if (previous != null && previous == state.lastMiss) state.streak + 1 else 1
}
/** `day + min(streak, max - 1)`: 1 → the next day, 4+ → five calendar days. */
fun lockedThrough(day: LocalDate, streak: Int): LocalDate =
day.plusDays(minOf(streak, Stakes.STICK_LOCKDOWN_MAX_DAYS - 1).toLong())
/** The nearest earlier stick day that does not [standsDown], or null. */
fun previousStickDay(day: LocalDate, standsDown: (LocalDate) -> Boolean): LocalDate? {
var step = day.minusDays(1)
val floor = day.minusDays(LOOKBACK_DAYS)
while (step.isAfter(floor)) {
if (isStickDay(step) && !standsDown(step)) return step
step = step.minusDays(1)
}
return null
}
fun isStickDay(day: LocalDate): Boolean = day.dayOfWeek in WorkdayStick.STICK_DAYS
}
/** A day the stick skips entirely: free or sick. */
val StickInputs.standsDown: (LocalDate) -> Boolean
get() = { isFree(it) || isSick(it) }

View File

@ -0,0 +1,80 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.util.Log
import java.time.LocalDate
import java.time.LocalDateTime
/**
* Runs the stick: gathers [StickInputs] from the native stores, asks
* [StickCheck], and on a miss persists the new state, signals focus-owner and
* logs it. The only place those three are wired together.
*
* Three triggers share this one decision, so they can never disagree:
* `exact` (the [StickAlarm] at A + 15), `boot` (closes "phone off before the
* alarm") and `watchdog` (the daily net). Every run also catches up on the
* unchecked days before today ([StickCheck.run]), so a phone off for days
* is judged day by day when it comes back. Running twice is harmless --
* [StickVerdict.ALREADY_PENALISED] makes a second miss on one day a no-op,
* which matters because Android replays BOOT_COMPLETED to a force-stopped
* app on its next launch.
*/
object StickRunner {
private const val TAG = "WakeAlarmStick"
@Synchronized
fun run(context: Context, trigger: String): StickVerdict {
val before = StickStore.load(context)
val run = StickCheck.run(
StickInputs(
now = LocalDateTime.now(),
alarm = AlarmScheduler.storedAlarm(context),
dismissedOn = { RingWatch.dismissedOn(context, it) },
escapedOn = { StickStore.escapedOn(context, it) },
isFree = { FreeDays.isFree(context, it) },
isSick = { SickDays.isSick(context, it) },
state = before,
checkedThrough = StickStore.checkedThrough(context),
),
)
for ((day, verdict) in run.verdicts) {
Log.i(TAG, "check ($trigger) $day: ${verdict.wire}")
EventLog.append(
context,
"stick_check",
mapOf("trigger" to trigger, "verdict" to verdict.wire, "date" to day.toString()),
)
}
if (run.state != before) StickStore.save(context, run.state)
StickStore.setCheckedThrough(context, run.checkedThrough)
// A missed day whose lockdown already ended (caught up days later)
// still counts toward the streak, but nothing is sent for it.
run.signalUntil?.let { until ->
WorkdayStick.sendLockdown(context, until)
EventLog.append(
context,
"lockdown_sent",
mapOf("until" to until.toString(), "streak" to run.state.streak),
)
}
return run.verdicts.last().verdict
}
/**
* A dismissed stick day breaks the chain: the streak shown and synced
* drops to 0 at once. A lockdown already running is left alone, and a
* dismiss *after* today's miss changes nothing -- the miss stands.
*/
@Synchronized
fun onDismissed(context: Context) {
val today = LocalDate.now()
if (!StickCheck.isStickDay(today) || FreeDays.isFree(context, today) ||
SickDays.isSick(context, today)
) {
return
}
val state = StickStore.load(context)
if (state.lastMiss == today || state.streak == 0) return
StickStore.save(context, state.copy(streak = 0))
}
}

View File

@ -0,0 +1,36 @@
package com.kuhy.wake_alarm_sync
import java.time.LocalDateTime
import java.time.LocalTime
/**
* When [StickAlarm] fires, as pure functions of the clock, the alarm time
* and the check already armed -- no Context, so every case is checkable in
* isolation.
*/
object StickSchedule {
/** A few seconds past the boundary, so "passed by >= 15 min" is never a rounding call. */
private const val SLACK_SECONDS = 5L
/** The next (A + grace + slack) strictly after [now]. */
fun nextOccurrence(now: LocalDateTime, alarm: LocalTime): LocalDateTime {
val time = alarm.plusMinutes(Stakes.STICK_GRACE_MINUTES).plusSeconds(SLACK_SECONDS)
val candidate = now.toLocalDate().atTime(time)
return if (candidate.isAfter(now)) candidate else candidate.plusDays(1)
}
/**
* The instant to arm: the earlier of [next] and a still-future [pending].
*
* One PendingIntent holds one instant, so arming tomorrow's check would
* silently drop today's. Between A and A + 15 every re-arm passes the
* *next* alarm's time -- opening the app re-arms with tomorrow's policy,
* and "wake me earlier" sets an earlier one -- whose check is tomorrow.
* Keeping the pending instant is what stops "phone off, back on at A + 5,
* open the app" from cancelling today's check. A pending instant at or
* before [now] has fired (or was missed while off) and is dropped.
*/
fun choose(now: LocalDateTime, next: LocalDateTime, pending: LocalDateTime?): LocalDateTime =
if (pending != null && pending.isAfter(now) && pending.isBefore(next)) pending else next
}

View File

@ -0,0 +1,67 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import java.time.LocalDate
/**
* Persists the stick ([StickState]) and the day an escape was used.
*
* Every write is `commit()`, not `apply()`: these run inside broadcast
* receivers (the exact check, BOOT_COMPLETED) whose process may be gone a
* moment later, and a miss recorded only in memory would be penalised again
* by the next trigger. [updatedAt] stamps the last change so the synced
* `stick_state` field is re-pushed only when something actually moved.
*/
object StickStore {
private const val PREFS = "wake_alarm_stick"
private const val KEY_STREAK = "streak"
private const val KEY_LOCKED_THROUGH = "locked_through"
private const val KEY_LAST_MISS = "last_miss"
private const val KEY_ESCAPED_DATES = "escaped_dates"
private const val KEY_CHECKED_THROUGH = "checked_through"
private const val KEY_UPDATED_AT = "updated_at"
fun load(context: Context): StickState {
val prefs = prefs(context)
return StickState(
streak = prefs.getInt(KEY_STREAK, 0),
lockedThrough = parse(prefs.getString(KEY_LOCKED_THROUGH, null)),
lastMiss = parse(prefs.getString(KEY_LAST_MISS, null)),
)
}
fun save(context: Context, state: StickState) {
prefs(context).edit()
.putInt(KEY_STREAK, state.streak)
.putString(KEY_LOCKED_THROUGH, state.lockedThrough?.toString())
.putString(KEY_LAST_MISS, state.lastMiss?.toString())
.putString(KEY_UPDATED_AT, EventLog.nowIso())
.commit()
}
/** Records an escape for [day]: the streak and any lockdown are gone. */
fun markEscaped(context: Context, day: LocalDate) {
save(context, load(context).copy(streak = 0, lockedThrough = null))
DateHistory.add(prefs(context), KEY_ESCAPED_DATES, day)
}
fun escapedOn(context: Context, day: LocalDate): Boolean =
DateHistory.contains(prefs(context), KEY_ESCAPED_DATES, day)
/** The last day whose verdict was final; null before the first run. */
fun checkedThrough(context: Context): LocalDate? =
parse(prefs(context).getString(KEY_CHECKED_THROUGH, null))
fun setCheckedThrough(context: Context, day: LocalDate) {
prefs(context).edit().putString(KEY_CHECKED_THROUGH, day.toString()).commit()
}
/** ISO instant of the last change, or null before the first one. */
fun updatedAt(context: Context): String? = prefs(context).getString(KEY_UPDATED_AT, null)
private fun parse(iso: String?): LocalDate? =
iso?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}

View File

@ -0,0 +1,51 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.content.Intent
import android.util.Log
import java.time.DayOfWeek
import java.time.LocalDate
/**
* Signals `focus-owner` (`~/src/phone-focus-mode`): lock distracting apps
* through a date, or lift a lockdown now. Signalling only -- whether to lock
* is [StickCheck]'s decision, run by [StickRunner].
*
* Tue/Wed/Thu is the same set `wake_alarm._constants.STICK_DAYS` uses on the
* PC side for the debt-stacking half of this same stick: both go easy on
* exactly these three days otherwise, which is why skipping one used to cost
* nothing.
*/
object WorkdayStick {
/** Tuesday/Wednesday/Thursday; mirrored by `test_workday_mirrors.py`. */
val STICK_DAYS =
setOf(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY)
private const val ACTION_LOCKDOWN = "com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD"
private const val ACTION_LIFT = "com.kuhy.focus_owner.action.LIFT_LOCKDOWN"
private const val EXTRA_UNTIL = "until"
private const val PERMISSION_SIGNAL = "com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"
private const val FOCUS_OWNER_PACKAGE = "com.kuhy.focus_owner"
private const val TAG = "WakeAlarmWorkdayStick"
/** Locks down through [until], inclusive (`yyyy-MM-dd` on the wire). */
fun sendLockdown(context: Context, until: LocalDate) {
Log.i(TAG, "signalling focus-owner lockdown through $until")
context.sendBroadcast(
Intent(ACTION_LOCKDOWN)
.setPackage(FOCUS_OWNER_PACKAGE)
.putExtra(EXTRA_UNTIL, until.toString()),
PERMISSION_SIGNAL,
)
}
/** Clears any lockdown now (the escape hatch). */
fun sendLift(context: Context) {
Log.i(TAG, "signalling focus-owner lift")
context.sendBroadcast(
Intent(ACTION_LIFT).setPackage(FOCUS_OWNER_PACKAGE),
PERMISSION_SIGNAL,
)
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

View File

@ -0,0 +1,34 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.LocalDate
class DayCacheTest {
private val day = LocalDate.of(2026, 10, 20)
@Test
fun aCachedDateIsInTheSet() {
assertTrue(DayCache.contains(day) { setOf("2026-10-19", "2026-10-20") })
}
@Test
fun anotherDateIsNot() {
assertFalse(DayCache.contains(day) { setOf("2026-10-21") })
}
@Test
fun aMissingCacheMeansNotInTheSet() {
assertFalse(DayCache.contains(day) { null })
}
@Test
fun anUnreadableCacheFailsClosedAndReportsTheError() {
val seen = mutableListOf<RuntimeException>()
val boom = ClassCastException("not a string set")
assertFalse(DayCache.contains(day, onError = { seen += it }) { throw boom })
assertEquals(listOf<RuntimeException>(boom), seen)
}
}

View File

@ -0,0 +1,49 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.LocalDateTime
import java.time.LocalTime
class PoolSyncScheduleTest {
private val alarm = LocalTime.of(7, 30)
private fun at(day: Int, hour: Int, minute: Int = 0) =
LocalDateTime.of(2026, 10, day, hour, minute)
@Test
fun afternoonNextSlotIsTheEvening() {
assertEquals(at(16, 21), PoolSyncSchedule.next(at(16, 14), alarm))
}
@Test
fun afterTheEveningNextSlotIsHalfAnHourBeforeTomorrowsAlarm() {
assertEquals(at(17, 7), PoolSyncSchedule.next(at(16, 21, 0), alarm))
assertEquals(at(17, 7), PoolSyncSchedule.next(at(16, 23, 59), alarm))
}
@Test
fun earlyMorningNextSlotIsTodaysPreAlarm() {
assertEquals(at(17, 7), PoolSyncSchedule.next(at(17, 3), alarm))
}
@Test
fun theSlotThatJustFiredIsNeverReturned() {
assertEquals(at(17, 21), PoolSyncSchedule.next(at(17, 7), alarm))
}
@Test
fun withNoAlarmStoredOnlyTheEveningRuns() {
assertEquals(at(16, 21), PoolSyncSchedule.next(at(16, 3), null))
assertEquals(at(17, 21), PoolSyncSchedule.next(at(16, 22), null))
}
@Test
fun theLeadIsThirtyMinutes() {
assertEquals(30L, PoolSyncSchedule.LEAD_MINUTES)
assertEquals(
at(17, 7, 30).minusMinutes(30),
PoolSyncSchedule.next(at(16, 22), alarm),
)
}
}

View File

@ -0,0 +1,30 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class RingDecisionTest {
@Test
fun aNormalDayRings() {
assertNull(RingDecision.skip(isFree = false, isSick = false))
}
@Test
fun aSickDayIsSilentAndNamedSick() {
val skip = RingDecision.skip(isFree = false, isSick = true)
assertEquals(RingSkip.SICK_DAY, skip)
assertEquals("sick_day", skip?.wire)
assertEquals("sick day", skip?.label)
}
@Test
fun aFreeDayIsSilentAndNamedFree() {
assertEquals("free_day", RingDecision.skip(isFree = true, isSick = false)?.wire)
}
@Test
fun aDateInBothPoolsIsNamedFree() {
assertEquals(RingSkip.FREE_DAY, RingDecision.skip(isFree = true, isSick = true))
}
}

View File

@ -0,0 +1,24 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SessionWarnTest {
private val deadline = 1_000_000_000L
@Test
fun warnsThreeMinutesBeforeTheDeadline() {
assertEquals(deadline - 180_000L, SessionWarn.warnAt(deadline, deadline - 600_000L))
}
@Test
fun aWarnInstantAlreadyPastIsDropped() {
assertNull(SessionWarn.warnAt(deadline, deadline - 60_000L))
}
@Test
fun aDeadlineAlreadyPastIsDropped() {
assertNull(SessionWarn.warnAt(deadline, deadline + 1L))
}
}

View File

@ -0,0 +1,87 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
/** The stick on sick days: no miss, no streak change, no lockdown. */
class StickCheckSickTest {
// 2026-10-20 is a Tuesday; 21 Wed, 22 Thu, 27 the next Tuesday.
private val tue = LocalDate.of(2026, 10, 20)
private val wed = tue.plusDays(1)
private val thu = tue.plusDays(2)
private fun inputs(
now: LocalDateTime,
sick: Set<LocalDate> = emptySet(),
free: Set<LocalDate> = emptySet(),
state: StickState = StickState(),
checkedThrough: LocalDate? = null,
) = StickInputs(
now = now,
alarm = LocalTime.of(7, 30),
dismissedOn = { false },
escapedOn = { false },
isFree = { it in free },
isSick = { it in sick },
state = state,
checkedThrough = checkedThrough,
)
@Test
fun anUndismissedSickStickDayIsNotAMiss() {
val run = StickCheck.run(inputs(wed.atTime(9, 0), sick = setOf(wed)))
assertEquals(StickVerdict.SICK_DAY, run.verdicts.single().verdict)
assertEquals("sick_day", run.verdicts.single().verdict.wire)
assertEquals(StickState(), run.state)
assertNull(run.signalUntil)
}
@Test
fun theSameDayNotSickIsAMiss() {
val run = StickCheck.run(inputs(wed.atTime(9, 0)))
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
assertEquals(thu, run.signalUntil)
}
@Test
fun aSickDayKeepsAnExistingStreakAsItWas() {
val before = StickState(streak = 2, lockedThrough = wed, lastMiss = tue)
val run = StickCheck.run(inputs(wed.atTime(9, 0), sick = setOf(wed), state = before))
assertEquals(before, run.state)
}
@Test
fun aSickDayIsSkippedWhenTheStreakLooksBack() {
// Missed Tuesday, sick Wednesday: Thursday's miss continues the chain.
val before = StickState(streak = 1, lockedThrough = wed, lastMiss = tue)
val after = StickCheck.afterMiss(thu, before) { it == wed }
assertEquals(2, after.streak)
}
@Test
fun aCaughtUpSickDayIsJudgedSick() {
val run = StickCheck.run(
inputs(thu.atTime(6, 0), sick = setOf(wed), checkedThrough = tue),
)
assertEquals(
listOf(StickVerdict.SICK_DAY, StickVerdict.TOO_EARLY),
run.verdicts.map { it.verdict },
)
}
@Test
fun aFreeDayIsStillNamedFree() {
val run = StickCheck.run(inputs(wed.atTime(9, 0), free = setOf(wed)))
assertEquals(StickVerdict.FREE_DAY, run.verdicts.single().verdict)
}
@Test
fun standsDownCoversBothPools() {
val i = inputs(wed.atTime(9, 0), sick = setOf(wed), free = setOf(thu))
assertEquals(listOf(false, true, true), listOf(tue, wed, thu).map(i.standsDown))
}
}

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip

View File

@ -19,7 +19,7 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false
id("com.android.application") version "9.3.2" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<rect width="1024" height="1024" fill="#211D1B"/>
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,0)">
<g fill="none" stroke="#B8862E" stroke-width="57.8145" stroke-linecap="round" stroke-linejoin="round" transform="translate(-125.626,-125.626) scale(1.24536)">
<circle cx="512" cy="512" r="244"/>
<path d="M 512 512 L 512 350"/>
<path d="M 512 512 L 636 512"/>

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 34 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,0)">
<g fill="none" stroke="#B8862E" stroke-width="57.8145" stroke-linecap="round" stroke-linejoin="round" transform="translate(-125.626,-125.626) scale(1.24536)">
<circle cx="512" cy="512" r="244"/>
<path d="M 512 512 L 512 350"/>
<path d="M 512 512 L 636 512"/>

Before

Width:  |  Height:  |  Size: 345 B

After

Width:  |  Height:  |  Size: 379 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,0)">
<g fill="none" stroke="#FFFFFF" stroke-width="57.8145" stroke-linecap="round" stroke-linejoin="round" transform="translate(-125.626,-125.626) scale(1.24536)">
<circle cx="512" cy="512" r="244"/>
<path d="M 512 512 L 512 350"/>
<path d="M 512 512 L 636 512"/>

Before

Width:  |  Height:  |  Size: 345 B

After

Width:  |  Height:  |  Size: 379 B

View File

@ -1,22 +1,83 @@
import 'package:flutter/material.dart';
import 'package:wake_alarm_sync/screens/home_screen.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/day_pool_refresh.dart';
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
import 'package:wake_alarm_sync/ui/theme.dart';
/// Route the Kotlin `AlarmActivity` hands to the engine as its initial
/// route.
const String kRingRoute = '/ring';
/// Navigator key, so the platform side can drive navigation without a context.
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
/// Entry point.
void main() => runApp(const WakeAlarmSyncApp());
///
/// `ensureInitialized` is required before any MethodChannel call: the
/// startup re-arm below runs before the first frame.
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 (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());
}
/// Headless entry point: the daily alarm starts it natively
/// (`HeadlessRingStart.kt`) to publish `ring_started` with no screen.
///
/// Lives here because only the root library's entry points are reachable
/// by name from Kotlin; `vm:entry-point` keeps release tree-shaking off it.
@pragma('vm:entry-point')
Future<void> ringStartedMain() => runHeadlessRingStart();
/// Headless entry point: `PoolSyncReceiver.kt` starts it in the evening and
/// shortly before the alarm, so a free or sick day marked on the PC reaches
/// the native ring-path caches with the app closed.
@pragma('vm:entry-point')
Future<void> poolSyncMain() => runHeadlessPoolSync();
/// Root application widget.
class WakeAlarmSyncApp extends StatelessWidget {
/// Creates a [WakeAlarmSyncApp].
const WakeAlarmSyncApp({super.key});
/// Creates a [WakeAlarmSyncApp]; [newScheduler] is the probes' seam.
const WakeAlarmSyncApp({super.key, this.newScheduler});
/// Builds the platform bridge for the ring and session screens.
///
/// Null in production (each screen builds the real one). The emulator
/// harness supplies a file-driven bridge so a machine with no NFC and no
/// step sensor can still walk the whole morning. A factory rather than an
/// instance so each screen owns its own, as in production: the NFC
/// listener's ownership is per instance, and sharing one instance hid the
/// ring-dispose-wipes-session-listener bug the phone had just shown.
final AlarmScheduler Function()? newScheduler;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Wake Alarm Sync',
theme: buildAppTheme(),
home: const HomeScreen(),
navigatorKey: navigatorKey,
// AlarmActivity sets its initial route to kRingRoute, so the ring screen
// is what comes up over the lockscreen; the launcher still gets home.
routes: <String, WidgetBuilder>{
'/': (_) => const HomeScreen(),
kRingRoute: (_) => RingScreen(scheduler: newScheduler?.call()),
// Reached by pushReplacement from the ring screen, or as
// AlarmActivity's initial route when the launcher or the ongoing
// notification reopens a live session (SessionNotice.kt). Always
// inside AlarmActivity: NFC reader mode and the kept-on screen live
// there.
kSessionRoute: (_) => SessionScreen(scheduler: newScheduler?.call()),
},
);
}
}

View File

@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
import 'package:wake_alarm_sync/main.dart';
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
/// Debug entrypoint that arms a real alarm a minute out, then shows the app.
///
/// Exercises the true `AlarmManager.setAlarmClock` path — the receiver, the
/// foreground service and the full-screen intent all firing on their own —
/// rather than the `ringNow` shortcut, which skips the scheduler entirely.
/// The offset comes from `--dart-define=ARM_IN_MINUTES`.
///
/// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
const offset = int.fromEnvironment('ARM_IN_MINUTES', defaultValue: 1);
final scheduler = AlarmScheduler();
final at = DateTime.now().add(const Duration(minutes: offset));
final fsi = await scheduler.canUseFullScreenIntent();
// Printed so the harness can read the armed time out of logcat; this is a
// debug entrypoint, so stdout is the interface.
// ignore: avoid_print
print('ARM_PROBE armed=${at.hour}:${at.minute} fsi=$fsi');
await scheduler.schedule(at.hour, at.minute);
runApp(const WakeAlarmSyncApp());
}

Some files were not shown because too many files have changed in this diff Show More