mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-24 21:26:20 +01:00
Compare commits
7 Commits
f0de01f9aa
...
899a2c5581
| Author | SHA1 | Date | |
|---|---|---|---|
| 899a2c5581 | |||
| 224015cc2e | |||
| 5937e22131 | |||
| 59a853839c | |||
| 677a9f0f00 | |||
| 7a3b767075 | |||
| dec4ecc0cb |
132
AGENTS.md
132
AGENTS.md
@ -39,8 +39,8 @@ passing sent the user back to the start.
|
||||
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).
|
||||
shaken phone would count; on the normal path it only added two minutes of
|
||||
ringing (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
|
||||
@ -50,8 +50,7 @@ passing sent the user back to the start.
|
||||
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.
|
||||
deleted, not merely unrouted: the ring screen is reached by walking in.
|
||||
|
||||
**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
|
||||
@ -69,10 +68,10 @@ 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`**.
|
||||
does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
|
||||
mark/release/sync. Picker, cache, 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
|
||||
|
||||
@ -88,16 +87,17 @@ today's fire instant in **local** time, and fires iff `now` is in
|
||||
`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.
|
||||
relaunches it on top of the user. The latch replaced the alarm's own dismissal
|
||||
record when `_alarm.py` was deleted; deleting one without adding the other is
|
||||
a silent regression.
|
||||
|
||||
`Persistent=true` plus the 60-minute window is also what replaced the deleted
|
||||
`Persistent=true` plus the 60-minute window also 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.
|
||||
`_sync.py` is the only reader; `_sync_transport.py` fetches, `_sync_token.py`
|
||||
holds the GitHub-token lookup (stdlib-only).
|
||||
|
||||
- Source of truth: a `crdt_sync` log written by `phone_app/` under
|
||||
`wake-alarm-sync/devices-e2e/<device-id>/alarm.json`, at
|
||||
@ -111,50 +111,45 @@ systemd-sleep hook: a suspended or just-booted machine still fires.
|
||||
or wrong passphrase reads as "nothing published" (cache, then 08:00) —
|
||||
never plaintext. diet_guard reads the same prefix for weigh-ins.
|
||||
- **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".
|
||||
`devices/phone/`.** The phone's device id is migrating from the constant
|
||||
`phone` to a per-install uuid; a pinned reader would silently stop seeing
|
||||
the alarm and fall back to 08:00, 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** (`device_id` breaks exact ties). A payload
|
||||
that does not parse is skipped, never allowed to win. `SYNC_ALARM_PATH`
|
||||
stays as a last-resort read for a backend that lists nothing.
|
||||
- Payload parsing/ranking lives in `_alarm_payload.py` ("what did the phone
|
||||
say"); `_sync.py` owns fetching, caching and fallback.
|
||||
- **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.
|
||||
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config 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**.
|
||||
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker's is no
|
||||
longer read: Firebase-only since 2026-10-09). 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 cache
|
||||
rather than crash the per-minute trigger. Both backends need it now (the
|
||||
GitHub mirror is read through `GitHubSyncClient`, encrypted too). Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the
|
||||
dev venv.
|
||||
rather than crash the per-minute trigger. Both backends need it (the GitHub
|
||||
mirror is read through `GitHubSyncClient`, encrypted too). 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.
|
||||
cache → 08:00. The cache bounds remote reads to ~288/day.
|
||||
- **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` →
|
||||
stamped it*, never on when we fetched: the cache is rewritten from the same
|
||||
stale record every few minutes, so `fetched_at` is always fresh. 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.
|
||||
trusted: 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.
|
||||
a loud persistent condition is 1440 journal lines a day. `_trigger` emits the
|
||||
one 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.
|
||||
@ -167,11 +162,10 @@ 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.
|
||||
same commit.** A stale path caused a month-long silent production failure
|
||||
(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
|
||||
|
||||
@ -183,26 +177,26 @@ site-packages:
|
||||
/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`.
|
||||
**Run `install.sh` (or `pip install -e`) from a durable clone**
|
||||
(`~/src/wake-alarm`, mirroring `~/src/screen-locker`), not a scratch directory:
|
||||
it is editable, so a later `git pull` there 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
|
||||
service.
|
||||
|
||||
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>"`.
|
||||
A dependency installed only into a dev venv makes the service fail with
|
||||
`ModuleNotFoundError` on its next run (this 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.
|
||||
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls
|
||||
`uninstall.sh --retired-only` last, so **`uninstall.sh` is load-bearing for
|
||||
installing** — 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
|
||||
would abort an install that had already placed the package and 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`
|
||||
@ -213,11 +207,9 @@ and the root ring unit's `systemctl start|stop` lines live there.
|
||||
- **`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.
|
||||
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A
|
||||
per-file redirect gets forgotten when a new writer appears (`_trigger` was
|
||||
one), and the failure is silent: a green suite that stamped the live file.
|
||||
|
||||
## Commands
|
||||
|
||||
@ -229,12 +221,12 @@ and the root ring unit's `systemctl start|stop` lines live there.
|
||||
- coverage-gaps: `coverage-gaps coverage.xml`
|
||||
- deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`)
|
||||
|
||||
Other: full lint gate `pre-commit run --all-files`; watch live
|
||||
Other: full lint gate `pre-commit run --all-files`; live log
|
||||
`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**
|
||||
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`.
|
||||
|
||||
|
||||
@ -67,7 +67,13 @@ lives in CMOS, so it survives however the PC goes down.
|
||||
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.
|
||||
vmbox only, 2026-11-15 (`vm new --uefi`, OVMF): `rtcwake -m no -s 120`
|
||||
then `systemctl poweroff` left AIE and `RTC_EN` set in CMOS, and the
|
||||
guest cold-booted 12 s (guest clock) after the alarm (`result=woke`).
|
||||
QEMU has no S5 wake path, so `vm wake` emulates the firmware half: this
|
||||
proves the arming survives a poweroff, not that this board wakes from S5.
|
||||
Host S5 firmware check dropped by kuhy 2026-11-15 (needs a physical
|
||||
power-on).
|
||||
|
||||
### Phone stick (Tue/Wed/Thu, not free days)
|
||||
|
||||
@ -231,8 +237,15 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
||||
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).
|
||||
keep it busy. **Decided 2026-11-15:** on the *first* busy open (no retries)
|
||||
`ring_alsa.sh` rings through the user's PipeWire (`runuser`, then
|
||||
`python -m wake_alarm._ring_main`); only if that fails does it `fuser -k
|
||||
-TERM` the card's playback nodes once, retry ALSA once and exit non-zero.
|
||||
Fallback before kill, because the holder is PipeWire itself. The fallback's
|
||||
`ring_backend` event says `FAILED` (`started=false`) when PipeWire cannot
|
||||
play, and the unit's non-zero exit is the loud failure; the user-level
|
||||
fallback ring is the last line. Gate: vmbox `ring-alsa-busy-fallback`
|
||||
(10 repetitions) and `ring-alsa-busy-fails-loudly`.
|
||||
- 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.
|
||||
@ -243,8 +256,11 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
||||
|
||||
## 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.
|
||||
`python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]` and the 11:05 timer write
|
||||
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
|
||||
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
|
||||
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
|
||||
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.
|
||||
An existing report is never overwritten silently: exit 2 `refusing to overwrite <path>`
|
||||
unless `--force`; `--stdout` (alias `--dry-run`) prints and writes nothing, not even
|
||||
`audit_written`.
|
||||
|
||||
@ -75,12 +75,15 @@ cleanup() {
|
||||
trap cleanup EXIT
|
||||
|
||||
install_ring_audio() {
|
||||
# fuser (psmisc): the ring script's last resort frees a held card with it.
|
||||
command -v fuser >/dev/null 2>&1 || sudo pacman -S --needed --noconfirm psmisc
|
||||
# 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"
|
||||
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
||||
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||
sudo systemctl daemon-reload
|
||||
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
|
||||
}
|
||||
|
||||
@ -37,7 +37,10 @@ object HeadlessRingStart {
|
||||
|
||||
/** Starts the engine unless one is already running. Main thread only. */
|
||||
fun start(context: Context) {
|
||||
if (engine != null) return
|
||||
if (engine != null) {
|
||||
Log.w(TAG, "headless ring_started engine already running; start ignored")
|
||||
return
|
||||
}
|
||||
try {
|
||||
val app = context.applicationContext
|
||||
val created = FlutterEngine(app)
|
||||
|
||||
@ -1,3 +1,8 @@
|
||||
// Framework material, for its MaterialLocalizations delegate only: material_ui
|
||||
// ships its own MaterialLocalizations type, so crdt_sync_flutter's dialogs
|
||||
// (framework `showDialog`) found none and threw a null check.
|
||||
// ignore: deprecated_member_use, the only source of the framework delegate.
|
||||
import 'package:flutter/material.dart' as fw show DefaultMaterialLocalizations;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
import 'package:wake_alarm_sync/screens/home_screen.dart';
|
||||
@ -67,6 +72,10 @@ class WakeAlarmSyncApp extends StatelessWidget {
|
||||
title: kAppName,
|
||||
theme: buildAppTheme(),
|
||||
navigatorKey: navigatorKey,
|
||||
localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
|
||||
fw.DefaultMaterialLocalizations.delegate,
|
||||
DefaultWidgetsLocalizations.delegate,
|
||||
],
|
||||
// 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>{
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import 'dart:developer' as developer;
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrint;
|
||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||
import 'package:wake_alarm_sync/services/enforcement_bridge.dart';
|
||||
import 'package:wake_alarm_sync/services/enforcement_sync.dart';
|
||||
@ -60,7 +61,10 @@ class RingStartRecorder {
|
||||
if (await RingStartedStore.publishedOn(entry['date'])) return true;
|
||||
final settings = await SyncSettings.load();
|
||||
final hasFirebase = await loadAccount() != null;
|
||||
if (!settings.isConfigured && !hasFirebase) return false;
|
||||
if (!settings.isConfigured && !hasFirebase) {
|
||||
_log('ring_started not published: no sync backend');
|
||||
return false;
|
||||
}
|
||||
final service = await _open();
|
||||
// Only the enforcement fields: the ring is no time to restage tags
|
||||
// and history, and the push carries the whole log regardless.
|
||||
@ -79,5 +83,9 @@ class RingStartRecorder {
|
||||
}
|
||||
}
|
||||
|
||||
void _log(String message) => developer.log(message, name: 'WakeAlarmRing');
|
||||
// developer.log is invisible in a release build; logcat needs debugPrint.
|
||||
void _log(String message) {
|
||||
debugPrint('WakeAlarmRing: $message');
|
||||
developer.log(message, name: 'WakeAlarmRing');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import 'dart:developer' as developer;
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrint;
|
||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||
import 'package:wake_alarm_sync/services/settings_sync.dart';
|
||||
@ -32,6 +33,8 @@ class SessionPublisher {
|
||||
await applySyncedSettings(service);
|
||||
return 'Session synced to PC ✓';
|
||||
} on Exception catch (e, stack) {
|
||||
// developer.log is invisible in a release build; logcat needs print.
|
||||
debugPrint('WakeAlarmSession: session publish failed: $e');
|
||||
developer.log(
|
||||
'session publish failed: $e',
|
||||
name: 'WakeAlarmSession',
|
||||
|
||||
26
phone_app/test/e2e_dialog_localizations_test.dart
Normal file
26
phone_app/test/e2e_dialog_localizations_test.dart
Normal file
@ -0,0 +1,26 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:wake_alarm_sync/main.dart';
|
||||
import 'package:wake_alarm_sync/screens/settings_screen.dart';
|
||||
|
||||
/// crdt_sync_flutter's passphrase dialog (0.8.2 imports material_ui, so it is
|
||||
/// material_ui's `AlertDialog`) must open from the settings lock icon without
|
||||
/// a localization exception.
|
||||
void main() {
|
||||
testWidgets('the settings lock icon opens the passphrase dialog', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(const WakeAlarmSyncApp());
|
||||
navigatorKey.currentState!.push(
|
||||
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(const Key('settings-e2e')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
expect(find.byType(EditableText), findsOneWidget);
|
||||
});
|
||||
}
|
||||
28
phone_app/test/services/session_publisher_log_test.dart
Normal file
28
phone_app/test/services/session_publisher_log_test.dart
Normal file
@ -0,0 +1,28 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:wake_alarm_sync/services/session_publisher.dart';
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test('a failed publish reaches debugPrint, not only developer.log', () async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage(initial: {'github_token': 'tok'});
|
||||
final lines = <String>[];
|
||||
final saved = debugPrint;
|
||||
debugPrint = (message, {wrapWidth}) => lines.add('$message');
|
||||
addTearDown(() => debugPrint = saved);
|
||||
|
||||
final status = await SessionPublisher(
|
||||
open: () async => throw Exception('boom'),
|
||||
).publish();
|
||||
|
||||
expect(status, 'Session kept locally (sync failed)');
|
||||
expect(
|
||||
lines.join('\n'),
|
||||
contains('session publish failed: Exception: boom'),
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Fail if `textgate scan` reports any text item not covered by keep.md.
|
||||
# Fail if `textgate scan` reports any text item not covered by DOCS-textgate-keep.md.
|
||||
#
|
||||
# textgate has no path exclusion and its config is a gate control, so the
|
||||
# repo's deliberate exceptions live in keep.md instead. This script reads the
|
||||
# repo's deliberate exceptions live in DOCS-textgate-keep.md instead. This script reads the
|
||||
# "## Scan exceptions" table there (first cell: a backticked file, or a
|
||||
# directory ending in "/"; second cell: the backticked exact text, or * for
|
||||
# any text) and prints every scan hit no row covers.
|
||||
@ -20,7 +20,7 @@ set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
||||
readonly REPO_ROOT
|
||||
readonly KEEP_FILE="$REPO_ROOT/keep.md"
|
||||
readonly KEEP_FILE="$REPO_ROOT/DOCS-textgate-keep.md"
|
||||
readonly SECTION="## Scan exceptions"
|
||||
|
||||
die() {
|
||||
@ -28,7 +28,7 @@ die() {
|
||||
exit 2
|
||||
}
|
||||
|
||||
# Print the exception rows of keep.md as "path<TAB>text" (empty text = any).
|
||||
# Print the exception rows of DOCS-textgate-keep.md as "path<TAB>text" (empty text = any).
|
||||
keep_rows() {
|
||||
awk -v section="$SECTION" '/^## /{on = ($0 == section)} on && /^\| `/' "$KEEP_FILE" |
|
||||
sed -E 's/^\| `([^`]+)` \| (`([^`]*)`|\*) \|.*$/\1\t\3/'
|
||||
@ -56,10 +56,10 @@ main() {
|
||||
|
||||
if [[ -n "$unmatched" ]]; then
|
||||
echo "$unmatched"
|
||||
echo "textgate keep: $(wc -l <<<"$unmatched") hit(s) not in keep.md" >&2
|
||||
echo "textgate keep: $(wc -l <<<"$unmatched") hit(s) not in DOCS-textgate-keep.md" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "textgate keep: all $(jq length <<<"$scan") hit(s) covered by keep.md"
|
||||
echo "textgate keep: all $(jq length <<<"$scan") hit(s) covered by DOCS-textgate-keep.md"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
@ -9,6 +9,14 @@
|
||||
# speakers' card has, plays the rising WAV once, then loops the full-volume
|
||||
# one until systemd stops the unit (RuntimeMaxSec is the backstop).
|
||||
#
|
||||
# When the card is held (almost always the user's PipeWire), the FIRST busy
|
||||
# open -- no retries -- hands the ring to PipeWire as the user
|
||||
# (wake_alarm._ring_main, via runuser). Killing the holder first would kill
|
||||
# the PipeWire that fallback needs. Only if that fallback also fails: one
|
||||
# `fuser -k -TERM` on the card's playback nodes, one more ALSA try, then exit
|
||||
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
||||
# and psmisc's fuser.
|
||||
#
|
||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav>
|
||||
# ============================================================================
|
||||
|
||||
@ -21,6 +29,10 @@ readonly DEVICE="plughw:CARD=${CARD},DEV=0"
|
||||
# Playback controls that may gate the speakers; only those present are set.
|
||||
# Front is the rear line-out jack on this board.
|
||||
readonly CONTROLS=(Master PCM Speaker Headphone Front)
|
||||
# The user whose PipeWire owns the card, and the interpreter that has the
|
||||
# wake_alarm package (system python, same as the user timers).
|
||||
readonly RING_USER="${WAKE_ALARM_USER:-}"
|
||||
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
||||
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
||||
readonly RETRY_SECONDS=1
|
||||
|
||||
@ -41,8 +53,59 @@ unmute_all() {
|
||||
done
|
||||
}
|
||||
|
||||
# aplay's stderr says why it failed; only "busy" triggers the fallback.
|
||||
play() {
|
||||
aplay -q -D "$DEVICE" "$1" || sleep "$RETRY_SECONDS"
|
||||
local err
|
||||
err="$(mktemp)"
|
||||
if aplay -q -D "$DEVICE" "$1" 2>"$err"; then
|
||||
rm -f "$err"
|
||||
return 0
|
||||
fi
|
||||
if grep -qi 'busy' "$err"; then
|
||||
rm -f "$err"
|
||||
return 3
|
||||
fi
|
||||
cat "$err" >&2
|
||||
rm -f "$err"
|
||||
sleep "$RETRY_SECONDS"
|
||||
}
|
||||
|
||||
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
||||
# cannot play (the fallback itself reports ring_backend FAILED).
|
||||
user_fallback() {
|
||||
[[ -n "$RING_USER" ]] || return 1
|
||||
local uid home
|
||||
uid="$(id -u "$RING_USER")"
|
||||
home="$(getent passwd "$RING_USER" | cut -d: -f6)"
|
||||
echo "fallback-started: card busy, ringing through PipeWire as $RING_USER"
|
||||
runuser -u "$RING_USER" -- env HOME="$home" PATH="$PATH" \
|
||||
XDG_RUNTIME_DIR="/run/user/$uid" \
|
||||
"$PY" -m wake_alarm._ring_main "$1" "$2"
|
||||
}
|
||||
|
||||
# Last resort: free the card from whatever holds it, once.
|
||||
kill_holder() {
|
||||
local node
|
||||
node="$(readlink "/proc/asound/$CARD")" || return 0
|
||||
echo "kill-holder: fuser -k -TERM on ${node}"
|
||||
# shellcheck disable=SC2046 # one argument per playback node, by design
|
||||
fuser -k -TERM $(compgen -G "/dev/snd/pcmC${node#card}D*p") 2>&1 || true
|
||||
sleep "$RETRY_SECONDS"
|
||||
}
|
||||
|
||||
# The card was busy on its first open: PipeWire first, then kill, then fail.
|
||||
# Returns only when the holder was killed and ALSA works again.
|
||||
handle_busy() {
|
||||
local rise="$1" loop="$2"
|
||||
if user_fallback "$rise" "$loop"; then
|
||||
exit 0
|
||||
fi
|
||||
echo "fallback-failed: killing the holder, one more ALSA try" >&2
|
||||
kill_holder
|
||||
aplay -q -D "$DEVICE" "$rise" || {
|
||||
echo "Error: card $CARD still unusable" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
main() {
|
||||
@ -53,9 +116,11 @@ main() {
|
||||
exit 1
|
||||
}
|
||||
unmute_all
|
||||
play "$rise"
|
||||
local rc=0
|
||||
play "$rise" || rc=$?
|
||||
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
||||
while true; do
|
||||
play "$loop"
|
||||
play "$loop" || sleep "$RETRY_SECONDS"
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
@ -8,6 +8,9 @@ Documentation=https://github.com/kuhyx/wake-alarm
|
||||
# graphical session owns the sound: the night lockdown masks lightdm, and
|
||||
# the user is not in `audio`, so only root can reach the card.
|
||||
Type=simple
|
||||
# install.sh replaces @USER@: whose PipeWire the script falls back to when
|
||||
# the card is busy.
|
||||
Environment=WAKE_ALARM_USER=@USER@
|
||||
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh /usr/local/share/wake-alarm/ring.wav /usr/local/share/wake-alarm/ring_loop.wav
|
||||
# Backstop for a fallback tick that died without stopping this unit: never
|
||||
# ring longer than the 30-min cap plus a minute.
|
||||
|
||||
@ -14,6 +14,10 @@ readonly RING_WAV_DIR=/usr/local/share/wake-alarm
|
||||
readonly SUDOERS=/etc/sudoers.d/wake-alarm
|
||||
readonly POWERKEY_DROPIN=/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf
|
||||
readonly WAKEALARM=/sys/class/rtc/rtc0/wakealarm
|
||||
# The repo root in the guest: `vm repo` names it after the host basename
|
||||
# (~/wake-alarm, or ~/wt from a worktree), so derive it, never hard-code it.
|
||||
GUEST_REPO="$(readlink -f "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../..")"
|
||||
readonly GUEST_REPO
|
||||
|
||||
# A timer present but disabled fails silently every morning.
|
||||
case_v2_timers() {
|
||||
@ -57,6 +61,113 @@ case_ring_script_plays() {
|
||||
fi
|
||||
}
|
||||
|
||||
# --- card held busy (PipeWire holds it on the real PC) ----------------------
|
||||
readonly BUSY_REPS=10
|
||||
readonly BUSY_DIR=/tmp/ring-busy
|
||||
readonly EVENTS="$HOME/.local/state/wake_alarm/events.jsonl"
|
||||
|
||||
# Stub wpctl/pw-play: the guest has no user PipeWire. $1 = "ok" or "broken".
|
||||
busy_stubs() {
|
||||
mkdir -p "$BUSY_DIR/bin"
|
||||
printf '#!/bin/sh\nexit 0\n' >"$BUSY_DIR/bin/wpctl"
|
||||
if [[ "$1" == ok ]]; then
|
||||
printf '#!/bin/sh\nexec sleep 30\n' >"$BUSY_DIR/bin/pw-play"
|
||||
else
|
||||
printf '#!/bin/sh\nexit 1\n' >"$BUSY_DIR/bin/pw-play"
|
||||
fi
|
||||
chmod +x "$BUSY_DIR/bin/"*
|
||||
}
|
||||
|
||||
# Hold the Dummy card's only playback substream as root (the ssh user has no
|
||||
# ACL on a freshly loaded card), from a process that really ignores TERM:
|
||||
# aplay installs its own TERM handler, so `fuser -k -TERM` would free the
|
||||
# card. Returns non-zero when nothing holds it: a dead fixture must fail the
|
||||
# case as a fixture, never pass for a product result.
|
||||
busy_hold() {
|
||||
busy_release
|
||||
sudo modprobe -r snd-dummy >/dev/null 2>&1 || true
|
||||
sudo modprobe snd-dummy pcm_substreams=1
|
||||
sudo udevadm settle
|
||||
local node
|
||||
node="$(busy_node)" || return 1
|
||||
sudo setsid bash -c "trap '' TERM; exec 3>$node; exec sleep 600" \
|
||||
>/dev/null 2>&1 &
|
||||
sleep 1
|
||||
# Captured, not piped: under pipefail aplay's own exit 1 fails the pipe.
|
||||
local probe
|
||||
probe="$(sudo aplay -q -D plughw:CARD=Dummy,DEV=0 "$RING_WAV_DIR/ring.wav" 2>&1)" || true
|
||||
grep -qi busy <<<"$probe"
|
||||
}
|
||||
|
||||
# The Dummy card's playback node, e.g. /dev/snd/pcmC0D0p.
|
||||
busy_node() {
|
||||
local card
|
||||
card="$(readlink /proc/asound/Dummy)" || return 1
|
||||
echo "/dev/snd/pcmC${card#card}D0p"
|
||||
}
|
||||
|
||||
busy_release() {
|
||||
local node
|
||||
node="$(busy_node)" || return 0
|
||||
sudo fuser -s -k -KILL "$node" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
# A ring_backend event in the user's log carrying $1 (started true/false).
|
||||
busy_event() {
|
||||
grep '"event": "ring_backend"' "$EVENTS" 2>/dev/null | grep -q "$1"
|
||||
}
|
||||
|
||||
# Run the ring script against the held card; $1 = seconds to let it run.
|
||||
busy_run() {
|
||||
sudo WAKE_ALARM_CARD=Dummy WAKE_ALARM_USER="$USER" PATH="$BUSY_DIR/bin:$PATH" \
|
||||
timeout "$1" "$RING_SCRIPT" "$RING_WAV_DIR/ring.wav" "$RING_WAV_DIR/ring_loop.wav" 2>&1
|
||||
}
|
||||
|
||||
# The first busy open hands the ring to PipeWire, N times over, with the
|
||||
# holder alive and ignoring TERM (so a kill-first design would fail here).
|
||||
case_ring_busy_fallback() {
|
||||
local name="ring-alsa-busy-fallback" i ok=0 out
|
||||
busy_stubs ok
|
||||
if ! busy_hold; then
|
||||
fail "$name" "fixture: nothing holds the Dummy card"
|
||||
return
|
||||
fi
|
||||
for ((i = 1; i <= BUSY_REPS; i++)); do
|
||||
: >"$EVENTS" 2>/dev/null || true
|
||||
out="$(busy_run 4)" || true
|
||||
if grep -q '^fallback-started' <<<"$out" &&
|
||||
! grep -q 'kill-holder' <<<"$out" &&
|
||||
busy_event '"started": true'; then
|
||||
ok=$((ok + 1))
|
||||
fi
|
||||
done
|
||||
busy_release
|
||||
if [[ $ok -eq $BUSY_REPS ]]; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "$ok of $BUSY_REPS repetitions fell back on the first busy open"
|
||||
fi
|
||||
}
|
||||
|
||||
# Holder present AND fallback broken: never a silent success.
|
||||
case_ring_busy_fails_loudly() {
|
||||
local name="ring-alsa-busy-fails-loudly" out rc=0
|
||||
busy_stubs broken
|
||||
if ! busy_hold; then
|
||||
fail "$name" "fixture: nothing holds the Dummy card"
|
||||
return
|
||||
fi
|
||||
: >"$EVENTS" 2>/dev/null || true
|
||||
out="$(busy_run 15)" || rc=$?
|
||||
busy_release
|
||||
if [[ $rc -ne 0 && $rc -ne 124 ]] && grep -q 'kill-holder' <<<"$out" &&
|
||||
busy_event '"started": false'; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "rc=$rc, expected non-zero exit, kill-holder and a FAILED event"
|
||||
fi
|
||||
}
|
||||
|
||||
case_sudoers() {
|
||||
local name="sudoers-merged"
|
||||
if ! sudo visudo -cf "$SUDOERS" >/dev/null 2>&1; then
|
||||
@ -103,7 +214,7 @@ case_rtc_arm() {
|
||||
# Last: uninstall must remove everything except the sudoers file.
|
||||
case_uninstall() {
|
||||
local name="uninstall-cleans" leftovers=()
|
||||
(cd ~/wake-alarm && bash uninstall.sh >/dev/null 2>&1) || true
|
||||
(cd "$GUEST_REPO" && bash uninstall.sh >/dev/null 2>&1) || true
|
||||
[[ -e "$RING_UNIT" ]] && leftovers+=("$RING_UNIT")
|
||||
[[ -e "$RING_SCRIPT" ]] && leftovers+=("$RING_SCRIPT")
|
||||
[[ -e "$POWERKEY_DROPIN" ]] && leftovers+=("$POWERKEY_DROPIN")
|
||||
@ -123,6 +234,8 @@ run_v2_cases() {
|
||||
case_v2_timers
|
||||
case_ring_unit_installed
|
||||
case_ring_script_plays
|
||||
case_ring_busy_fallback
|
||||
case_ring_busy_fails_loudly
|
||||
case_sudoers
|
||||
case_powerkey_dropin
|
||||
case_rtc_arm
|
||||
|
||||
@ -25,6 +25,11 @@ readonly SCRIPT_DIR
|
||||
# directory in the guest and rsync writes into /home instead of the repo.
|
||||
REPO_DIR="$(readlink -f "${SCRIPT_DIR}/../..")"
|
||||
readonly REPO_DIR
|
||||
# Where `vm repo` lands the tree: ~/<basename>, so a worktree named "wt" is
|
||||
# ~/wt, not ~/wake-alarm. Hard-coding the name broke every worktree run.
|
||||
# shellcheck disable=SC2088 # the guest shell expands ~, not this one
|
||||
GUEST_REPO="~/$(basename "$REPO_DIR")"
|
||||
readonly GUEST_REPO
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
readonly SCRIPT_NAME
|
||||
|
||||
@ -34,7 +39,7 @@ readonly SCRIPT_NAME
|
||||
# dies with "libtk8.6.so: cannot open shared object file" without it. Measured
|
||||
# in the guest, not guessed -- dropping this package is what broke the harness
|
||||
# when the alarm window was deleted.
|
||||
readonly GUEST_PACKAGES="tk alsa-utils"
|
||||
readonly GUEST_PACKAGES="tk alsa-utils psmisc"
|
||||
|
||||
# Printed by guest_cases.sh only when every case passed. See run_cases().
|
||||
readonly GUEST_OK_SENTINEL="ALL-CASES-PASSED"
|
||||
@ -119,7 +124,7 @@ run_install() {
|
||||
# sentinel grep below matched vm's echo of the command line itself.
|
||||
# Hence -x: only a line that IS the sentinel counts.
|
||||
vm run "$VM_NAME" \
|
||||
'cd ~/wake-alarm && bash install.sh && echo INSTALL-OK' \
|
||||
"cd $GUEST_REPO && bash install.sh && echo INSTALL-OK" \
|
||||
>/tmp/wa-install.log 2>&1 || true
|
||||
if ! grep -qx 'INSTALL-OK' /tmp/wa-install.log; then
|
||||
tail -20 /tmp/wa-install.log >&2
|
||||
@ -135,7 +140,7 @@ run_cases() {
|
||||
step "Running the guest cases"
|
||||
local output
|
||||
output="$(vm run "$VM_NAME" \
|
||||
'bash ~/wake-alarm/scripts/vmbox/guest_cases.sh all' 2>&1)"
|
||||
"bash $GUEST_REPO/scripts/vmbox/guest_cases.sh all" 2>&1)"
|
||||
echo "$output"
|
||||
grep -q "$GUEST_OK_SENTINEL" <<<"$output"
|
||||
}
|
||||
|
||||
@ -2,20 +2,22 @@
|
||||
|
||||
``wake-alarm-audit.timer`` runs it at 11:05; by hand::
|
||||
|
||||
python -m wake_alarm._audit [YYYY-MM-DD] [--dry-run]
|
||||
python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]
|
||||
|
||||
It merges the phone's ``phone_events`` with the PC's named ``events.jsonl``
|
||||
lines, boots and resumes into one timeline, runs the expected-vs-observed
|
||||
checks (``_audit_checks``) and writes ``INCIDENTS_DIR/<date>.md`` with every
|
||||
escape and mismatch first, under ``## Flags``. Read-only everywhere except
|
||||
that one file (and ``audit_written``); ``--dry-run`` prints without writing.
|
||||
that one file (and ``audit_written``). An existing report is never
|
||||
overwritten silently: exit 2 unless ``--force``; ``--stdout`` (alias
|
||||
``--dry-run``) prints and writes nothing.
|
||||
Outside the repo on purpose: the report holds personal data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import date, datetime
|
||||
from datetime import UTC, date, datetime
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@ -79,6 +81,11 @@ def gather(day: date) -> tuple[Evidence, bool]:
|
||||
escapes=[e for e in view.escapes if e.date == day.isoformat()],
|
||||
ring_started=view.ring_started_on(day.isoformat()),
|
||||
stick_state=view.stick_state,
|
||||
last_push=(
|
||||
None
|
||||
if view.last_push is None
|
||||
else datetime.fromtimestamp(view.last_push, tz=UTC).astimezone()
|
||||
),
|
||||
),
|
||||
)
|
||||
return evidence, published is not None
|
||||
@ -161,17 +168,30 @@ def write_report(day: date, text: str) -> str:
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Entry point; exit 1 when the report could not be written."""
|
||||
"""Entry point; exit 1 if unwritable, 2 if a report exists and no flag."""
|
||||
parser = argparse.ArgumentParser(description="Audit one wake-up")
|
||||
parser.add_argument("day", nargs="?", type=date.fromisoformat, default=None)
|
||||
parser.add_argument("--dry-run", action="store_true", help="print, write nothing")
|
||||
parser.add_argument(
|
||||
"--stdout",
|
||||
"--dry-run",
|
||||
dest="stdout",
|
||||
action="store_true",
|
||||
help="print, write nothing",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", action="store_true", help="overwrite an existing report"
|
||||
)
|
||||
args = parser.parse_args(sys.argv[1:] if argv is None else argv)
|
||||
day = args.day or datetime.now().astimezone().date()
|
||||
existing = INCIDENTS_DIR / f"{day.isoformat()}.md"
|
||||
if existing.exists() and not (args.stdout or args.force):
|
||||
sys.stderr.write(f"refusing to overwrite {existing}; use --stdout or --force\n")
|
||||
return 2
|
||||
evidence, reachable = gather(day)
|
||||
checks = run_checks(evidence)
|
||||
text = render(evidence, checks, reachable=reachable)
|
||||
sys.stdout.write(text)
|
||||
if args.dry_run:
|
||||
if args.stdout:
|
||||
return 0
|
||||
configure_logging(component="audit")
|
||||
try:
|
||||
|
||||
@ -20,7 +20,7 @@ from wake_alarm._audit_evidence import (
|
||||
phone_on_day,
|
||||
)
|
||||
from wake_alarm._audit_stick import check_lockdown, check_penalty
|
||||
from wake_alarm._constants import RTC_WAKE_LEAD
|
||||
from wake_alarm._constants import PHONE_PUSH_STALE_SECONDS, RTC_WAKE_LEAD
|
||||
from wake_alarm._enforcement_payload import is_honoured
|
||||
from wake_alarm._enforcement_records import parse_instant
|
||||
|
||||
@ -127,8 +127,26 @@ def check_fallback_stop(ev: Evidence) -> Check:
|
||||
return ok("fallback stopped correctly", ", ".join(reasons))
|
||||
|
||||
|
||||
def check_phone_push(ev: Evidence) -> Check:
|
||||
"""The phone wrote to Firebase within the last day.
|
||||
|
||||
Not applicable (could not check) when no dated record is readable --
|
||||
Firebase unreachable, locked, or nothing stamped -- which is not the
|
||||
phone's silence.
|
||||
"""
|
||||
name = "phone pushed to Firebase"
|
||||
if ev.last_push is None:
|
||||
return na(name, "could not check: no dated phone write readable")
|
||||
age = (ev.now - ev.last_push).total_seconds()
|
||||
detail = f"last write {ev.last_push:%Y-%m-%d %H:%M}, {age / 3600:.0f} h ago"
|
||||
if age > PHONE_PUSH_STALE_SECONDS:
|
||||
return bad(name, detail)
|
||||
return ok(name, detail)
|
||||
|
||||
|
||||
CHECKS = (
|
||||
check_alarm,
|
||||
check_phone_push,
|
||||
check_rtc,
|
||||
check_up_by_alarm,
|
||||
check_ring,
|
||||
|
||||
@ -9,12 +9,13 @@ ring screen and the stick streak), plus the day and its alarm.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from wake_alarm._enforcement_records import parse_instant
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
|
||||
from wake_alarm._audit_sources import PcEvent, Up
|
||||
from wake_alarm._enforcement_records import Escape, PhoneEvent, StickState
|
||||
@ -38,6 +39,13 @@ class PhoneSide:
|
||||
escapes: list[Escape] = field(default_factory=list)
|
||||
ring_started: bool = False
|
||||
stick_state: StickState | None = None
|
||||
# Newest dated write to Firebase by any phone; None = unreadable/undated.
|
||||
last_push: datetime | None = None
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
"""The audit's clock: an aware local instant."""
|
||||
return datetime.now().astimezone()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@ -52,6 +60,7 @@ class Evidence:
|
||||
pc_side: PcSide = field(default_factory=PcSide)
|
||||
phone_side: PhoneSide = field(default_factory=PhoneSide)
|
||||
sick_day: bool = False
|
||||
now: datetime = field(default_factory=_now)
|
||||
|
||||
@property
|
||||
def pc(self) -> list[PcEvent]:
|
||||
@ -93,6 +102,11 @@ class Evidence:
|
||||
"""The phone's streak, as published now."""
|
||||
return self.phone_side.stick_state
|
||||
|
||||
@property
|
||||
def last_push(self) -> datetime | None:
|
||||
"""When the phone last wrote anything to Firebase, if readable."""
|
||||
return self.phone_side.last_push
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Check:
|
||||
|
||||
@ -119,6 +119,12 @@ PUBLISHED_ALARM_MAX_AGE_SECONDS: float = 14 * 24 * 60 * 60
|
||||
|
||||
ALARM_CACHE_MAX_AGE_SECONDS: float = 300.0
|
||||
|
||||
# The daily audit flags a phone whose newest Firebase write is older than
|
||||
# this. A phone that stopped uploading (2026-11-13) was only noticed when the
|
||||
# PC fallback rang three days later; a day of silence is the evening-before
|
||||
# catch for a morning that would otherwise ring as ``phone_silent``.
|
||||
PHONE_PUSH_STALE_SECONDS: float = 24 * 60 * 60
|
||||
|
||||
# How long after the alarm instant the trigger will still fire. Covers a
|
||||
# suspended PC, a missed timer tick, and a machine booted mid-window. Also the
|
||||
# reason a phone alarm moved *earlier* mid-window still fires promptly.
|
||||
|
||||
@ -20,7 +20,7 @@ import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from wake_alarm._alarm_payload import extract_hlc
|
||||
from wake_alarm._alarm_payload import extract_hlc, hlc_instant
|
||||
from wake_alarm._constants import (
|
||||
ESCAPE_HATCH_LAST_DAY,
|
||||
ESCAPE_REASON_MIN_CHARS,
|
||||
@ -54,6 +54,8 @@ class EnforcementView:
|
||||
escapes: tuple[Escape, ...] = ()
|
||||
stick_state: StickState | None = None
|
||||
phone_events: tuple[PhoneEvent, ...] = ()
|
||||
# Epoch seconds of the newest dated write on any device; None = undatable.
|
||||
last_push: float | None = None
|
||||
|
||||
def ring_started_on(self, day: str) -> bool:
|
||||
"""Whether the phone's ring screen opened on ``day``."""
|
||||
@ -152,10 +154,29 @@ def parse_logs(published: list[tuple[str, str]]) -> list[tuple[str, dict[str, An
|
||||
return logs
|
||||
|
||||
|
||||
def newest_push(logs: list[tuple[str, dict[str, Any]]]) -> float | None:
|
||||
"""Epoch seconds of the newest dated HLC of any field on any device.
|
||||
|
||||
Every phone write stamps the field it changed, so the largest instant is
|
||||
when the phone last uploaded anything. A stamp that cannot be dated is
|
||||
skipped: None means "cannot tell", never "old".
|
||||
"""
|
||||
stamps: list[float] = []
|
||||
for _, log in logs:
|
||||
record = log.get("alarm")
|
||||
fields = record.get("fields") if isinstance(record, dict) else None
|
||||
for name in fields if isinstance(fields, dict) else ():
|
||||
at = hlc_instant(extract_hlc(log, name))
|
||||
if at is not None:
|
||||
stamps.append(at)
|
||||
return max(stamps, default=None)
|
||||
|
||||
|
||||
def enforcement_view(published: list[tuple[str, str]]) -> EnforcementView:
|
||||
"""Merge every device's v2 fields into one view."""
|
||||
logs = parse_logs(published)
|
||||
return EnforcementView(
|
||||
last_push=newest_push(logs),
|
||||
ring_started=_newest(logs, RING_STARTED_FIELD, ring_started_from),
|
||||
escapes=_union(logs, ESCAPES_FIELD, escape_from, lambda e: e.id),
|
||||
stick_state=_newest(logs, STICK_STATE_FIELD, stick_state_from),
|
||||
|
||||
66
wake_alarm/_ring_main.py
Normal file
66
wake_alarm/_ring_main.py
Normal file
@ -0,0 +1,66 @@
|
||||
"""The user-side ring the root ALSA script falls back to.
|
||||
|
||||
``scripts/pc/ring_alsa.sh`` runs ``python -m wake_alarm._ring_main <rise>
|
||||
<loop>`` as the user (``runuser``) the first time the speakers' card is busy:
|
||||
PipeWire holds it, so the ring goes *through* PipeWire instead of fighting
|
||||
it. Plays until SIGTERM (exit 0); exits 1 with ``ring_backend ... FAILED``
|
||||
when PipeWire cannot play, which tells the script to try killing the holder.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
from wake_alarm._events import emit
|
||||
from wake_alarm._logging_setup import configure_logging
|
||||
from wake_alarm._ring_player import PipeWireBackend
|
||||
|
||||
_PUMP_SECONDS = 1.0
|
||||
_ARGS = 2 # rise.wav, loop.wav
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Ring through PipeWire until SIGTERM; 1 when it cannot, 2 on bad usage."""
|
||||
args = sys.argv[1:] if argv is None else argv
|
||||
if len(args) != _ARGS:
|
||||
sys.stderr.write("Usage: _ring_main <rise.wav> <loop.wav>\n")
|
||||
return 2
|
||||
configure_logging(component="ring")
|
||||
backend = PipeWireBackend(Path(args[0]), Path(args[1]))
|
||||
started, detail = backend.start()
|
||||
emit(
|
||||
"ring_backend",
|
||||
f"pipewire for root unit ({'started' if started else 'FAILED'})",
|
||||
backend=backend.name,
|
||||
why="root unit found the card busy",
|
||||
started=started,
|
||||
detail=detail,
|
||||
)
|
||||
if not started:
|
||||
return 1
|
||||
stopping: list[bool] = []
|
||||
signal.signal(signal.SIGTERM, lambda *_: stopping.append(True))
|
||||
try:
|
||||
while not stopping:
|
||||
if not backend.pump():
|
||||
# Dying mid-ring must reach the log as loudly as never starting.
|
||||
emit(
|
||||
"ring_backend",
|
||||
"pipewire for root unit (FAILED)",
|
||||
backend=backend.name,
|
||||
why="pw-play stopped mid-ring",
|
||||
started=False,
|
||||
detail="pump failed",
|
||||
)
|
||||
return 1
|
||||
time.sleep(_PUMP_SECONDS)
|
||||
finally:
|
||||
backend.stop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -46,7 +46,7 @@ from wake_alarm._events import emit, emit_on_change
|
||||
from wake_alarm._fallback_policy import alarm_instant
|
||||
from wake_alarm._logging_setup import configure_logging
|
||||
from wake_alarm._pc_wake_mode import read_mode
|
||||
from wake_alarm._rtc_hw import arm, current_alarm, disarm_ours, read_record
|
||||
from wake_alarm._rtc_hw import arm, current_alarm, disarm_ours, matches, read_record
|
||||
from wake_alarm._sick import alarm_stands_down, alarm_stands_down_synced
|
||||
from wake_alarm._sync import Alarm, get_alarm
|
||||
from wake_alarm._workday_penalty import cancel_for_sick_day
|
||||
@ -169,7 +169,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
chosen = plan(now, get_alarm())
|
||||
sys.stdout.write(describe(chosen))
|
||||
record = read_record()
|
||||
if not chosen.arm and record is not None and current_alarm() == record.epoch:
|
||||
if not chosen.arm and record is not None and matches(current_alarm(), record.epoch):
|
||||
sys.stdout.write(
|
||||
f"would disarm ours: {record.epoch} for {record.target_date}\n"
|
||||
)
|
||||
|
||||
@ -8,7 +8,10 @@ setting and clearing go through the NOPASSWD ``sudo -n /usr/sbin/rtcwake``.
|
||||
armed, so :func:`disarm_ours` only ever clears that one: an alarm someone
|
||||
else set (a manual ``rtcwake``) is not ours to remove. The comparison is on
|
||||
the sysfs value, which is epoch seconds when the RTC keeps UTC (this host:
|
||||
no ``/etc/adjtime``). An RTC on local time would never match, which fails
|
||||
no ``/etc/adjtime``). ``rtcwake -t`` shifts the alarm by the RTC/system clock
|
||||
offset (vmbox: +1 s), so "ours" means within ``_MATCH_SLACK_SECONDS``, never
|
||||
exact equality: an exact compare forgot the record and left the alarm armed.
|
||||
An RTC on local time is off by whole hours and never matches, which fails
|
||||
safe -- the alarm is left in place, never cleared by mistake.
|
||||
|
||||
Every process goes through ``_run``, the seam the suite replaces.
|
||||
@ -28,6 +31,8 @@ _logger = logging.getLogger(__name__)
|
||||
|
||||
RTCWAKE = "/usr/sbin/rtcwake"
|
||||
WAKEALARM_FILE = Path("/sys/class/rtc/rtc0/wakealarm")
|
||||
# Clock offset rtcwake may add; far below the 1 h of a local-time RTC.
|
||||
_MATCH_SLACK_SECONDS = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@ -62,6 +67,11 @@ def current_alarm() -> int | None:
|
||||
return int(text) if text.isdigit() else None
|
||||
|
||||
|
||||
def matches(pending: int | None, epoch: int) -> bool:
|
||||
"""Whether the pending sysfs alarm is the one armed for ``epoch``."""
|
||||
return pending is not None and abs(pending - epoch) <= _MATCH_SLACK_SECONDS
|
||||
|
||||
|
||||
def read_record() -> ArmedRecord | None:
|
||||
"""What we last armed, or None."""
|
||||
try:
|
||||
@ -91,7 +101,7 @@ def _write_record(record: ArmedRecord | None) -> None:
|
||||
|
||||
def arm(epoch: int, target_date: str) -> tuple[bool, str]:
|
||||
"""Set the RTC alarm (unless it already is exactly this) and record it."""
|
||||
if current_alarm() == epoch:
|
||||
if matches(current_alarm(), epoch):
|
||||
ok, detail = True, "already set"
|
||||
else:
|
||||
ok, detail = _rtcwake("-m", "no", "-t", str(epoch))
|
||||
@ -113,7 +123,7 @@ def disarm_ours() -> tuple[ArmedRecord | None, bool, str]:
|
||||
record = read_record()
|
||||
if record is None:
|
||||
return None, False, "nothing of ours armed"
|
||||
if current_alarm() != record.epoch:
|
||||
if not matches(current_alarm(), record.epoch):
|
||||
_write_record(None)
|
||||
return record, False, "no longer pending"
|
||||
ok, detail = _rtcwake("-m", "disable")
|
||||
|
||||
@ -41,8 +41,6 @@ from wake_alarm._sync_transport import (
|
||||
_FIREBASE_AVAILABLE,
|
||||
_fetch_firebase_alarm,
|
||||
_fetch_github_alarm,
|
||||
_read_token,
|
||||
_read_token_fallback,
|
||||
fetch_remote_alarm,
|
||||
)
|
||||
|
||||
@ -55,8 +53,6 @@ __all__ = [
|
||||
"Alarm",
|
||||
"_fetch_firebase_alarm",
|
||||
"_fetch_github_alarm",
|
||||
"_read_token",
|
||||
"_read_token_fallback",
|
||||
"fetch_remote_alarm",
|
||||
"get_alarm",
|
||||
]
|
||||
@ -201,7 +197,7 @@ def get_alarm(*, max_cache_age_seconds: float = ALARM_CACHE_MAX_AGE_SECONDS) ->
|
||||
return Alarm(remote[0], remote[1], "remote")
|
||||
|
||||
# Both degraded paths log at INFO for the same per-minute-tick reason as
|
||||
# _read_token above; _trigger warns when it fires on a degraded source.
|
||||
# the transport; _trigger warns when it fires on a degraded source.
|
||||
if cached is not None:
|
||||
_logger.info("Using stale cached alarm — sync read failed")
|
||||
return Alarm(cached[0], cached[1], "stale-cache")
|
||||
|
||||
69
wake_alarm/_sync_token.py
Normal file
69
wake_alarm/_sync_token.py
Normal file
@ -0,0 +1,69 @@
|
||||
"""The GitHub-mirror token: this package's own config, then a sibling app's.
|
||||
|
||||
Split out of ``_sync_transport.py`` for the 250-line cap. Only the GitHub
|
||||
fallback needs a token; Firebase authenticates through ``crdt_sync``'s own
|
||||
cached refresh token. Stdlib-only on purpose: the per-minute trigger runs
|
||||
``/usr/bin/python`` and must import this even when ``crdt_sync`` failed to
|
||||
install.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from wake_alarm._constants import SYNC_CONFIG_FILE, SYNC_TOKEN_FALLBACK_FILES
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _read_token_config() -> str | None:
|
||||
"""Read the token from this package's own JSON config.
|
||||
|
||||
Returns:
|
||||
The token, or None if the file is missing, unreadable, malformed, or
|
||||
holds no usable token.
|
||||
"""
|
||||
try:
|
||||
with SYNC_CONFIG_FILE.open() as handle:
|
||||
config = json.load(handle)
|
||||
except OSError, json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(config, dict):
|
||||
return None
|
||||
token = config.get("token")
|
||||
if not isinstance(token, str) or not token:
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
def _read_token_fallback() -> str | None:
|
||||
"""Read the token from a sibling app's raw single-line token file.
|
||||
|
||||
Returns:
|
||||
The first usable token found, or None if none of the fallback files
|
||||
exists or holds one.
|
||||
"""
|
||||
for path in SYNC_TOKEN_FALLBACK_FILES:
|
||||
try:
|
||||
token = path.read_text().strip()
|
||||
except OSError:
|
||||
continue
|
||||
if token:
|
||||
_logger.debug("Using sync token from %s", path)
|
||||
return token
|
||||
return None
|
||||
|
||||
|
||||
def read_token() -> str | None:
|
||||
"""Read the GitHub token, preferring this package's own config.
|
||||
|
||||
Falls back to diet_guard's token file so one repo-scoped PAT covers
|
||||
every app syncing through ``kuhyx/syncs``.
|
||||
|
||||
Returns:
|
||||
The token, or None if no configured source holds one.
|
||||
"""
|
||||
# No warning on a miss here: the caller reports "no token" once. Logging
|
||||
# twice for one unconfigured file makes every tick noisy in the journal.
|
||||
return _read_token_config() or _read_token_fallback()
|
||||
@ -1,8 +1,9 @@
|
||||
"""Fetching the alarm the phone pushed — Firebase first, GitHub as mirror.
|
||||
|
||||
Split out of ``_sync.py`` for the 250-line cap, along the seam item 8 needs:
|
||||
this module is the **transport** (token discovery and the two backends), while
|
||||
``_sync.py`` keeps **resolution** (cache, staleness, fallback) and the CLI.
|
||||
this module is the **transport** (the two backends; the GitHub token lives in
|
||||
``_sync_token.py``), while ``_sync.py`` keeps **resolution** (cache, staleness,
|
||||
fallback) and the CLI.
|
||||
|
||||
Both backends hold the same end-to-end encrypted layout
|
||||
(``wake-alarm-sync/devices-e2e``), sealed under the shared crdt-sync
|
||||
@ -21,21 +22,19 @@ real file.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from wake_alarm import _sync_token
|
||||
from wake_alarm._alarm_payload import newest_alarm
|
||||
from wake_alarm._constants import (
|
||||
SYNC_ALARM_FILENAME,
|
||||
SYNC_ALARM_PATH,
|
||||
SYNC_APP_NAME,
|
||||
SYNC_CONFIG_FILE,
|
||||
SYNC_HTTP_TIMEOUT_SECONDS,
|
||||
SYNC_LEGACY_PREFIX,
|
||||
SYNC_REPO_NAME,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_TOKEN_FALLBACK_FILES,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -123,58 +122,6 @@ def _read_published(client: RemoteStore) -> list[tuple[str, str]]:
|
||||
return published
|
||||
|
||||
|
||||
def _read_token_config() -> str | None:
|
||||
"""Read the token from this package's own JSON config.
|
||||
|
||||
Returns:
|
||||
The token, or None if the file is missing, unreadable, malformed, or
|
||||
holds no usable token.
|
||||
"""
|
||||
try:
|
||||
with SYNC_CONFIG_FILE.open() as handle:
|
||||
config = json.load(handle)
|
||||
except OSError, json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(config, dict):
|
||||
return None
|
||||
token = config.get("token")
|
||||
if not isinstance(token, str) or not token:
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
def _read_token_fallback() -> str | None:
|
||||
"""Read the token from a sibling app's raw single-line token file.
|
||||
|
||||
Returns:
|
||||
The first usable token found, or None if none of the fallback files
|
||||
exists or holds one.
|
||||
"""
|
||||
for path in SYNC_TOKEN_FALLBACK_FILES:
|
||||
try:
|
||||
token = path.read_text().strip()
|
||||
except OSError:
|
||||
continue
|
||||
if token:
|
||||
_logger.debug("Using sync token from %s", path)
|
||||
return token
|
||||
return None
|
||||
|
||||
|
||||
def _read_token() -> str | None:
|
||||
"""Read the GitHub token, preferring this package's own config.
|
||||
|
||||
Falls back to diet_guard's token file so one repo-scoped PAT covers
|
||||
every app syncing through ``kuhyx/syncs``.
|
||||
|
||||
Returns:
|
||||
The token, or None if no configured source holds one.
|
||||
"""
|
||||
# No warning on a miss here: the caller reports "no token" once. Logging
|
||||
# twice for one unconfigured file makes every tick noisy in the journal.
|
||||
return _read_token_config() or _read_token_fallback()
|
||||
|
||||
|
||||
def fetch_firebase_logs() -> list[tuple[str, str]] | None:
|
||||
"""Fetch every device's decrypted ``alarm.json`` from Firebase.
|
||||
|
||||
@ -235,13 +182,13 @@ def _fetch_github_alarm() -> tuple[int, int, float | None] | None:
|
||||
"""
|
||||
if not _FIREBASE_AVAILABLE:
|
||||
return None
|
||||
token = _read_token()
|
||||
token = _sync_token.read_token()
|
||||
if token is None:
|
||||
# INFO, not WARNING: get_alarm() runs on every one-minute trigger tick,
|
||||
# so a persistent condition logged loudly here is 1440 identical
|
||||
# journal lines a day. The trigger warns once, at the moment it
|
||||
# actually fires on a degraded source — that is the actionable event.
|
||||
_logger.info("No sync token configured at %s", SYNC_CONFIG_FILE)
|
||||
_logger.info("No sync token configured at %s", _sync_token.SYNC_CONFIG_FILE)
|
||||
return None
|
||||
client = GitHubSyncClient(
|
||||
SYNC_REPO_OWNER,
|
||||
|
||||
@ -63,9 +63,9 @@ def _patch_paths(
|
||||
) -> None:
|
||||
"""Redirect every on-disk path into tmp_path for every test."""
|
||||
with (
|
||||
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
|
||||
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -18,6 +18,7 @@ from wake_alarm._sync import Alarm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
from dataclasses import replace
|
||||
|
||||
DAY = date(2026, 10, 1)
|
||||
@ -151,6 +152,35 @@ class TestCli:
|
||||
assert main(["2026-10-01"]) == 1
|
||||
assert "could not write" in capsys.readouterr().err
|
||||
|
||||
def _existing(self) -> Path:
|
||||
_audit.INCIDENTS_DIR.mkdir(parents=True)
|
||||
path = _audit.INCIDENTS_DIR / "2026-10-01.md"
|
||||
path.write_text("keep me")
|
||||
return path
|
||||
|
||||
def test_refuses_to_overwrite(self, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
path = self._existing()
|
||||
assert main(["2026-10-01"]) == 2
|
||||
err = capsys.readouterr().err
|
||||
assert f"refusing to overwrite {path}; use --stdout or --force" in err
|
||||
assert path.read_text() == "keep me"
|
||||
|
||||
def test_stdout_prints_and_writes_nothing(
|
||||
self, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
path = self._existing()
|
||||
with patch.object(_audit, "emit") as emitted:
|
||||
assert main(["2026-10-01", "--stdout"]) == 0
|
||||
assert "# Wake audit 2026-10-01" in capsys.readouterr().out
|
||||
assert path.read_text() == "keep me"
|
||||
emitted.assert_not_called()
|
||||
|
||||
def test_force_overwrites(self) -> None:
|
||||
path = self._existing()
|
||||
with patch.object(_audit, "configure_logging"):
|
||||
assert main(["2026-10-01", "--force"]) == 0
|
||||
assert path.read_text().startswith("# Wake audit 2026-10-01")
|
||||
|
||||
|
||||
def test_timeline_skips_an_unparsable_phone_stamp() -> None:
|
||||
evidence, _ = gather(DAY)
|
||||
|
||||
96
wake_alarm/tests/test_audit_push.py
Normal file
96
wake_alarm/tests/test_audit_push.py
Normal file
@ -0,0 +1,96 @@
|
||||
"""The audit's "has the phone pushed to Firebase lately" check."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm import _audit
|
||||
from wake_alarm._audit import gather
|
||||
from wake_alarm._audit_checks import check_phone_push, run_checks
|
||||
from wake_alarm._audit_evidence import Evidence, PhoneSide
|
||||
from wake_alarm._constants import PHONE_PUSH_STALE_SECONDS
|
||||
from wake_alarm._sync import Alarm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
|
||||
NOW = datetime(2026, 11, 15, 20, 0, tzinfo=UTC)
|
||||
LAST_PUSH = datetime(2026, 11, 13, 17, 38, tzinfo=UTC)
|
||||
|
||||
|
||||
def _ev(last_push: datetime | None) -> Evidence:
|
||||
return Evidence(
|
||||
day=date(2026, 11, 16),
|
||||
stick_day=True,
|
||||
free_day=False,
|
||||
alarm_at=None,
|
||||
alarm_source="t",
|
||||
phone_side=PhoneSide(last_push=last_push),
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_threshold_is_a_day() -> None:
|
||||
assert PHONE_PUSH_STALE_SECONDS == 24 * 60 * 60
|
||||
|
||||
|
||||
def test_a_stale_phone_is_a_mismatch() -> None:
|
||||
check = check_phone_push(_ev(LAST_PUSH))
|
||||
assert check.ok is False
|
||||
assert "2026-11-13 17:38" in check.detail
|
||||
assert "50 h" in check.detail
|
||||
|
||||
|
||||
def test_a_fresh_phone_is_ok() -> None:
|
||||
check = check_phone_push(_ev(NOW - timedelta(hours=3)))
|
||||
assert check.ok is True
|
||||
assert "3 h" in check.detail
|
||||
|
||||
|
||||
def test_exactly_a_day_old_is_still_ok() -> None:
|
||||
assert check_phone_push(_ev(NOW - timedelta(hours=24))).ok is True
|
||||
|
||||
|
||||
def test_a_push_stamped_in_the_future_is_ok() -> None:
|
||||
assert check_phone_push(_ev(NOW + timedelta(minutes=5))).ok is True
|
||||
|
||||
|
||||
def test_no_dated_record_is_unknown_not_ok_not_bad() -> None:
|
||||
check = check_phone_push(_ev(None))
|
||||
assert check.ok is None
|
||||
assert "could not check" in check.detail
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _sources() -> Generator[None]:
|
||||
with (
|
||||
patch.object(_audit, "get_alarm", return_value=Alarm(7, 0, "cache")),
|
||||
patch.object(_audit, "boots", return_value=[]),
|
||||
patch.object(_audit, "resumes", return_value=[]),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def _published(hlc: str) -> list[tuple[str, str]]:
|
||||
fields = {"alarm_hour": [7, hlc]}
|
||||
return [("p", json.dumps({"alarm": {"fields": fields}}))]
|
||||
|
||||
|
||||
def test_gather_feeds_the_check_and_it_runs_with_the_rest() -> None:
|
||||
published = _published("2026-11-13T17:38:00.000Z-0001-p")
|
||||
with patch.object(_audit, "fetch_firebase_logs", return_value=published):
|
||||
evidence, _ = gather(date(2026, 11, 16))
|
||||
assert evidence.phone_side.last_push == LAST_PUSH
|
||||
assert "phone pushed to Firebase" in [c.name for c in run_checks(evidence)]
|
||||
|
||||
|
||||
def test_gather_unreachable_firebase_is_unknown() -> None:
|
||||
with patch.object(_audit, "fetch_firebase_logs", return_value=None):
|
||||
evidence, reachable = gather(date(2026, 11, 16))
|
||||
assert not reachable
|
||||
assert check_phone_push(evidence).ok is None
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
|
||||
from wake_alarm._enforcement_payload import (
|
||||
@ -85,3 +86,19 @@ def test_only_honoured_escapes_count() -> None:
|
||||
def test_is_honoured_rejects_a_bad_date() -> None:
|
||||
assert not is_honoured(Escape("x", "someday", "", REASON))
|
||||
assert not is_honoured(Escape("x", "2026-10-01", "", " " * 50))
|
||||
|
||||
|
||||
def test_last_push_is_the_newest_dated_hlc_of_any_field_on_any_device() -> None:
|
||||
old = _log(alarm_hour=(7, "2026-11-12T08:00:00.000Z-0000-a"))
|
||||
new = _log(
|
||||
alarm_hour=(7, "2026-11-01T08:00:00.000Z-0000-b"),
|
||||
phone_events=([], "2026-11-13T17:38:00.000Z-0001-b"),
|
||||
stick_state=({"streak": 0}, "garbled"),
|
||||
)
|
||||
view = enforcement_view([("a", old), ("b", new), ("c", "{bad")])
|
||||
assert view.last_push == datetime(2026, 11, 13, 17, 38, tzinfo=UTC).timestamp()
|
||||
|
||||
|
||||
def test_last_push_is_none_without_a_dated_stamp() -> None:
|
||||
assert enforcement_view([("a", _log(alarm_hour=(7, "h")))]).last_push is None
|
||||
assert enforcement_view([]).last_push is None
|
||||
|
||||
94
wake_alarm/tests/test_ring_main.py
Normal file
94
wake_alarm/tests/test_ring_main.py
Normal file
@ -0,0 +1,94 @@
|
||||
"""The user-side ring entry the root ALSA script falls back to."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import signal
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from wake_alarm import _ring_main
|
||||
from wake_alarm._ring_main import main
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
WAVS = ["rise.wav", "loop.wav"]
|
||||
|
||||
|
||||
def _backend(*, start: tuple[bool, str] = (True, "ok"), pumps: list[bool]) -> MagicMock:
|
||||
backend = MagicMock()
|
||||
backend.name = "pipewire"
|
||||
backend.start.return_value = start
|
||||
backend.pump.side_effect = pumps
|
||||
return backend
|
||||
|
||||
|
||||
def _run(backend: MagicMock, argv: list[str] | None = None) -> tuple[int, MagicMock]:
|
||||
with (
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend),
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit") as emitted,
|
||||
patch.object(_ring_main.time, "sleep"),
|
||||
):
|
||||
return main(WAVS if argv is None else argv), emitted
|
||||
|
||||
|
||||
def test_start_failure_emits_failed_and_exits_1() -> None:
|
||||
backend = _backend(start=(False, "no pw"), pumps=[])
|
||||
code, emitted = _run(backend)
|
||||
assert code == 1
|
||||
assert "FAILED" in emitted.call_args.args[1]
|
||||
backend.stop.assert_not_called()
|
||||
|
||||
|
||||
def test_pump_failure_exits_1_and_stops() -> None:
|
||||
backend = _backend(pumps=[True, False])
|
||||
code, emitted = _run(backend)
|
||||
assert code == 1
|
||||
assert "started" in emitted.call_args_list[0].args[1]
|
||||
# pw-play dying mid-ring is a failure the audit must see, not silence.
|
||||
assert "FAILED" in emitted.call_args.args[1]
|
||||
assert emitted.call_args.kwargs["started"] is False
|
||||
backend.stop.assert_called_once()
|
||||
|
||||
|
||||
def test_sigterm_ends_the_ring_cleanly() -> None:
|
||||
backend = _backend(pumps=[True, True])
|
||||
handler: list[Callable[..., object]] = []
|
||||
|
||||
def capture(sig: int, fn: Callable[..., object]) -> None:
|
||||
assert sig == signal.SIGTERM
|
||||
handler.append(fn)
|
||||
|
||||
def stop_after_first(_: float) -> None:
|
||||
handler[0](signal.SIGTERM, None)
|
||||
|
||||
with (
|
||||
patch.object(_ring_main.signal, "signal", capture),
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend),
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit"),
|
||||
patch.object(_ring_main.time, "sleep", stop_after_first),
|
||||
):
|
||||
assert main(WAVS) == 0
|
||||
backend.stop.assert_called_once()
|
||||
|
||||
|
||||
def test_wrong_usage_exits_2(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
assert main(["only-one"]) == 2
|
||||
assert "Usage" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_paths_reach_the_backend() -> None:
|
||||
backend = _backend(pumps=[False])
|
||||
with (
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend) as cls,
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit"),
|
||||
):
|
||||
main(WAVS)
|
||||
cls.assert_called_once_with(Path("rise.wav"), Path("loop.wav"))
|
||||
@ -108,3 +108,27 @@ def test_real_seam() -> None:
|
||||
with patch.object(subprocess, "run", return_value=_done()) as run:
|
||||
REAL_RUN(["true"])
|
||||
assert run.call_args.args[0] == ["true"]
|
||||
|
||||
|
||||
def test_rtc_offset_still_matches_our_alarm() -> None:
|
||||
"""rtcwake shifts -t by the RTC/system clock offset (seen: +1 s)."""
|
||||
with patch.object(_rtc_hw, "_run", return_value=_done()):
|
||||
arm(EPOCH, "2026-10-06")
|
||||
_rtc_hw.WAKEALARM_FILE.write_text(str(EPOCH + 1))
|
||||
run = MagicMock(return_value=_done())
|
||||
with patch.object(_rtc_hw, "_run", run):
|
||||
assert arm(EPOCH, "2026-10-06") == (True, "already set")
|
||||
record, disarmed, _ = disarm_ours()
|
||||
assert (record, disarmed) == (ArmedRecord(EPOCH, "2026-10-06"), True)
|
||||
assert run.call_args.args[0][-2:] == ["-m", "disable"]
|
||||
|
||||
|
||||
def test_alarm_an_hour_away_is_not_ours() -> None:
|
||||
with patch.object(_rtc_hw, "_run", return_value=_done()):
|
||||
arm(EPOCH, "2026-10-06")
|
||||
_rtc_hw.WAKEALARM_FILE.write_text(str(EPOCH + 3600))
|
||||
assert disarm_ours() == (
|
||||
ArmedRecord(EPOCH, "2026-10-06"),
|
||||
False,
|
||||
"no longer pending",
|
||||
)
|
||||
|
||||
@ -64,9 +64,9 @@ def _patch_paths(
|
||||
) -> None:
|
||||
"""Redirect every on-disk path into tmp_path for every test."""
|
||||
with (
|
||||
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
|
||||
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -61,9 +61,9 @@ def _patch_paths(
|
||||
) -> None:
|
||||
"""Redirect every on-disk path into tmp_path for every test."""
|
||||
with (
|
||||
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
|
||||
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -14,7 +14,7 @@ from unittest.mock import patch
|
||||
from crdt_sync import open_encrypted_client
|
||||
import pytest
|
||||
|
||||
from wake_alarm import _sync_transport
|
||||
from wake_alarm import _sync_token, _sync_transport
|
||||
from wake_alarm._constants import SYNC_DEVICES_PREFIX, SYNC_LEGACY_PREFIX
|
||||
from wake_alarm.tests.conftest import TEST_ARGON2, TEST_PHRASE, DictStore
|
||||
|
||||
@ -30,8 +30,8 @@ def config_file(tmp_path: Path) -> Iterator[Path]:
|
||||
"""This app's GitHub token config, redirected; no sibling fallbacks."""
|
||||
path = tmp_path / "sync.json"
|
||||
with (
|
||||
patch.object(_sync_transport, "SYNC_CONFIG_FILE", path),
|
||||
patch.object(_sync_transport, "SYNC_TOKEN_FALLBACK_FILES", ()),
|
||||
patch.object(_sync_token, "SYNC_CONFIG_FILE", path),
|
||||
patch.object(_sync_token, "SYNC_TOKEN_FALLBACK_FILES", ()),
|
||||
):
|
||||
yield path
|
||||
|
||||
|
||||
@ -59,9 +59,9 @@ def _patch_paths(
|
||||
) -> None:
|
||||
"""Redirect every on-disk path into tmp_path for every test."""
|
||||
with (
|
||||
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
|
||||
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for _sync.py's GitHub token discovery and its sibling fallbacks.
|
||||
"""Tests for _sync_token.py's GitHub token discovery and its sibling fallbacks.
|
||||
|
||||
Split out of test_sync.py to hold both files under the 250-line gate.
|
||||
"""
|
||||
@ -11,9 +11,9 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm._sync import (
|
||||
_read_token,
|
||||
from wake_alarm._sync_token import (
|
||||
_read_token_fallback,
|
||||
read_token,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -58,40 +58,40 @@ def _patch_paths(
|
||||
) -> None:
|
||||
"""Redirect every on-disk path into tmp_path for every test."""
|
||||
with (
|
||||
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
|
||||
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
|
||||
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
class TestReadToken:
|
||||
"""Tests for _read_token."""
|
||||
"""Tests for read_token."""
|
||||
|
||||
def test_missing_file(self) -> None:
|
||||
"""A missing config file yields no token."""
|
||||
assert _read_token() is None
|
||||
assert read_token() is None
|
||||
|
||||
def test_malformed_json(self, config_file: Path) -> None:
|
||||
"""Unparsable JSON yields no token."""
|
||||
config_file.write_text("{not json")
|
||||
assert _read_token() is None
|
||||
assert read_token() is None
|
||||
|
||||
def test_not_a_dict(self, config_file: Path) -> None:
|
||||
"""A JSON array is not a config object."""
|
||||
config_file.write_text("[]")
|
||||
assert _read_token() is None
|
||||
assert read_token() is None
|
||||
|
||||
@pytest.mark.parametrize("value", [None, "", 42])
|
||||
def test_unusable_token_values(self, config_file: Path, value: object) -> None:
|
||||
"""Absent, empty and non-string tokens are all rejected."""
|
||||
config_file.write_text(json.dumps({"token": value}))
|
||||
assert _read_token() is None
|
||||
assert read_token() is None
|
||||
|
||||
def test_valid_token(self, config_file: Path) -> None:
|
||||
"""A non-empty string token is returned."""
|
||||
config_file.write_text(json.dumps({"token": "ghp_x"}))
|
||||
assert _read_token() == "ghp_x"
|
||||
assert read_token() == "ghp_x"
|
||||
|
||||
|
||||
class TestTokenFallback:
|
||||
@ -100,7 +100,7 @@ class TestTokenFallback:
|
||||
def test_no_fallback_files(self) -> None:
|
||||
"""With nothing on disk anywhere there is no token."""
|
||||
assert _read_token_fallback() is None
|
||||
assert _read_token() is None
|
||||
assert read_token() is None
|
||||
|
||||
def test_reads_raw_single_line_token(
|
||||
self, fallback_files: tuple[Path, Path]
|
||||
@ -130,11 +130,11 @@ class TestTokenFallback:
|
||||
"""wake_alarm's own config takes precedence over a sibling's."""
|
||||
config_file.write_text(json.dumps({"token": "ghp_own"}))
|
||||
fallback_files[0].write_text("ghp_sibling")
|
||||
assert _read_token() == "ghp_own"
|
||||
assert read_token() == "ghp_own"
|
||||
|
||||
def test_falls_back_when_config_absent(
|
||||
self, fallback_files: tuple[Path, Path]
|
||||
) -> None:
|
||||
"""With no own config, the sibling token is used."""
|
||||
fallback_files[0].write_text("ghp_sibling")
|
||||
assert _read_token() == "ghp_sibling"
|
||||
assert read_token() == "ghp_sibling"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user