Compare commits

...

143 Commits

Author SHA1 Message Date
88b6a9306d Pin flutter_local_notifications 23.0.4
Some checks failed
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze,dependency-freshness) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
The dependency-freshness hook went red on the new upstream release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:21:42 +01:00
5ba9e4b438 Pay flat bonuses by signed progress
earned_time 0.24 progress rows: the reset and sick floor pass
progress_map to resolve (workout left out, WorkoutCreditMixin owns
it); the live pass pays max(0, pay_now - applied) and stamps
<name>_bonus_minutes. A legacy <name>_bonus_date of today still
means the full bonus, so a mid-day deploy never pays twice. The
reset stamps minutes, never the date, so a partial stays open.
No progress row pays exactly as before; a credit pays in full.

Lands 5b6ac0b from the progress stack as this commit; its parent
4ed64b4 was already on main. Pins earned_time to the new tag
earned-time-v0.24.0 (utils c06f2da), in the manifests and the
pylint hook envs.

The preview keeps both sides: earners come from the day's registry
(main) and are priced through term_for with a progress row (stack).
_preview_sim.ROWS is the one row source for the live add and the
derivation; a new test pins a 1-of-2 review row on 2026-11-24 and
checks the preview pays term_for's share (10), not the flat 20.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:21:39 +01:00
a8c6177012 Skip the coverage bar on -k subset runs
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
pytest -q -k <name> (the board's done_check form) exited 1 on green
tests: fail_under = 100 judged a handful of tests against the whole
package. A pytest_sessionstart plugin clears pytest-cov's fail_under
when a keyword is given; whole-suite runs (commit gate, full_gate.sh,
CI) select none and keep the bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:49:14 +01:00
c7a7593a55 Pin the review preview on 2026-11-24 too
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:45:50 +01:00
acf69becc7 Preview a review credit by the day's registry
preview_shutdown --sequence review@HH:MM raised KeyError: the review
(ReviewEarner) joins the registry only through earners_for(day) from
REVIEW_FROM, while the sim looked names up in the static EARNERS tuple.
The sim now looks earners up in the simulated day's registry, the done
maps come from that day's flat earners, and a step that is no earner on
that day is an argparse usage error (exit 2), not a traceback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:43:07 +01:00
e7bf74c3aa Pin gatelock 0.16.1, crdt_sync_dart 0.14.2
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
sync_settings_ui 0.8.6 too: the freshness gate went red after
the upstream releases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:07:19 +01:00
4ed64b463c Write a progress row for a short run day
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
When a verified RunnerUp day is real but too short to qualify, the
ledger now gets one signed "progress" row saying how far it got:
metres over the distance bar or seconds over the time bar, whichever
fraction is larger, from the verified TCX only. Several short runs in
a day are summed; a longer second run writes a new row with a larger
done. The row is inert: no reader uses it yet, and no bonus, shutdown
time, stamp or web payload changes.

Qualifying days write only their normal credit. Manual and StrongLifts
days and the rooted-DB path write nothing.

Failure modes: if the row cannot be signed or written, the workout
verdict and everything else proceed exactly as before and the failure
is logged at warning or above. An unreadable TCX is "could not check"
and writes nothing. The bars appear only inside the signed row, never
in a log line or message.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVfmEXxPymCs5bo3Zs
2026-11-22 18:23:46 +01:00
c852379719 Pin sickdays 0.5.9, freedays 0.4.4
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
sickdays 0.5.8 pinned kuhy-credit 0.3.1, so the clean CI install
could not resolve against kuhy-credit 0.3.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:36:39 +01:00
90c542e069 Audit icons: add 1-word hover tooltips
Todo: fe70b845
2026-11-22 16:25:40 +01:00
5c1bfb93ec Pin earned-time 0.23.0
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
0.23.0 adds the LeetCode review top-up earner (20 shutdown minutes for a
finished review, in the registry from 2026-11-23). Pin-only for this repo,
plus the one test that assumed the stand-in earner is last.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXYyzSw5S9UTM5k5M1
2026-11-21 22:31:19 +01:00
71aca9740f Rebuild web/dist on deploy when web/ changed
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The server serves the git-ignored web/dist, so a deploy that only pulled
and restarted kept the last hand-built bundle live; the kuhy credit footer
never reached :8770. deploy.sh now rebuilds it when the web/ tree differs
from the last built one (--web-only runs just that step).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:53:04 +01:00
25a5f534f2 Fit the line cap; sort requirements
Some checks failed
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
release-apk / release (APK) (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:44:15 +01:00
83ca052a1c Docstrings and top-level imports in credit test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:42:40 +01:00
a5a50d72c7 Add kuhy-credit to the pylint hook envs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:40:56 +01:00
97b7e85bb2 Show kuhy credit logo on lock, app and web
The shared kuhy_credit logo (kuhyx/utils, kuhy-credit-v0.3.1) now sits
bottom-right on every lock surface, the aux windows, the status window
and the heat-skip prompt; at the end of the workout app's Settings;
and in the web dashboard footer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:32:42 +01:00
3595b61902 Cap gate shard flutter tests at 2 isolates
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The gate shards inherited one test isolate per core and hit the
4 GiB capped.sh limit in ~6 s, so the kernel OOM-killed them.

Todo: f1ccef82

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:21:12 +01:00
b25412d819 screen locker workout app
Todo: f1ccef82
2026-11-21 08:18:04 +01:00
c4dc30502b Cover gap deload launch, seed and edge rows
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
2026-11-21 00:57:40 +01:00
218e84e04a Make the v10 migration idempotent
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:40:44 +01:00
394ff70dc5 Load gap deload marks after the snapshot push
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:44 +01:00
9b50d95386 Resolve adb path in restore script; trim header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:22:24 +01:00
1cbb310ff7 Split gap deload files under the 250-line cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:20:28 +01:00
be15e1c083 Docstrings for restore script tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:15:54 +01:00
a5ec96f1b8 Fix gap deload tile test label lookup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:11:54 +01:00
bc4e590822 workout_app: deload after a training gap at load
The old break rule ran at finish after the session was saved, so
daysSince was always 0 and it never fired. Now the gap deload cuts
by tier (7-13d 1 step, 14-20d 2, +1/week, 40% cap) when the workout
loads, stamps last_deloaded_at (shared with manual deload, synced),
logs progression_events, and shows the old target struck through.
One-time backfill with pre-cut export + restore script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:11:54 +01:00
27e4ff5064 Bump coverage to 7.17.4
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
2026-11-20 23:38:30 +01:00
2e58e734ef workout_app: drop geolocator for LocationManager
geolocator_android links non-free play-services-location (plus -base,
-basement, -tasks). LocationManagerPositionSource reads fixes through
kuhyx/utils platform_location (AOSP LocationManager, also registers in
the run-service isolate). Release APK: 0 com/google/android/gms
classes (was 15). Emulator: 2 s GPS fixes with the screen off,
location-off and denied-forever states.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:33:40 +01:00
9c0af63547 Bump flutter 3.50.1, gradle 9.9.2, web deps
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Freshness gate went red on new upstream releases: flutter 3.50.1,
gradle 9.9.2, astro 7.4.13, jest-dom 8.0.0, user-event 14.6.13.
Web tests 100% covered, lint and build green; daily release APK
builds on 3.50.1 with no analyzer issues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:26:22 +01:00
2987d6efa7 Arm stall watch once the Tk loop runs
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The watch was armed in __init__, before the lock window build
(xrandr, setxkbmap, surfaces, grab), so the ~1.5 s build was reported
as a tk.mainloop freeze. Arm it via after_idle in run() instead; a real
freeze after the loop starts is still reported.

Error-Signature: screen-locker:c890f31a21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:12:10 +01:00
26853a9dfe Skip phone deploy when the app is unchanged
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
deploy.sh records the workout app's git tree after each phone install
and skips the phone when the tree is the same, so a PC-only change
deploys with the phone unplugged. No record means the phone is needed.

Todo: 2556952d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:25:51 +01:00
84e8f7fff5 Drop freshness-only deps from CI pre-commit
pyyaml and packaging were installed only for dependency-freshness,
which CI no longer runs.

Todo: 2556952d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:10:46 +01:00
9c4f8e32cf Bump sickdays to 0.5.6
Todo: 2556952d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:05:11 +01:00
edde541f91 Cap CI mirror pytest at 4 xdist workers
-n auto (16 workers) peaked at 3.2 GiB and the kernel OOM-killed the
ci-pytest gate step in capped.sh's 4 GiB slice. 4 workers fit in 2 GiB
and finish in 19 s instead of 58 s under the CPU cap.

Todo: 2556952d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:05:02 +01:00
62fa631b6b get rid of github ci/cd version check of package…
Todo: 2556952d
2026-11-19 20:46:45 +01:00
a7620e37b8 Bump vitest and coverage-v8 to 5.1.1
Some checks failed
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:49:45 +01:00
5f462e42bd Serve the build stamp at /version
pnpm build now writes the short HEAD hash to web/dist/version.txt
(web/stamp-version.mjs). The web server serves it at GET /version as
text/plain and answers 404 when the stamp is missing, so an unstamped
build never passes a live-build check. Docstring now says Astro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:40:01 +01:00
9e7f536f96 Report errors and stalls to the shared board
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
gatelock error_report: uncaught, thread and Tk callback errors plus a
frozen lock window over 1 s go to the app-errors spool. The pre-commit
pylint env moves to gatelock 0.16.0, the version requirements pin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:00:15 +01:00
2faa118ac2 Bump gatelock, data_transfer, sync_settings_ui
Some checks failed
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
release-apk / release (APK) (push) Has been cancelled
gatelock 0.16.0 (already installed on the PC), data_transfer_flutter
0.2.3 and sync_settings_ui 0.8.4: tagged today, the freshness gate
refused the push.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
2026-11-18 21:16:00 +01:00
7bfd19edae Drop credit-time asserts from unlock tests
Two more callers asserted the at= anchor the late-credit rule needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
2026-11-18 21:16:00 +01:00
67a54ba89d Add every credit to tonight's shutdown
kuhy, 2026-11-18: shutdown 18:00, a run ending 19:58 must give 20:00
and the book's +1h 21:00 -- what the daily reset derives. The
late-credit rule (credit's own time + reward, 2026-10-17) made it
21:58 and 22:58. Unpaid gates now hold the PC behind the evening
chain until 23:00 instead, so the rule and its credit-time plumbing
go: _late_credit, the at= anchors, _done_at. The preview flags any
live-vs-derived MISMATCH again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
2026-11-18 21:12:40 +01:00
64c6105dbe Bump flutter_local_notifications to 23.0.3
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
2026-11-18 20:55:42 +01:00
7539a82429 Show the run's reward in the credit toast
A late credit moves shutdown from an hour already past to the run's
end plus its reward, so the toast read "+3h58m" for a 2h run
(18:00 -> 21:58, 2026-11-18). The delta is now capped at the reward
the credit earned: still the real move when the ceiling cut it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
2026-11-18 20:53:52 +01:00
95adc8699c Document the selective push gate
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:52:00 +01:00
89f8efc92b Set push gate Dart budget to 25 tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:51:33 +01:00
01b7a4a83f Fix ruff findings in selector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:54 +01:00
55d5d29fed Satisfy pylint in coverage helper
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:37 +01:00
c3207c43dc Docstring the selector tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:26 +01:00
4b6e4df1bf Log gate helper failures
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:50:09 +01:00
f79d425d3d Add full gate, nightly timer, 8 shards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:47:43 +01:00
100b0c9663 Add selective push gate and wire it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:47:11 +01:00
1c696b72ce Test the push-gate selector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:46:44 +01:00
eb9d8c5e32 Add change-based test selector for push gate
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:46:18 +01:00
4009e9475b Bump material_ui, sync_settings_ui, web pins
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:37:53 +01:00
9ba2f46c23 Fix run-mode gates: logs, file caps, coverage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
2026-11-17 22:35:32 +01:00
2137152729 Relay run notification taps to the host
flutter_foreground_task 11.0.3 calls onNotificationPressed only for a
MAIN+LAUNCHER intent; the sandbox has no LAUNCHER filter, so the press
never reached RunHost. MainActivity now relays it (cold and warm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:55:52 +01:00
0175cbede4 Persist runs: tests, trims, adapter coverage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:28:45 +01:00
cfc2cd553a Adapt run host to the real recorder API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 21:08:45 +01:00
218632fd0e Merge branch 'run-persist-logic' into worktree-agent-ad5ad3468f792eb82 2026-11-17 20:59:06 +01:00
c1dbfa0352 Host the run in the foreground service
WIP: host, link, view, finish modal, launch routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 20:59:06 +01:00
d45e67a02c Persist and bridge GPS runs across death
Checkpoint codec and file store, gap bridging at 2:30-12:00 min/km, watchdog (suggest finish, 5 h auto end), recorder restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
2026-11-17 20:54:40 +01:00
bdf79ca6be Pin sickdays-v0.5.5 for freshness gate
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWViGJJaqBKGr1Hbppr
2026-11-16 16:17:38 +01:00
ad849aff02 Drop gaming from credit toast and poke
Pin earned-time-v0.22.0. The toast and the poke reply show only the
shutdown gain; gaming_budget_minutes leaves the reply and the phone
app's result line (an older PC's field is ignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWViGJJaqBKGr1Hbppr
2026-11-16 16:13:46 +01:00
8e52688138 Key workout_app /sdcard paths on package name
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
A slot build (com.kuhy.slotN) shared /sdcard/WorkoutTracker and
workout_result.json with the daily build. MainActivity now reports the
package name; any package but com.kuhy.workout_app gets sibling paths
and never reads RunnerUp's exports. The daily build's paths are
unchanged, so the PC side needs nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:47:49 +01:00
981fad12f0 Bump gatelock to 0.14.0
On 2026-11-16 at 09:35 a session ran an install.sh pinning gatelock 0.13.0, which downgraded system python's gatelock and broke diet-guard's lock window (ImportError: watch_credit). One pin across all consumers stops install.sh from downgrading it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:45:04 +01:00
68d5ef98af Let sandbox run test drain its late chimes
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
run_screen_sandbox_test failed in flutter test: the kilometre chimes
play after the vibrator probe answers, so the last ones can start
audioplayers' frame callbacks after the final pump, and the framework
reports them as running after the tree was disposed. The test now
waits 300 ms and pumps twice before it ends. It failed the same way
on 74a39c3, so it was not caused by the material_ui move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:16:03 +01:00
f26903f57a Zero gatelock's startup grace in tests
wait_for_turn sleeps its 1.5 s startup grace for real, so every test
that builds a locker paid it. The suite took ~135 s under the CPU
cap and the ci-pytest gate step could not finish inside the 60 s
action cap. With the grace zeroed in the hermetic gatelock fixture
all 2142 tests run in 13 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:06:03 +01:00
9eac2ce3d6 Bump dependencies behind newest stable
The dependency-freshness gate failed the pre-push stamp on 17
findings: node 26.13.1, crdt-sync 0.11.1, freedays 0.4.3, sickdays
0.5.4 (the pylint hooks still pinned 0.3.0), coverage 7.17.3, pylint
4.1.4, ruff 0.17.5, flutter_local_notifications 23.0.2, and five
web packages with pnpm 12.21.0. Manifests, hook pins and lockfiles
move together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 08:57:17 +01:00
5f2925a550 Move workout_app to Flutter 3.50 material_ui
Flutter 3.50 deprecates package:flutter/material.dart, which made
flutter-analyze report 27 deprecated_member_use infos and blocked the
gate. workout_app now imports material_ui 1.11.0, with crdt_sync_dart
0.14.1 and sync_settings_ui 0.8.2 (both on material_ui).

material_ui's MaterialApp ships its own MaterialLocalizations, so a
package that still calls the framework showDialog threw a null check.
WorkoutApp now adds the framework delegate, and a widget test opens a
material_ui and a framework dialog through the real app root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 08:54:33 +01:00
74a39c3054 Close the lock window when credit lands
On 2026-11-16 a manual workout was credited at 07:59 by
_session_stream, but the open lock window never rechecked log.json
(TRY AGAIN only asked StrongLifts/adb), so kuhy had to mark a sick
day. The window now polls log.json mtime every 3 s via Tk after and
stands down (decision workout_credited_elsewhere, no second credit),
and TRY AGAIN stands down when today is already logged.
_verify_phone_workout is deliberately unchanged (shared with
early-bird/status).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 08:29:01 +01:00
50c32c4f40 Find shared sync screen by type, not title
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
sync_settings_ui 0.7.0 is text-free; its AppBar title is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:08:26 +01:00
459b400b6a Bump sickdays 0.5.0, sync_settings_ui 0.7.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:53:08 +01:00
aa70a9181f Add deploy script and CLAUDE.md deploy line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:42:45 +01:00
ccc0e09938 Bump gatelock to 0.13.0
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZbpxQZj41WpbQPuxB
2026-11-11 12:59:06 +01:00
71cb5eecdb Drop GPS dropout bridging
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Revert 6777656; the app again writes zero distance across a gap
over 30 s. Also drop the importer-test skip for its fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYwyP67ppvkeie3X1F
2026-11-11 12:12:42 +01:00
eb4ce6fd68 Bind HTTP server tests to an ephemeral port
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
2026-11-11 11:53:35 +01:00
f0d4f1036c Bump notification, sqflite, user-event pins
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:50:20 +01:00
83a5c6b4bc Fix lint in text-free check and glyph tests
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
2026-11-11 01:32:10 +01:00
71a35d6aa1 Guard workout app screens against painted words
Walks every RenderParagraph of the main screens and widget states;
fails on any 2+ letter word besides exercise names and units after a
number. Red on 32a735f (22 of 23), green now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
2c52408cec Make GitHub mirror screen text-free
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
17014c6399 Make manual workout form text-free
Fields carry a glyph (old label spoken), group headings are dividers,
budget and date are numbers, errors an error glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:49 +01:00
b584c0441b Make settings screen text-free
Headings are glyphs, helper paragraphs are gone, statuses are a
tick/warning glyph with the sentence spoken, the exercise summary is
glyphs + numbers, PC pairing a link glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
5fa160f114 Make history screen text-free
Section headings and the all-workouts entry are glyphs, tiles drop
their word prefixes, chart and calendar dates are numeric, weekday
headers are dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
661b293bc2 Make exercise tile and settings sheet text-free
Mode chip shows the mode glyph, paused row a pause glyph + 11.10 date
+ cross. Target change reads x13 / = instead of 13 reps / same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
1f8f602564 Make workout summary and PC line text-free
Summary title is a trophy/flag glyph, duration mm:ss, save state a
glyph, home button a glyph. The PC line is PC glyph + outcome glyph +
the PC's own numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:48 +01:00
b24718710e Make workout app home screen text-free
Home card: plan letter + state glyph, play-glyph buttons. Sync card
and banner: state glyph, age as 5m/3h/2d, action glyph. Old words
stay as spoken labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:28:47 +01:00
e5bfdd9a9a Make the Tk locker screens text-free
Every locker screen, the status window and the credit toast now show
glyphs (screen_locker/_glyphs.py) and numbers, coloured by state.
Sentences that carried a reason (verifier message, sync diagnosis,
sick refusal, form rejection) go to the log at warning instead.
New pre-commit hook text-free runs scripts/verify_text_free.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:20:23 +01:00
3073faa623 Add text-free check for locker screens
Paints every locker screen under Xvfb and fails on any painted word.
Red now: 18 screens. --shots DIR saves one PNG per screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:07:57 +01:00
32a735f168 Drop explanation pages and window titles
textgate scan 319 -> 0: docs/explanations (dropped explain-diff
output, not published, nothing links it), Tk window titles, the
MaterialApp title, '+kg' -> '+' plus the weight icon, and
spoken-only Semantics labels hoisted so the gate sees them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:04:56 +01:00
b6db88f9b9 Make workout app and locker text-free
Painted chrome becomes icons or symbols; old words stay as
spoken labels or code comments. OS window titles kept. Tests
build today from the local day.

Todo: ed07cff3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 00:54:59 +01:00
e08a520019 Bump shared Flutter pins, typescript-eslint
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
data_transfer_flutter 0.2.2, sync_settings_ui 0.6.3,
typescript-eslint 8.72.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 20:08:05 +01:00
94f9822884 Let CI mirror pytest worker count be set
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:48:00 +01:00
94a55deb86 Keep dropout fixture out of importer tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:39:51 +01:00
13f1e9ed93 Fix pylint shadowed tcx in webdav test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:32:43 +01:00
6777656418 Bridge GPS dropouts in run distance
The PC keeps a dropout moving at 1 m/s to 25 km/h; the app zeroed
every gap over 30 s. Bridge unpaused dropouts, pauses stay zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:11:42 +01:00
9c415d8f9a Bump astro 7.4.8 and gradle 9.9.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:11:07 +01:00
9641906818 Pace target in backup, run rule comments
Back up and restore the pace target (null or absent = off, a stale
target is cleared). Mirror comments in run_math and friends now state
the PC's merged rule and where the app is stricter. Pace tones get
MANIFEST entries; default map and backup get tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXcjiPpgRfxzrRfoky
2026-11-10 19:05:53 +01:00
cd32c0a79e Merge branch 'worktree-agent-af4066a0307a0da8f'
# Conflicts:
#	stronglift_replacement/workout_app/lib/services/run_math.dart
2026-11-10 18:48:22 +01:00
48d21bfafc One-mode run, pace target, idle map
Remove the run/walk toggle: every recording uses the 25 km/h running
filter and writes a Running TCX; decodeTcx still reads walking files.
Add the optional pace target (stepper, 30 s current pace, band,
throttled cues, persisted). The idle map follows the user's fix; refused
location shows only the red icon, no map and no start.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:47:53 +01:00
6df7c397ca Merge branch 'worktree-agent-aa94bbfa685da1112' 2026-11-10 18:36:47 +01:00
882b6a56c8 Reapply "Merge branch 'worktree-agent-aa94bbfa685da1112'"
This reverts commit 43e7f6d7e0.
2026-11-10 18:36:47 +01:00
fccde84bcb Judge speed over 10 s windows, keep dropouts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:36:25 +01:00
43e7f6d7e0 Revert "Merge branch 'worktree-agent-aa94bbfa685da1112'"
This reverts commit 8cc66d2803, reversing
changes made to ba9e9c31c0.
2026-11-10 18:29:41 +01:00
8cc66d2803 Merge branch 'worktree-agent-aa94bbfa685da1112' 2026-11-10 18:28:41 +01:00
d066726a60 Cap credited pair speed at 25 km/h
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:28:28 +01:00
f528722e1f Make unified tests match the -k filter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:26:23 +01:00
0a48b76d59 Credit runs and walks by one rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:23:57 +01:00
ba9e9c31c0 Open OSM tiles over TLS in the sandbox
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:18:00 +01:00
d0bb8d700e Allow OSM tiles in the sandbox, log metres
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 18:13:26 +01:00
1475ab913b Shard ci-precommit into four gate steps
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Each slice runs under 30 s; together they run all 35 default-stage
hooks once. CI (pre-commit.yml) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:45:58 +01:00
2998bd5353 Give enum-only run files covered members
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:40:13 +01:00
0ec8cfddec Exempt run_tcx fixtures from whitespace fixers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:35:55 +01:00
39c85a7dfd Revert "Normalize run_tcx fixture whitespace"
The golden test compares the encoder with these byte-exact files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:35:54 +01:00
5d3547c221 Fix gate: file caps, silent catch, pin bump
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:31:18 +01:00
7f9169b9d0 Normalize run_tcx fixture whitespace
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:19:37 +01:00
17dac66a11 Allow an extra workout after done today
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:53:37 +01:00
23ad2e02b4 Swap google_sign_in for google_account_token
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:48:04 +01:00
aaaecca3be Show the live map on the run screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:27:42 +01:00
bd12b8711d Add run screen, home entry, provisioning
One-screen live run UI (icons and digits), map slot via mapBuilder, upload badge, sandbox e2e, Pixel 6a inset test, dufs provisioning script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:24:25 +01:00
97d73b31f5 Merge main, use shared dufs login
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:15:15 +01:00
66e9948777 WIP run screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:12:59 +01:00
801e303b39 Merge branch 'worktree-agent-a19044abadd522d41' 2026-11-10 16:12:27 +01:00
6fa9666cdd Marker lists distinct runs; guard fixes
Marker: twins (Pixel_6a_ infix) listed once, app-authored files never. Backup guard: a recorded run no longer lifts the workout-history clobber guard. runGuarded: a throw outside per-file handling logs and sets failed. Silent-failure hook clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:11:59 +01:00
b1ff91249b Merge branch 'worktree-agent-acd53f670745f7d44' 2026-11-10 16:09:14 +01:00
0411116f24 Harden RunnerUp retirement after review
Silent-failure checker, mypy, pylint now clean. Hidden packages count
as installed (pm list -u), pull gets a long timeout, wifi entries are
matched by ro.serialno, and a missing log/drop dir is a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:08:40 +01:00
770a88454d Add run controller, run service, km cue
Foreground service (dataSync+location) started after access, numbers-only notification, kilometre buzz and chime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:07:25 +01:00
a6c97dab8f Import RunnerUp history into the app
One-time, phone-only import of /RunnerUp/processed over dufs WebDAV as display-only runs, then a dotfile marker PUT for the PC. Never PUTs a tcx. Icon-only status badge in Settings, shared DufsCredentials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:07:03 +01:00
8ca4c301fd Back up and export GPS runs
runs/run_points were in neither backup.json nor the user export. App-made runs go in the backup (history returns from the PC), all runs in export v3; merge keyed by id or hash, idempotent. The backup clobber guard now also protects a runs-only backup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:06:56 +01:00
ca205fa67e Build a fresh tile provider per map
TileLayer disposes its provider; cache only the directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:03:02 +01:00
25ee5ca9ad Add sandbox GPS replay and speed setting
Synthetic 4 km loop generated in Dart, replayed at 1x/10x/60x; main imports the dufs login and retries pending uploads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:02:39 +01:00
50faee673f Wire runnerup-retire units into installer
Daily timer (+10 min after boot) running the retirement, installed
and removed with the other screen-locker units; README section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:01:37 +01:00
b174339979 Add RunnerUp retirement logic
Anchor = PC credit time of an app-authored run (joined on TCX end
time in log.json), due 7 days later, gated on a validated import
marker, then adb backup + uninstall. Typed results, --status/--dry-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:01:17 +01:00
8a26387396 Add run recorder, upload queue, saver
State machine over PositionSource + GpsFilter with pause segments, pending-run WebDAV PUT queue, dufs login import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:00:31 +01:00
b4e69dbff4 Add RunMap, run detail and runs in history
RunMap.route/.live (flutter_map, OSM tiles cached on disk,
collapsed icon-only attribution, one warning when tiles fail),
RunDetailScreen (full-bleed map + numbers, no scrolling), a runs
strip in the history, and day+sport dedupe that hides the PC's
runnerup_verified entry once the phone has the run itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:00:01 +01:00
63caf9dee9 Match RunnerUp TCX: Calories, walk as Other
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 15:41:55 +01:00
c2544c4a9c Add GPS run foundation: TCX codec, DB, deps
Pure-Dart TCX codec pinned to the PC's RunnerUp parser by a shared
golden fixture (Dart byte-compare + pytest through the real verifier),
GPS filters and moving-time maths mirroring the PC walk rule, runs /
run_points tables (schema v9), PositionSource seam over geolocator,
location permissions and foreground service type, map/cache deps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 15:37:41 +01:00
1020421371 Bump crdt_sync to v0.12.0
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 14:28:15 +01:00
c4d2bbcd7d Bump deps: fln 23, gradle 9.9, astro, jsdom 31
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
Pin @emnapi core/runtime to stable 1.11.3: astro's peers
otherwise resolve to 2.0.0-beta.2 and astro check crashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:44:45 +01:00
595c5f41e6 Pin gatelock v0.12.0
Also bump coverage 7.17.2 and ruff 0.17.4 for the freshness gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:31:14 +01:00
856f0c0774 Lift armed lock when carrot lands late
Poll morning_session every 15s (05:00-11:00) while the lock is
up; on a signed skip bank the early-bird marker, record
wake_alarm_skip_late and leave through the normal close().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:11:39 +01:00
0987975bca Fix lint: hold status mirror, split tests
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Has been cancelled
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Has been cancelled
Tests / web-coverage (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tests / flutter-coverage (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:46:47 +01:00
6919ddea28 Close open workout window when a hold starts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:39:47 +01:00
fdf6251847 Bump web deps: astro 7.4.5, vitest 5.1.0
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 }}) (flutter, flutter-analyze, ) (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,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Unblocks the dependency-freshness gate for the push.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:31:51 +01:00
47da4131a8 Stand down workout prompt/lock during test hold
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:29:11 +01:00
531 changed files with 35255 additions and 5871 deletions

2
.fvmrc
View File

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

View File

@ -1,62 +0,0 @@
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

View File

@ -28,9 +28,10 @@ jobs:
- group: flutter - group: flutter
hooks: flutter-analyze hooks: flutter-analyze
skip: "" skip: ""
# dependency-freshness is local only (pre-commit hook), never in CI.
- group: rest - group: rest
hooks: "" hooks: ""
skip: mypy,pylint,flutter-analyze skip: mypy,pylint,flutter-analyze,dependency-freshness
name: pre-commit (${{ matrix.group }}) name: pre-commit (${{ matrix.group }})
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@ -60,7 +61,7 @@ jobs:
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1 - uses: kuhyx/utils/flutter-setup@flutter-setup-v1
if: matrix.group == 'flutter' if: matrix.group == 'flutter'
with: with:
flutter-version: 3.47.9 flutter-version: 3.50.1
working-directory: stronglift_replacement/workout_app working-directory: stronglift_replacement/workout_app
# analyze needs resolved packages (.dart_tool); the hook runs analyze # analyze needs resolved packages (.dart_tool); the hook runs analyze
# only, so fetch deps here first. # only, so fetch deps here first.
@ -83,7 +84,7 @@ jobs:
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
if: matrix.group == 'rest' if: matrix.group == 'rest'
with: with:
node-version: "26.13.0" node-version: "26.13.1"
cache: pnpm cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml cache-dependency-path: web/pnpm-lock.yaml
- name: Install status-UI packages - name: Install status-UI packages
@ -93,12 +94,11 @@ jobs:
# Every hook brings its own environment except the language: system # Every hook brings its own environment except the language: system
# ones, and those all run in `rest`: screens-fit imports screen_locker # ones, and those all run in `rest`: screens-fit imports screen_locker
# (and so its runtime deps) and dependency-freshness needs pyyaml and # (and so its runtime deps). The other groups need pre-commit alone. uv with a cached
# packaging. The other groups need pre-commit alone. uv with a cached
# wheel store replaces a ~27 s pip install. # wheel store replaces a ~27 s pip install.
- name: Install requirements for the system hooks - name: Install requirements for the system hooks
if: matrix.group == 'rest' if: matrix.group == 'rest'
run: uv pip install --system -r requirements.txt pyyaml packaging run: uv pip install --system -r requirements.txt
- name: Install pre-commit - name: Install pre-commit
if: matrix.group != 'rest' if: matrix.group != 'rest'
run: uv pip install --system pre-commit run: uv pip install --system pre-commit

View File

@ -9,7 +9,7 @@ on:
env: env:
# Bucket count for the Flutter suite; the matrix below lists 0..N-1. # Bucket count for the Flutter suite; the matrix below lists 0..N-1.
# 10, not more: the account runs at most 20 jobs at once, and a push also # 10, not more: the account runs at most 20 jobs at once, and a push also
# starts ~10 others (pre-commit, freshness, the rest of this file). At 12 # starts ~10 others (pre-commit, the rest of this file). At 12
# three shards queued for up to 34 s and the workflow took 91 s. # three shards queued for up to 34 s and the workflow took 91 s.
FLUTTER_SHARDS: 10 FLUTTER_SHARDS: 10
@ -99,7 +99,7 @@ jobs:
# cache cost ~38 s to restore even on a hit. # cache cost ~38 s to restore even on a hit.
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1 - uses: kuhyx/utils/flutter-setup@flutter-setup-v1
with: with:
flutter-version: 3.47.9 flutter-version: 3.50.1
working-directory: stronglift_replacement/workout_app working-directory: stronglift_replacement/workout_app
- name: flutter test --coverage, bucket ${{ matrix.shard }} - name: flutter test --coverage, bucket ${{ matrix.shard }}
@ -136,7 +136,7 @@ jobs:
package_json_file: web/package.json package_json_file: web/package.json
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: 26.13.0 node-version: 26.13.1
cache: pnpm cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml cache-dependency-path: web/pnpm-lock.yaml

View File

@ -60,7 +60,7 @@ jobs:
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
flutter-version: 3.47.9 flutter-version: 3.50.1
channel: stable channel: stable
cache: true cache: true

View File

@ -13,9 +13,13 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 rev: v4.6.0
hooks: hooks:
# run_tcx holds byte-exact RunnerUp exports; the golden test compares the
# encoder's output with them, so the fixers must never rewrite them.
- id: trailing-whitespace - id: trailing-whitespace
args: [--markdown-linebreak-ext=md] args: [--markdown-linebreak-ext=md]
exclude: ^screen_locker/tests/fixtures/run_tcx/
- id: end-of-file-fixer - id: end-of-file-fixer
exclude: ^screen_locker/tests/fixtures/run_tcx/
- id: check-yaml - id: check-yaml
# pnpm-lock.yaml is a two-document stream by design. # pnpm-lock.yaml is a two-document stream by design.
exclude: ^web/pnpm-lock\.yaml$ exclude: ^web/pnpm-lock\.yaml$
@ -110,7 +114,7 @@ repos:
# Same release as requirements.txt. No --jobs here: pyproject.toml holds # Same release as requirements.txt. No --jobs here: pyproject.toml holds
# it at 1, because parallel pylint pickles through dill, which crashes on # it at 1, because parallel pylint pickles through dill, which crashes on
# Python 3.15 (see the comment on `jobs` there). # Python 3.15 (see the comment on `jobs` there).
rev: v4.1.3 rev: v4.1.4
hooks: hooks:
# Two hooks, because the three checks below are not defects in a test # Two hooks, because the three checks below are not defects in a test
# suite -- they are how pytest and unit-testing private mixins work -- # suite -- they are how pytest and unit-testing private mixins work --
@ -126,6 +130,7 @@ repos:
# what else happened to be staged alongside. Both are a hard 10.00. # what else happened to be staged alongside. Both are a hard 10.00.
- id: pylint - id: pylint
name: pylint (source, 10.00) name: pylint (source, 10.00)
alias: pylint-source
exclude: ^screen_locker/tests/ exclude: ^screen_locker/tests/
args: args:
- --rcfile=pyproject.toml - --rcfile=pyproject.toml
@ -136,11 +141,12 @@ repos:
# direct URLs for one distribution, so any pin that drifts from # direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather # the manifest becomes an unresolvable hook environment rather
# than merely an old one. # than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.11.0#subdirectory=gatelock - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time - earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays - freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays - sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
# Same pin as workout_app/tools/render_finish_chime.sh installs. # Same pin as workout_app/tools/render_finish_chime.sh installs.
- music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory - music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory
- mcp>=2,<3 - mcp>=2,<3
@ -159,11 +165,12 @@ repos:
# direct URLs for one distribution, so any pin that drifts from # direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather # the manifest becomes an unresolvable hook environment rather
# than merely an old one. # than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.11.0#subdirectory=gatelock - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time - earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays - freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays - sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
- mcp>=2,<3 - mcp>=2,<3
- pydantic - pydantic
@ -185,6 +192,9 @@ repos:
# The CI mirror, one step per hook so each call stays under the 60 s # The CI mirror, one step per hook so each call stays under the 60 s
# action cap. Order matters: ci-venv (re)builds .ci-mirror-venv from # action cap. Order matters: ci-venv (re)builds .ci-mirror-venv from
# requirements.txt when it changed, so ci-pytest only reuses it. # requirements.txt when it changed, so ci-pytest only reuses it.
# `pre-commit run --all-files` is split into four ci-precommit-* steps
# (each well under the cap); together they run every default-stage hook
# exactly once -- see run_precommit_group in scripts/ci_mirror.sh.
- id: ci-venv - id: ci-venv
name: CI mirror (clean requirements.txt venv) name: CI mirror (clean requirements.txt venv)
entry: bash scripts/ci_mirror.sh venv entry: bash scripts/ci_mirror.sh venv
@ -193,9 +203,33 @@ repos:
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-precommit - id: ci-precommit-pylint-source
name: CI mirror (pre-commit --all-files) name: "CI mirror (pre-commit --all-files: pylint source)"
entry: bash scripts/ci_mirror.sh precommit entry: bash scripts/ci_mirror.sh precommit pylint-source
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-pylint-tests
name: "CI mirror (pre-commit --all-files: pylint tests)"
entry: bash scripts/ci_mirror.sh precommit pylint-tests
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-flutter-web
name: "CI mirror (pre-commit --all-files: flutter analyze + web lint/typecheck)"
entry: bash scripts/ci_mirror.sh precommit flutter-web
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-rest
name: "CI mirror (pre-commit --all-files: every other hook)"
entry: bash scripts/ci_mirror.sh precommit rest
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
@ -266,6 +300,13 @@ repos:
files: '^screen_locker/.*\.py$' files: '^screen_locker/.*\.py$'
pass_filenames: false pass_filenames: false
require_serial: true require_serial: true
- id: text-free
name: No locker screen paints a word (textgate)
entry: python3 -m scripts.verify_text_free
language: system
files: '^(screen_locker|scripts)/.*\.py$'
pass_filenames: false
require_serial: true
- id: flutter-analyze - id: flutter-analyze
name: flutter analyze (workout app) name: flutter analyze (workout app)
# env -u GIT_DIR: git exports it to hooks, and flutter shells out to # env -u GIT_DIR: git exports it to hooks, and flutter shells out to
@ -277,7 +318,7 @@ repos:
files: '^stronglift_replacement/workout_app/.*\.(dart|yaml)$' files: '^stronglift_replacement/workout_app/.*\.(dart|yaml)$'
pass_filenames: false pass_filenames: false
- id: flutter-test-coverage-shard-0 - id: flutter-test-coverage-shard-0
name: flutter test bucket 0/4 (workout app, local gate) name: flutter test bucket 0/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 0 entry: bash scripts/check_flutter_coverage.sh --gate-shard 0
language: system language: system
pass_filenames: false pass_filenames: false
@ -285,7 +326,7 @@ repos:
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: flutter-test-coverage-shard-1 - id: flutter-test-coverage-shard-1
name: flutter test bucket 1/4 (workout app, local gate) name: flutter test bucket 1/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 1 entry: bash scripts/check_flutter_coverage.sh --gate-shard 1
language: system language: system
pass_filenames: false pass_filenames: false
@ -293,7 +334,7 @@ repos:
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: flutter-test-coverage-shard-2 - id: flutter-test-coverage-shard-2
name: flutter test bucket 2/4 (workout app, local gate) name: flutter test bucket 2/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 2 entry: bash scripts/check_flutter_coverage.sh --gate-shard 2
language: system language: system
pass_filenames: false pass_filenames: false
@ -301,17 +342,49 @@ repos:
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: flutter-test-coverage-shard-3 - id: flutter-test-coverage-shard-3
name: flutter test bucket 3/4 (workout app, local gate) name: flutter test bucket 3/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 3 entry: bash scripts/check_flutter_coverage.sh --gate-shard 3
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: flutter-test-coverage-shard-4
name: flutter test bucket 4/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 4
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-5
name: flutter test bucket 5/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 5
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-6
name: flutter test bucket 6/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 6
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: flutter-test-coverage-shard-7
name: flutter test bucket 7/8 (workout app, local gate)
entry: bash scripts/check_flutter_coverage.sh --gate-shard 7
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
# Fails unless every shard above passed on THIS tree, then applies the # Fails unless every shard above passed on THIS tree, then applies the
# unchanged 100% bar and every-lib-file guard to their union. # unchanged 100% bar and every-lib-file guard to their union.
- id: flutter-test-coverage-merge - id: flutter-test-coverage-merge
name: flutter coverage 100% (union of the 4 buckets) name: flutter coverage 100% (union of the 8 buckets)
entry: bash scripts/check_flutter_coverage.sh --gate-merge entry: bash scripts/check_flutter_coverage.sh --gate-merge
language: system language: system
pass_filenames: false pass_filenames: false
@ -388,7 +461,8 @@ repos:
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached # Runs WITHOUT --strict on purpose. Offline it degrades to the cached
# answer and passes with a loud banner; `--no-verify` is banned here, so # 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 # a hook that hard-failed on a flaky connection would leave no way to
# commit at all. CI, always online, is the strict authority. # commit at all. The strict run is local only (CI does not check
# freshness): scripts/check_dependency_freshness.sh --all --strict
- id: dependency-freshness - id: dependency-freshness
name: dependencies on newest stable name: dependencies on newest stable
entry: scripts/check_dependency_freshness.sh entry: scripts/check_dependency_freshness.sh

View File

@ -46,8 +46,10 @@ Anything that pushes the hour with a plain read-add-write and is *not* a term
of that derivation gets wiped by the next reset -- that is how a 00:02 workout of that derivation gets wiped by the next reset -- that is how a 00:02 workout
lost its hours on 2026-09-13. A new bonus source is an `Earner` in the lost its hours on 2026-09-13. A new bonus source is an `Earner` in the
registry, never code here: the reset includes it as a term, and the live pass registry, never code here: the reset includes it as a term, and the live pass
(`apply_flat_bonuses_if_new`, stamped `<name>_bonus_date` in (`apply_flat_bonuses_if_new`, stamped `<name>_bonus_minutes` in
`shutdown_base.json`) picks it up for flat earners. That pass runs the moment `shutdown_base.json`; the old `<name>_bonus_date` still means the full bonus)
picks it up for flat earners, paying a signed progress row's share
(`earned_time` 0.24) as it rises and a credit in full. That pass runs the moment
a gate writes its ledger: `earner-bonus.path` (rendered from the registry by a gate writes its ledger: `earner-bonus.path` (rendered from the registry by
`_earner_units`, re-synced by every `--sync-only` pass) starts `_earner_units`, re-synced by every `--sync-only` pass) starts
`earner-bonus.service` (`--apply-bonuses`). The 15-minute `workout-sync` is `earner-bonus.service` (`--apply-bonuses`). The 15-minute `workout-sync` is
@ -67,17 +69,19 @@ re-derives it on every live pass from the ledgers, and a sick-day credit only
raises to it (`_raise_on_sick_day`), never adds -- its row is already in the raises to it (`_raise_on_sick_day`), never adds -- its row is already in the
sum. No lift is saved on a sick day. sum. No lift is saved on a sick day.
## A shutdown never blocks submitting a finished task ## Every credit adds to tonight's shutdown, whenever it lands
A credit timed at or after tonight's shutdown moves tonight to A credit adds its reward to tonight's config even after that shutdown passed:
`min(23:00, the credit's OWN time + its reward)` (`_late_credit.late_tonight`): 18:00, a run ending 19:58 -> 20:00, the book's +1h -> 21:00, exactly what the
only the 23:00 ceiling is hard. The anchor is the credit's own time (the run's daily reset derives (`scripts/preview_shutdown.py` flags any MISMATCH). Unpaid
end via `_workout_ledger.entry_done_at`, the ledger row via gates do not shut the PC down: the evening chain (book, tutor, LeetCode) holds
`_earned.first_credit_time`), never the sync time, so a late upload buys it behind their locks until 23:00, the only hard bound. The late-credit rule
nothing. It is live-only: the next day's reset re-derives from scratch. This (`min(23:00, credit's own time + reward)`, 2026-10-17) is gone since
replaced the first-credit +60 grace floor (gone 2026-10-17); `_grace_floor` 2026-11-18 (kuhy): it turned that evening into 21:58 and 22:58. Trade-off kuhy
keeps only `first_done_at`, `tonight_minutes` and the lift file, which accepted: with no gate pending, a workout ending after its earned shutdown
`plan_absorb` spends once if a stale one is left. buys only the time left before it. `_grace_floor` keeps `first_done_at`,
`tonight_minutes` and the lift file, which `plan_absorb` spends once if a
stale one is left.
Flat earners are read from their gate's ledger by `earned_time.done_today` Flat earners are read from their gate's ledger by `earned_time.done_today`
via `_earned.py`: HMAC-verified `credit` rows matched by the earner's own via `_earned.py`: HMAC-verified `credit` rows matched by the earner's own
@ -122,3 +126,18 @@ wait, and tests pin the retry to 0.
- lint: `pre-commit run ruff --all-files` - lint: `pre-commit run ruff --all-files`
- coverage: `python -m pytest -n auto -p no:sugar -q` - coverage: `python -m pytest -n auto -p no:sugar -q`
- coverage-gaps: `coverage-gaps coverage.lcov` - coverage-gaps: `coverage-gaps coverage.lcov`
- deploy: `git -C ~/src/screen-locker pull --ff-only && bash ~/src/screen-locker/scripts/deploy.sh` (reinstalls, restarts web/poke/runnerup units, health-checks them, then release-deploys the workout app (skipped when its source tree matches the last phone install, `~/.local/state/screen-locker/phone_app_tree`); exit 46 from the phone guard means kuhy reruns it with `PHONE_PROTECT_ALLOW=com.kuhy.workout_app`)
## Pre-push gate (<=60 s)
A stamped tree (full suite green) pushes in ~1 s. An unstamped tree runs
`scripts/push_gate.sh`: pre-commit plus only the tests the change since the
last full-green commit can affect (`scripts/gate_select.py`), 100% line
coverage on the changed dart files, and it prints which tests ran and why.
Pubspec/analysis_options/conftest/pyproject changes, or more than 25 selected
Dart tests, need the full suite: `scripts/full_gate.sh step <id>` once per id
(`full_gate.sh list`; 8 shards, each <60 s) or `full_gate.sh all`. The nightly
`full-gate.timer` (22:00, loadavg guard) runs `full_gate.sh all`; a red result
(`$GIT_DIR/gate-full-status`) refuses every push until a full run is green.
Install the nightly: copy `full-gate.{service,timer}` to `~/.config/systemd/user/`
and `systemctl --user enable --now full-gate.timer` (enabled on kuhy's PC).

View File

@ -17,8 +17,9 @@ pay of everything credited that day, capped at 23:00
raised to it by the next live pass (`_sick_floor`), and every later credit raised to it by the next live pass (`_sick_floor`), and every later credit
that day raises it again. that day raises it again.
A credit landing at or after tonight's shutdown is never lost: tonight A credit landing after tonight's shutdown adds its reward to that shutdown,
becomes `min(23:00, the credit's own time + its reward)` (`_late_credit`). `install.sh` migrates the old like any other (18:00 + 2h = 20:00 even for a run ending at 19:58); unpaid
evening gates hold the PC until 23:00 instead. `install.sh` migrates the old
`sick_history.json` dates into the pool once (`scripts/migrate_sick_history.py`). `sick_history.json` dates into the pool once (`scripts/migrate_sick_history.py`).
A sick day may *keep* lockers (`sickdays add --keep workout`). A kept workout A sick day may *keep* lockers (`sickdays add --keep workout`). A kept workout
@ -48,6 +49,34 @@ so a run finished after 20:00 pushes the hour later without the phone being
plugged in; the per-minute shutdown check then lifts the night lockdown on its plugged in; the per-minute shutdown check then lifts the night lockdown on its
own once the hour is past "now" (digital-wellbeing's check script). own once the hour is past "now" (digital-wellbeing's check script).
Runs and walks are credited by ONE rule, whatever the TCX sport or the
`_Walking` file-name suffix (RunnerUp's files and the workout app's alike): a
day's activities are summed, and the day counts once their distance reaches
3.5 km (5% GPS tolerance) OR their *moving* time reaches the shared duration
bar (30 min minus the hidden leeway). Both are summed over the track cut into
windows of at least 10 s, each judged by its average speed: faster than 25 km/h
(a vehicle or a GPS jump) counts neither time nor distance; moving time needs
0.5 m/s or more (1 m/s across a signal dropout longer than 30 s, so a pause
earns nothing but a run through a dropout keeps its time). Files without
trackpoints earn nothing (the lap totals are never used). The reward is the usual one
workout credit per day (`runnerup_verified:<date>`); the log's `activity`
field is display only. Code: `screen_locker/_walk_tcx.py`.
**Retiring RunnerUp.** A week after the PC first credits a run recorded by the
workout app (TCX author `kuhy workout_app`), `runnerup-retire.timer` (daily, retries
until the phone is attached) backs `/sdcard/Documents/RunnerUp` up to
`~/data/cloud/RunnerUp/runnerup_phone_backup_<date>/` and uninstalls `org.runnerup.free`,
once the app's `.workout_app_import.json` matches `processed/`; no app run, no uninstall.
`python3 -m screen_locker.runnerup_retire --status` / `--dry-run` change nothing.
## Error reports
Every uncaught, thread or Tk callback error, and any freeze of the lock window
over 1 s, goes to the shared app-errors spool through `gatelock.error_report`
(`screen_locker/_errors.py`, installed by the CLI for every mode). The PC's
`app-errors` timer turns each one into a ticket on the todoImplementer board
(kuhyx/utils `DOCS-app-errors.md`). Nothing shows on screen.
## MCP server (Claude Code integration) ## MCP server (Claude Code integration)
screen-locker exposes a **read-only** MCP server (`screen_locker._mcp`) so screen-locker exposes a **read-only** MCP server (`screen_locker._mcp`) so

View File

@ -1,7 +1,7 @@
# Workout poke: phone -> PC wire contract (v1) # Workout poke: phone -> PC wire contract (v1)
The phone sends a finished StrongLifts session straight to the PC over the The phone sends a finished StrongLifts session straight to the PC over the
home LAN, so the credit (shutdown time, gaming budget, notification) lands in home LAN, so the credit (shutdown time, notification) lands in
under a second instead of waiting for the GitHub/Firebase round trip. The under a second instead of waiting for the GitHub/Firebase round trip. The
normal sync push still runs in parallel; the PC dedups by record id, so a normal sync push still runs in parallel; the PC dedups by record id, so a
session that arrives both ways is credited once. session that arrives both ways is credited once.
@ -45,11 +45,13 @@ session that arrives both ways is credited once.
```json ```json
{"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>, {"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>,
"shutdown":"HH:MM"|null,"gaming_budget_minutes":<int|null>,"pc_ms":<int>, "shutdown":"HH:MM"|null,"pc_ms":<int>,
"reason":"<sentence a human can act on>"} "reason":"<sentence a human can act on>"}
``` ```
The phone must treat `shutdown` and `gaming_budget_minutes` as nullable. The phone must treat `shutdown` as nullable. `gaming_budget_minutes` was dropped
when the gaming budget was removed (2026-11-16); a phone ignores it if an older
PC still sends it.
Outcomes of a verified (200) request: Outcomes of a verified (200) request:
@ -64,8 +66,8 @@ Outcomes of a verified (200) request:
Refusals are never 200. Besides the four checks above, the PC may answer Refusals are never 200. Besides the four checks above, the PC may answer
`404` (wrong path), `405` (not POST), `411` (no Content-Length), `413` (body `404` (wrong path), `405` (not POST), `411` (no Content-Length), `413` (body
over 64 KiB) and `500` (internal error; the regular sync still credits). All over 64 KiB) and `500` (internal error; the regular sync still credits). All
of them carry the same JSON shape with `ok:false` and `shutdown` and of them carry the same JSON shape with `ok:false` and `shutdown`
`gaming_budget_minutes` both `null`. The PC answers a `413` without reading `null`. The PC answers a `413` without reading
the body, so the phone may see a connection reset instead of the reply. the body, so the phone may see a connection reset instead of the reply.
## Shared fixture ## Shared fixture

View File

@ -1,464 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Driving the workout app to 100% test coverage</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5a5a5a; --card: #f5f5f7;
--border: #e2e2e6; --accent: #4f46e5; --accent-soft: #ede9fe;
--good: #15803d; --good-bg: #dcfce7; --bad: #b91c1c; --bad-bg: #fee2e2;
--code-bg: #f6f8fa; --add: #e6ffec; --add-fg: #04562a; --del: #ffebe9; --del-fg: #82071e;
--pill: #eef2ff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14151a; --fg: #e6e6ea; --muted: #9aa0aa; --card: #1c1e26;
--border: #2a2d38; --accent: #a5b4fc; --accent-soft: #262347;
--good: #4ade80; --good-bg: #16351f; --bad: #f87171; --bad-bg: #3a1a1a;
--code-bg: #1a1c23; --add: #12321f; --add-fg: #7ee2a8; --del: #3a1a1d; --del-fg: #f0a8ae;
--pill: #23263a;
}
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.65; font-size: 17px;
}
.wrap { max-width: min(48rem, 92vw); margin: 0 auto; padding: 2.5rem 0 5rem; }
h1 { font-size: 2rem; line-height: 1.2; margin: 0 0 .3rem; }
h2 { font-size: 1.5rem; margin: 3rem 0 1rem; padding-top: .4rem; border-top: 1px solid var(--border); }
h3 { font-size: 1.15rem; margin: 1.8rem 0 .6rem; }
p, li { color: var(--fg); }
.sub { color: var(--muted); font-size: 1.02rem; margin: 0 0 1.5rem; }
a { color: var(--accent); }
code { background: var(--code-bg); padding: .1em .35em; border-radius: 5px; font-size: .88em;
font-family: "SF Mono", ui-monospace, Menlo, Consolas, monospace; }
pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 10px;
padding: 1rem; overflow-x: auto; white-space: pre-wrap; word-break: break-word; font-size: .82rem; line-height: 1.55; }
pre code { background: none; padding: 0; font-size: inherit; }
.toc { background: var(--card); border: 1px solid var(--border); border-radius: 12px;
padding: 1rem 1.25rem; margin: 1.5rem 0 0; }
.toc strong { font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
.toc ol { margin: .5rem 0 0; padding-left: 1.2rem; }
.toc a { text-decoration: none; }
.toc a:hover { text-decoration: underline; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 1.25rem; margin: 1.25rem 0; }
.pill { display: inline-block; background: var(--pill); color: var(--accent); font-size: .72rem;
font-weight: 600; padding: .15em .6em; border-radius: 999px; letter-spacing: .03em; }
.add { color: var(--add-fg); background: var(--add); display: block; }
.del { color: var(--del-fg); background: var(--del); display: block; }
.diagram { display: flex; flex-wrap: wrap; gap: .75rem; align-items: stretch; margin: 1.25rem 0; }
.zone { flex: 1 1 220px; border: 2px solid var(--border); border-radius: 12px; padding: 1rem; }
.zone.fake { border-color: var(--bad); }
.zone.real { border-color: var(--good); }
.zone h4 { margin: 0 0 .5rem; font-size: .95rem; }
.zone .tag { font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
.zone.fake .tag { color: var(--bad); }
.zone.real .tag { color: var(--good); }
.box { border: 1px solid var(--border); border-radius: 8px; background: var(--bg); padding: .5rem .7rem; margin: .5rem 0; font-size: .82rem; }
.flowrow { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; margin: .4rem 0; font-size: .85rem; }
.arrow { color: var(--muted); font-weight: 700; }
.k { font-weight: 600; }
table.cov { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: .9rem; }
table.cov th, table.cov td { border: 1px solid var(--border); padding: .5rem .6rem; text-align: left; }
table.cov th { background: var(--card); }
table.cov td.num { text-align: right; font-variant-numeric: tabular-nums; }
.good { color: var(--good); font-weight: 600; }
.bad { color: var(--bad); font-weight: 600; }
/* micro-world */
.sim { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 1.25rem; margin: 1.5rem 0; }
.sim h4 { margin: 0 0 .25rem; }
.sim .controls { display: flex; flex-wrap: wrap; gap: .5rem; margin: .9rem 0; }
.seg { display: inline-flex; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
.seg button { background: var(--bg); color: var(--fg); border: none; padding: .5rem .85rem; font-size: .85rem; cursor: pointer; }
.seg button.on { background: var(--accent); color: #fff; }
.runbtn { background: var(--accent); color: #fff; border: none; border-radius: 10px; padding: .6rem 1.1rem; font-size: .9rem; font-weight: 600; cursor: pointer; }
.runbtn:active { transform: translateY(1px); }
.stage { margin-top: 1rem; border: 1px dashed var(--border); border-radius: 10px; padding: 1rem; background: var(--bg); }
.step { font-size: .85rem; margin: .3rem 0; opacity: .35; transition: opacity .25s; }
.step.active { opacity: 1; }
.verdict { margin-top: .9rem; font-weight: 700; padding: .6rem .8rem; border-radius: 8px; font-size: .95rem; }
.verdict.pass { background: var(--good-bg); color: var(--good); }
.verdict.fail { background: var(--bad-bg); color: var(--bad); }
.verdict.idle { background: var(--code-bg); color: var(--muted); font-weight: 500; }
/* quiz */
.q { border: 1px solid var(--border); border-radius: 12px; padding: 1.1rem 1.25rem; margin: 1.1rem 0; background: var(--card); }
.q .qhead { font-weight: 600; margin-bottom: .75rem; }
.opt { display: block; width: 100%; text-align: left; background: var(--bg); color: var(--fg);
border: 1px solid var(--border); border-radius: 9px; padding: .6rem .8rem; margin: .4rem 0; font-size: .92rem; cursor: pointer; }
.opt:hover { border-color: var(--accent); }
.opt.correct { background: var(--good-bg); border-color: var(--good); color: var(--good); }
.opt.wrong { background: var(--bad-bg); border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.rationale { font-size: .85rem; color: var(--muted); margin-top: .5rem; display: none; }
.rationale.show { display: block; }
.score { position: sticky; bottom: 0; background: var(--accent); color: #fff; border-radius: 10px;
padding: .6rem 1rem; margin-top: 1rem; font-weight: 600; text-align: center; }
.mono { font-family: "SF Mono", ui-monospace, Menlo, Consolas, monospace; font-size: .85em; }
</style>
</head>
<body>
<div class="wrap">
<span class="pill">CHANGE EXPLAINED · 2026-07-13</span>
<h1>Driving the workout app to 100% test coverage</h1>
<p class="sub">How a stuck push gate got unblocked — and the Flutter widget-test techniques that made the hard 267 lines of chart, calendar and live-workout UI testable.</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — the gate that never went green</a></li>
<li><a href="#intuition">Intuition — two clocks, one test</a></li>
<li><a href="#code">Code — what actually changed</a></li>
<li><a href="#quiz">Quiz — check your understanding</a></li>
</ol>
</nav>
<h2 id="background">1 · Background</h2>
<p>The repo contains a Flutter phone app, <code>workout_app</code>, that tracks strength workouts and syncs them to a PC. To keep quality high, the project installs a <em>pre-push gate</em>: whenever a commit touches Dart code, pushing runs two checks locally before the push is allowed to leave your machine.</p>
<div class="card">
<div class="flowrow"><span class="k">git push</span> <span class="arrow">→</span> <span class="box"><b>flutter analyze</b> — zero issues (even <span class="mono">info</span>-level)</span></div>
<div class="flowrow"><span class="k"></span> <span class="arrow">→</span> <span class="box"><b>flutter test --coverage</b> — <b>100%</b> of every <code>lib/</code> line, and every file must appear in the report</span></div>
</div>
<p>That second check is strict in two ways. First, the bar is <strong>100%</strong> — not 90%, not "the lines you changed". Second, a helper script (<code>check_flutter_coverage.sh</code>) also fails if any <code>lib/**/*.dart</code> file is <em>missing</em> from the coverage report, so you can't quietly earn 100% by never importing a file into a test.</p>
<p>The catch: this gate had <strong>never once passed</strong> for a Dart commit. It was added while the app was only ~83% covered, so ten commits — an entire phone-to-PC sync feature — sat finished but <em>unpushable</em>, stuck behind 316 uncovered lines. This change closes that gap and ships all of it.</p>
<h3>Where the 316 lines lived</h3>
<table class="cov">
<thead><tr><th>File</th><th class="num">Before</th><th class="num">After</th><th>Nature of the gap</th></tr></thead>
<tbody>
<tr><td>storage_service.dart</td><td class="num">139/165</td><td class="num good">163/163</td><td>migrations, restore, edge branches</td></tr>
<tr><td>home_screen.dart</td><td class="num">117/121</td><td class="num good">121/121</td><td>post-navigation reloads</td></tr>
<tr><td>settings_screen.dart</td><td class="num">243/262</td><td class="num good">262/262</td><td>device-flow branches, steppers</td></tr>
<tr><td>history_screen.dart</td><td class="num">167/308</td><td class="num good">307/307</td><td>whole exercise drill-down + chart</td></tr>
<tr><td>workout_screen.dart</td><td class="num">144/270</td><td class="num good">269/269</td><td>live-workout breaks &amp; finish</td></tr>
</tbody>
</table>
<p>The two screens at the bottom — the history charts/calendar and the live-workout timer UI — held 267 of the 316 lines and were the genuinely hard part. Testing them ran head-first into a subtlety about <em>how time works inside a Flutter widget test</em>. That's the idea worth understanding, so it gets its own section.</p>
<h2 id="intuition">2 · Intuition — two clocks, one test</h2>
<p>A normal <code>testWidgets</code> test does <strong>not</strong> run on real time. Flutter wraps it in a <em>fake clock</em> (<span class="mono">FakeAsync</span>): timers only advance when you explicitly say <code>tester.pump(someDuration)</code>. This is usually wonderful — you can "wait" 3 minutes for a rest timer in a microsecond, deterministically.</p>
<p>But the app's real database, <span class="mono">sqflite</span>, schedules work on <em>real</em> timers and background isolates. Under the fake clock, those never get a chance to finish. So the moment a tapped widget kicks off a database write, you get a landmine:</p>
<div class="diagram">
<div class="zone fake">
<div class="tag">Fake-async zone (default)</div>
<h4>tap outside <span class="mono">runAsync</span></h4>
<div class="box">tap a set → <span class="mono">_tapCircle</span></div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><span class="mono">unawaited(_saveActiveSession())</span> → sqflite write</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box bad">write parks on a real timer the fake clock never ticks</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><b class="bad">✗ "Pending timers" — test fails</b></div>
</div>
<div class="zone real">
<div class="tag">Real loop via <span class="mono">tester.runAsync</span></div>
<h4>tap inside <span class="mono">runAsync</span></h4>
<div class="box">tap a set → <span class="mono">_tapCircle</span></div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><span class="mono">unawaited(_saveActiveSession())</span> → sqflite write</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box good">real event loop runs the write to completion</div>
<div class="flowrow"><span class="arrow">↓</span></div>
<div class="box"><b class="good">✓ no leftover timers — test passes</b></div>
</div>
</div>
<p>So the rule that unlocked the live-workout screen is: <strong>any tap that triggers a database write or starts a <span class="mono">Timer.periodic</span> must be dispatched inside <code>tester.runAsync(...)</code></strong>, which runs that code on the genuine event loop where the work can actually finish. The assertion afterward happens on the fake clock again, so you still get deterministic <code>expect</code>s.</p>
<p>Two corollaries fell out of this while writing the tests:</p>
<ul>
<li><b>A dialog that awaits, then does DB work, is one flow.</b> When you tap "Finish", a confirm dialog opens; confirming resumes <code>_confirmFinish</code> in the <em>same zone the first tap fired in</em>, and that continuation does six sqflite writes. So the <em>whole</em> finish flow — open dialog, confirm, save — has to live in a single <code>runAsync</code> block, not just the confirm tap.</li>
<li><b><code>tester.longPress</code> fights <code>runAsync</code>.</b> It does its own internal fake-clock pumps to time the press, which don't advance inside <code>runAsync</code>. The fix is a manual gesture: <code>startGesture</code>, hold for a real 700 ms, then release — a real-time long-press.</li>
</ul>
<div class="sim" id="sim">
<h4>▶ Micro-world: run the test yourself</h4>
<p style="font-size:.9rem;color:var(--muted);margin:.2rem 0 0">Pick where the tapped code runs and what it does, then dispatch the tap. Watch whether the background work completes or leaks a pending timer.</p>
<div class="controls">
<div>
<div style="font-size:.75rem;color:var(--muted);margin-bottom:.25rem">Dispatch the tap in…</div>
<div class="seg" id="zoneSeg">
<button data-zone="fake" class="on">fake-async (default)</button>
<button data-zone="real">tester.runAsync</button>
</div>
</div>
<div>
<div style="font-size:.75rem;color:var(--muted);margin-bottom:.25rem">The tapped code…</div>
<div class="seg" id="workSeg">
<button data-work="db" class="on">writes to sqflite</button>
<button data-work="timer">starts a break timer</button>
<button data-work="pure">just calls setState</button>
</div>
</div>
</div>
<button class="runbtn" id="runBtn">Dispatch tap →</button>
<div class="stage" id="stage">
<div class="step" id="s1">1 · gesture dispatched, <span class="mono">onTap</span> fires</div>
<div class="step" id="s2">2 · handler runs…</div>
<div class="step" id="s3">3 · background work scheduled…</div>
<div class="step" id="s4">4 · test tears down, checks for leftover timers…</div>
<div class="verdict idle" id="verdict">Choose options and press “Dispatch tap”.</div>
</div>
</div>
<h3>The other half: reaching the code at all</h3>
<p>Zone discipline makes taps <em>survive</em>, but many lines were uncovered simply because the widget was never <em>built</em>. Flutter's <code>ListView</code> lazily builds only what's near the viewport, so the history screen's session tiles and the "DUMBBELL LUNGE" section label — which sit below an 800×600 test fold — never existed in the tree, and their lines stayed cold. The fix is to <code>scrollUntilVisible</code> / <code>ensureVisible</code> them first: scrolling builds them, which both renders and covers them.</p>
<h3>Honest 100%: what <code>coverage:ignore</code> is for</h3>
<p>A few lines genuinely can't run on a Linux CI host, so they're marked <code>coverage:ignore</code> with a stated reason rather than faked. The bar for an ignore is "no reachable test path exists," not "this was annoying to test":</p>
<div class="diagram">
<div class="box" style="flex:1 1 240px"><b>Android/iOS only</b><br><span style="font-size:.85rem;color:var(--muted)"><code>Vibration.vibrate()</code> — <code>hasVibrator()</code> returns <b>false</b> on Linux (no <code>Platform.isAndroid/isIOS</code>), so the body never runs there.</span></div>
<div class="box" style="flex:1 1 240px"><b>Production-only path</b><br><span style="font-size:.85rem;color:var(--muted)">The real on-device DB path (<code>getDatabasesPath()</code>) — tests always inject an in-memory or temp-file path instead.</span></div>
<div class="box" style="flex:1 1 240px"><b>Truly unreachable</b><br><span style="font-size:.85rem;color:var(--muted)">A defensive <code>null</code>-state branch that seeding makes impossible, and a history <code>_load</code> branch only reachable via a path that never calls <code>_load</code>.</span></div>
</div>
<h2 id="code">3 · Code — what actually changed</h2>
<p>The diff is <strong>792 insertions</strong> across ten files, but it splits cleanly into two buckets: a lot of <em>test</em> code, and a handful of tiny <em>production</em> edits that make code reachable from tests. Grouped by concern:</p>
<h3>A · Test seams in production code</h3>
<p>To test the "server not started" placeholder, a private widget had to become public — private widgets can't be constructed from a test file:</p>
<pre><code><span class="del">-class _ServerAddressTile extends StatelessWidget {
- const _ServerAddressTile({required this.addresses});</span>
<span class="add">+/// ...Public so the empty-address fallback can be exercised in a widget test.
+class ServerAddressTile extends StatelessWidget {
+ const ServerAddressTile({required this.addresses, super.key});</span></code></pre>
<p>And to test the schema migration, <code>resetForTesting</code> gained an optional path so a test can hand it a real <em>file</em> DB (in-memory DBs can't be reopened at a new version, which is exactly what an <code>onUpgrade</code> migration needs):</p>
<pre><code><span class="del">- static void resetForTesting() {
- _testDbPath = ':memory:';</span>
<span class="add">+ static void resetForTesting({String dbPath = ':memory:'}) {
+ _testDbPath = dbPath;</span></code></pre>
<h3>B · Justified coverage ignores</h3>
<p>Four small blocks are marked unreachable-on-CI, each with a comment explaining <em>why</em> — for example the haptics call:</p>
<pre><code> if (await Vibration.hasVibrator()) {
<span class="add">+ // Android/iOS-only: hasVibrator() returns false on the Linux test host
+ // (no Platform.isAndroid/isIOS), so this body never runs there.
+ // coverage:ignore-start</span>
unawaited(Vibration.vibrate(duration: 800));
<span class="add">+ // coverage:ignore-end</span>
}</code></pre>
<h3>C · The tests — real behaviour, on the real loop</h3>
<p>The bulk of the change. A representative live-workout test: a tap starts a rest break, and the tap is dispatched through a helper that keeps it on the real event loop so the sqflite write and periodic timer complete cleanly.</p>
<pre><code>Future&lt;void&gt; _tapReal(WidgetTester tester, Finder f) async {
await tester.runAsync(() async {
await tester.tap(f);
await Future&lt;void&gt;.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
testWidgets('tapping a set starts a break which Skip cancels', (tester) async {
await _pump(tester, _wrap());
await _tapReal(tester, find.byType(RepCircle).first);
expect(find.byType(BreakBanner), findsOneWidget); // break started
await _tapReal(tester, find.text('Skip'));
expect(find.byType(BreakBanner), findsNothing); // Skip cancelled it
});</code></pre>
<p>And the schema-migration unit test that the new <code>dbPath</code> seam unlocked — build a v1 database on disk, open it through <code>StorageService</code> (which runs at v3), and assert the migration ran:</p>
<pre><code>final oldDb = await databaseFactory.openDatabase(dbFile,
options: OpenDatabaseOptions(version: 1, onCreate: /* v1 schema */));
await oldDb.close();
StorageService.resetForTesting(dbPath: dbFile); // real file, not :memory:
await StorageService.init(); // triggers onUpgrade 1 → 3
expect(await _svc.getNextWorkoutType(), 'A'); // settings table now exists
expect((await _svc.getExerciseState(name))!.successThreshold, 3); // column added</code></pre>
<h3>D · Making analyze green</h3>
<p>The gate also requires a spotless <code>flutter analyze</code>, and it exits non-zero on even an <span class="mono">info</span>. The last commit documents the newly-public field, reshapes the ignore comment so it isn't an over-long line, and reflows one pre-existing 81-char comment. Small, but the push doesn't go through without it.</p>
<h2 id="quiz">4 · Quiz</h2>
<p class="sub">Five questions on the reasoning behind the change. Click an answer to reveal whether it's right and why.</p>
<div id="quiz"></div>
<div class="score" id="score">Score: 0 / 0</div>
</div>
<script>
/* ---------- Micro-world ---------- */
(function () {
var zone = 'fake', work = 'db';
var zoneSeg = document.getElementById('zoneSeg');
var workSeg = document.getElementById('workSeg');
zoneSeg.addEventListener('click', function (e) {
if (!e.target.dataset.zone) return;
zone = e.target.dataset.zone;
[].forEach.call(zoneSeg.children, function (b) { b.classList.toggle('on', b.dataset.zone === zone); });
});
workSeg.addEventListener('click', function (e) {
if (!e.target.dataset.work) return;
work = e.target.dataset.work;
[].forEach.call(workSeg.children, function (b) { b.classList.toggle('on', b.dataset.work === work); });
});
var steps = ['s1', 's2', 's3', 's4'].map(function (id) { return document.getElementById(id); });
var verdict = document.getElementById('verdict');
var timers = [];
function clearTimers() { timers.forEach(clearTimeout); timers = []; }
function labelFor() {
if (work === 'db') return 'schedules a sqflite write (a real timer)';
if (work === 'timer') return 'starts a Timer.periodic rest break';
return 'only calls setState — no async work';
}
document.getElementById('runBtn').addEventListener('click', function () {
clearTimers();
steps.forEach(function (s) { s.classList.remove('active'); });
verdict.className = 'verdict idle';
verdict.textContent = 'Running…';
var leaks = (zone === 'fake') && (work === 'db' || work === 'timer');
var texts = [
'1 · gesture dispatched, onTap fires',
'2 · handler runs in the ' + (zone === 'fake' ? 'fake-async zone' : 'real event loop (runAsync)'),
'3 · handler ' + labelFor(),
'4 · teardown checks for leftover timers…'
];
steps.forEach(function (s, i) {
timers.push(setTimeout(function () {
s.classList.add('active');
s.textContent = texts[i];
}, 350 * (i + 1)));
});
timers.push(setTimeout(function () {
if (leaks) {
verdict.className = 'verdict fail';
verdict.textContent = '✗ FAIL — the ' + (work === 'db' ? 'sqflite write' : 'periodic timer') +
' never completed under the fake clock. "Pending timers" at teardown.';
} else if (zone === 'real' && work !== 'pure') {
verdict.className = 'verdict pass';
verdict.textContent = '✓ PASS — on the real loop the ' + (work === 'db' ? 'write' : 'timer') +
' finished (or was cancelled on dispose). No leftover timers.';
} else {
verdict.className = 'verdict pass';
verdict.textContent = '✓ PASS — pure setState schedules no async work, so there is nothing to leak in either zone.';
}
}, 350 * 5));
});
})();
/* ---------- Quiz ---------- */
var QUESTIONS = [
{
q: "A set-tap test run outside runAsync failed with “pending timers.” What caused it?",
options: [
"Its sqflite write and break timer stayed unfinished in the FakeAsync zone",
"The RepCircle sat below the 800×600 test fold so the simulated tap never landed",
"The setUp block forgot the fake secure-storage handler the tap path needs",
"The BreakBanner threw while building because its remaining value was null"
],
correct: 0,
why: "Under the fake clock, the real timers that sqflite (and Timer.periodic) schedule never advance, so they linger and fail teardown."
},
{
q: "Why does dispatching that same tap inside tester.runAsync fix the failure?",
options: [
"runAsync disables the widget's own timers so none of them can leak later",
"It runs that code on the real event loop, where the DB write completes",
"It auto-mocks the vibration and audio platform channels for the test",
"It forces a pumpAndSettle that drains every pending microtask first"
],
correct: 1,
why: "runAsync escapes the fake clock: the write and timer execute on the genuine event loop and actually finish, leaving nothing pending."
},
{
q: "Why was _ServerAddressTile renamed to the public ServerAddressTile?",
options: [
"A second screen needed to embed the identical tile without copying it",
"The analyzer forbids underscore-prefixed StatelessWidgets in screen files",
"A test file can't build a private widget, so its empty case is untested",
"So HttpServerService could write new addresses straight into the tile"
],
correct: 2,
why: "Only its no-address 'Server not started' branch was uncovered, and a test can't construct a library-private widget — so it had to be exposed."
},
{
q: "Why is the Vibration.vibrate call wrapped in coverage:ignore rather than tested?",
options: [
"Vibration is a side effect that unit tests must never trigger on the build host",
"The vibration plugin channel was too slow to mock reliably in the suite",
"The team decided haptics fall outside the 100% coverage requirement",
"hasVibrator() is false on the Linux CI host, so that body never runs there"
],
correct: 3,
why: "hasVibrator() checks Platform.isAndroid/isIOS via device_info_plus; both are false on Linux, so the guarded body is genuinely unreachable in CI."
},
{
q: "Why did resetForTesting gain an optional dbPath parameter?",
options: [
"To speed the suite up by sharing a single database across every test",
"To let production override the DB location from an environment variable",
"So a test can point at a real file DB and drive the v1→v3 migration",
"To stop the in-memory DB from leaking rows between separate test cases"
],
correct: 2,
why: "onUpgrade only runs when a persisted DB is reopened at a higher version; an in-memory DB can't be reopened, so a real file path was needed."
}
];
(function () {
var host = document.getElementById('quiz');
var scoreEl = document.getElementById('score');
var answered = 0, correct = 0;
QUESTIONS.forEach(function (item, qi) {
var card = document.createElement('div');
card.className = 'q';
var head = document.createElement('div');
head.className = 'qhead';
head.textContent = (qi + 1) + '. ' + item.q;
card.appendChild(head);
var done = false;
var buttons = [];
item.options.forEach(function (opt, oi) {
var b = document.createElement('button');
b.className = 'opt';
b.textContent = opt;
b.addEventListener('click', function () {
if (done) return;
done = true;
answered++;
buttons.forEach(function (bb, bi) {
bb.disabled = true;
if (bi === item.correct) bb.classList.add('correct');
});
if (oi === item.correct) { correct++; }
else { b.classList.add('wrong'); }
rat.classList.add('show');
scoreEl.textContent = 'Score: ' + correct + ' / ' + answered;
});
buttons.push(b);
card.appendChild(b);
});
var rat = document.createElement('div');
rat.className = 'rationale';
rat.textContent = '→ ' + item.why;
card.appendChild(rat);
host.appendChild(card);
});
})();
</script>
</body>
</html>

View File

@ -1,686 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multiple workouts per day, the sync that never ran, and a ban on silence</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5b6470; --line: #e2e6ea;
--card: #f6f8fa; --accent: #0b6bcb; --good: #1a7f37; --bad: #b42318;
--warn: #9a6700; --code: #f2f4f7;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14171a; --fg: #e6e9ec; --muted: #9aa4b0; --line: #2b3138;
--card: #1b1f24; --accent: #6cb6ff; --good: #4ac26b; --bad: #ff7b72;
--warn: #d4a72c; --code: #1e2329;
}
}
* { box-sizing: border-box; }
body {
margin: 0 auto; padding: 2rem 1rem 5rem; max-width: min(48rem, 92vw);
background: var(--bg); color: var(--fg); line-height: 1.65;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
h1 { font-size: 1.9rem; line-height: 1.25; margin: 0 0 .4rem; }
h2 { font-size: 1.4rem; margin: 2.6rem 0 .8rem; padding-top: .6rem;
border-top: 1px solid var(--line); }
h3 { font-size: 1.08rem; margin: 1.6rem 0 .5rem; }
.sub { color: var(--muted); margin: 0 0 1.5rem; }
a { color: var(--accent); }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
code { background: var(--code); padding: .12em .35em; border-radius: 4px;
font-size: .88em; }
.codewrap { overflow-x: auto; background: var(--code); border: 1px solid var(--line);
border-radius: 8px; margin: .8rem 0; }
pre { margin: 0; padding: .85rem 1rem; white-space: pre-wrap; overflow-x: auto;
font-size: .84rem; line-height: 1.5; }
.add { color: var(--good); }
.del { color: var(--bad); }
nav.toc { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: .9rem 1.1rem; margin: 1.5rem 0 2rem; }
nav.toc ol { margin: .4rem 0 0; padding-left: 1.2rem; }
nav.toc li { margin: .25rem 0; }
.card { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: 1rem 1.1rem; margin: 1.2rem 0; }
.note { border-left: 3px solid var(--accent); }
.warnbox { border-left: 3px solid var(--warn); }
.badbox { border-left: 3px solid var(--bad); }
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
.tablewrap { overflow-x: auto; margin: 1rem 0; }
th, td { border: 1px solid var(--line); padding: .45rem .6rem; text-align: left; }
th { background: var(--card); }
/* diagram primitives */
.diagram { margin: 1.2rem 0; }
.row { display: flex; gap: .6rem; align-items: stretch; flex-wrap: wrap; }
.box { border: 1px solid var(--line); border-radius: 8px; padding: .55rem .7rem;
background: var(--card); font-size: .84rem; flex: 1 1 0; min-width: 8.5rem; }
.box .t { font-weight: 600; font-size: .78rem; color: var(--muted);
text-transform: uppercase; letter-spacing: .03em; margin-bottom: .3rem; }
.arrow { display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 1.3rem; padding: .2rem 0; }
.pill { display: inline-block; border-radius: 999px; padding: .08em .55em;
font-size: .76rem; border: 1px solid var(--line); }
.pill.v { color: var(--good); border-color: var(--good); }
.pill.m { color: var(--warn); border-color: var(--warn); }
.pill.x { color: var(--bad); border-color: var(--bad); }
/* micro-world */
.sim { border: 1px solid var(--line); border-radius: 10px; padding: 1rem;
background: var(--card); }
.sim .days { display: grid; grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr));
gap: .5rem; margin: .8rem 0; }
.day { border: 1px solid var(--line); border-radius: 8px; padding: .5rem;
background: var(--bg); }
.day h4 { margin: 0 0 .35rem; font-size: .8rem; color: var(--muted); }
.day .slot { font-size: .74rem; margin: .12rem 0; }
.btnrow { display: flex; gap: .3rem; margin-top: .35rem; flex-wrap: wrap; }
button { font: inherit; font-size: .78rem; padding: .2rem .5rem; cursor: pointer;
border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--fg); }
button:hover { border-color: var(--accent); }
.verdict { margin-top: .8rem; padding: .7rem .9rem; border-radius: 8px;
background: var(--bg); border: 1px solid var(--line); font-size: .9rem; }
.big { font-size: 1.5rem; font-weight: 700; }
/* quiz */
.q { margin: 1.4rem 0; }
.q .stem { font-weight: 600; margin-bottom: .5rem; }
.opt { display: block; width: 100%; text-align: left; margin: .3rem 0;
padding: .5rem .7rem; border-radius: 8px; border: 1px solid var(--line);
background: var(--bg); color: var(--fg); cursor: pointer; font-size: .9rem; }
.opt:disabled { cursor: default; }
.opt.correct { border-color: var(--good); background: color-mix(in srgb, var(--good) 12%, var(--bg)); }
.opt.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, var(--bg)); }
.rat { font-size: .85rem; color: var(--muted); margin: .4rem 0 0; display: none; }
.rat.show { display: block; }
#score { font-weight: 600; }
</style>
</head>
<body>
<h1>Multiple workouts per day, the sync that never ran, and a ban on silence</h1>
<p class="sub">
<code>feat/check-phone-runnerup-and-tray</code> · 3 commits · 62 files ·
+2719 / −777 · 2026-07-17
</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what this thing is</a></li>
<li><a href="#intuition">Intuition — one slot per day</a></li>
<li><a href="#code">Code — the change, by concern</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">1. Background — what this thing is</h2>
<p>
<strong>screen-locker</strong> is a discipline tool. A systemd user service runs
<code>python -m screen_locker.screen_lock --production</code> at login and again
from a timer at 08:30/09:05. If you haven't earned your workout, it throws a
fullscreen Tk window over everything until you do. If you have, it calls
<code>sys.exit(0)</code> and you never see it. That's why "the locker isn't
running" is usually the <em>healthy</em> state, not a fault.
</p>
<p>
It decides using <code>screen_locker/log.json</code> — a gitignored,
HMAC-signed file. Each entry is signed with a key shared across screen-locker,
diet_guard and wake_alarm, so the log can't be quietly hand-edited to fake a
workout. Two things read it constantly: <code>has_weekly_minimum()</code>
(fire the lock or not?) and the reward path (how late may the PC stay on
tonight?).
</p>
<p>
A workout gets in three ways. <span class="pill v">phone_verified</span> — a
StrongLifts session pulled off the phone. <span class="pill v">runnerup_verified</span>
— a real run, parsed from the actual TCX file that RunnerUp writes to
<code>/sdcard/Documents/RunnerUp/</code> and pulled over ADB. And
<span class="pill m">manual_workout</span> — a self-reported evidence form
(squash, table tennis), rate-limited by a budget because nothing verifies it.
That distinction — machine-checked versus self-reported — is the hinge the
whole change turns on.
</p>
<p>
There's also a companion Flutter app on the phone, and a shared GitHub repo
(<code>kuhyx/syncs</code>) holding a small CRDT log per device, so the two
machines can agree on what happened.
</p>
<h3>The shape that caused everything</h3>
<p>
<code>log.json</code> was <strong>keyed by date, one entry per day</strong>.
The writer said so in as many words, and did exactly that:
</p>
<div class="codewrap"><pre><span class="muted"># _log_mixin.py — before</span>
"""...The log is day-keyed: one entry per date."""
logs[date] = entry <span class="del"># a second workout that day OVERWRITES the first</span></pre></div>
<p>
So the file physically could not hold two workouts on one day. Everything
downstream inherited that: <code>count_weekly_workouts</code> iterated the date
keys, so "4 workouts a week" and "4 <em>days</em> a week" were the same
sentence. Nobody had to choose between them, because the data model had
already chosen.
</p>
<h2 id="intuition">2. Intuition — one slot per day</h2>
<p>
The trigger was mundane. On Monday 13 July, kuhy played squash <em>and</em> went
for a 9.8&nbsp;km run. He logged the squash by hand. The run — a real, verified,
TCX-backed run — had nowhere to go. The day already had its slot.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">Before — one slot</div>
<div>2026-07-13 →</div>
<div style="margin-top:.3rem"><span class="pill m">squash (manual)</span></div>
<div style="margin-top:.4rem; color:var(--bad); font-size:.8rem">
the 9.8 km run would <strong>overwrite</strong> this
</div>
</div>
<div class="box">
<div class="t">After — a list</div>
<div>2026-07-13 → [</div>
<div style="margin-top:.3rem">
<span class="pill m">squash</span> <span class="pill v">run 9.8 km</span>
</div>
<div>]</div>
<div style="margin-top:.4rem; color:var(--good); font-size:.8rem">
both kept, both counted
</div>
</div>
</div>
</div>
<h3>The trap: a list alone is a cheat code</h3>
<p>
Letting a day hold many workouts sounds harmless until you notice what the
lock is <em>for</em>. If every entry counted, you could type four
<span class="pill m">manual</span> entries on a Monday morning, satisfy "4
workouts this week", and never be locked again until Sunday. The whole tool
would be an honour system with extra steps.
</p>
<p>
So the rule isn't "count workouts". It's <strong>count what can't be
faked</strong>:
</p>
<div class="card note">
<strong>The weekly rule.</strong> Each <span class="pill v">verified</span>
workout counts <em>individually</em> — several in one day all count, because a
TCX file and a StrongLifts session are machine-checked.
<span class="pill m">manual</span> entries count <strong>at most once per
day</strong>, however many you write. Self-reports can't inflate the total.
</div>
<p>
Play with it. Add workouts and watch the count and the lock:
</p>
<div class="sim diagram" id="sim">
<div style="font-size:.85rem; color:var(--muted)">
A week (Mon–Thu shown). Weekly minimum is <strong>4</strong>.
</div>
<div class="days" id="days"></div>
<div class="btnrow">
<button id="reset">Reset</button>
<button id="preset-real">Preset: kuhy's Jul 13</button>
<button id="preset-cheat">Preset: the 4-manual cheat</button>
</div>
<div class="verdict" id="verdict"></div>
</div>
<h3>The second trap: the same workout, twice</h3>
<p>
Once a day can hold many workouts, "is this one already here?" stops being
free. Every entry now carries a <code>workout_id</code> — deliberately the
<em>same string</em> the sync layer uses as its record id, so a workout logged
on the PC and the same workout arriving from the phone collapse to one row
instead of two.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">manual</div>
<code>manual:2026-07-13T14:00</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">date + start time</div>
</div>
<div class="box">
<div class="t">runnerup</div>
<code>runnerup_verified:2026-07-13</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">type + date</div>
</div>
<div class="box">
<div class="t">phone session</div>
<code>startTime.toIso8601String()</code>
<div style="font-size:.78rem;color:var(--muted);margin-top:.3rem">minted by the app</div>
</div>
</div>
</div>
<h3>The sync had never worked. Not once.</h3>
<p>
While fixing the above, a second thing surfaced. The PC was supposed to
publish its workouts so the phone could see them. It never had —
<code>screen-locker-sync/</code> in the repo contained a single
<code>.gitkeep</code>. Two independent reasons:
</p>
<ol>
<li>
<strong>No token.</strong> <code>push_pc_manuals()</code> opened with
<code>if token is None: return</code> — a bare return, no log line. The PAT
had been saved to the wrong app's config directory. The code knew and said
nothing.
</li>
<li>
<strong>A side-store.</strong> It pushed from <code>manual_sync_log.json</code>,
written only at log-time. So anything recorded before that feature existed —
like the squash — could never publish, no matter how many times it ran.
</li>
</ol>
<p>
The fix for (2) also fixes a category error: <em>derive the push from
<code>log.json</code> itself</em>. The log is the truth; the sync is a
projection of it. Then history publishes automatically, forever, with no
second place to fall out of date.
</p>
<h3>Why silence was the real bug</h3>
<p>
Notice the shape of the failure. Not a crash — a <code>return []</code>. During
the debugging session, <code>pull_all_manual_records()</code> returned
<code>0</code> and it was <strong>impossible to tell</strong> whether the repo
was empty or the call had failed, because the token guard was silent and real
errors logged at <code>INFO</code>. The answer only came from bypassing the
function and hitting the API by hand.
</p>
<div class="card badbox">
<strong>An invisible log is a silent failure with extra steps.</strong> That's
now a rule with teeth: <code>scripts/check_silent_failures.py</code>, a
pre-commit hook. Every <code>except</code> must re-raise or log at
<code>warning</code>+. It found <strong>27 violations across 16 modules</strong>
on its first run — and flagged its own source file too.
</div>
<p>
Worth knowing why a custom AST rule was needed at all: ruff already runs with
<code>select = ["ALL"]</code>, so <code>S110</code> (<code>except: pass</code>)
was <em>already</em> enforced — and the codebase had none. The lethal pattern
wasn't <code>pass</code>. It was <code>except: log.info(...); return []</code>,
which <em>looks</em> handled and no ruff rule catches.
</p>
<h2 id="code">3. Code — the change, by concern</h2>
<h3>3.1 One reader, two shapes</h3>
<p>
A new dependency-free module is the single place that reads the file. Old and
new shapes both load, so a half-migrated file — or a rolled-back writer — is
never a crash. Crucially, wrapping a legacy dict in a list leaves the
<em>signed bytes untouched</em>, so every existing HMAC still verifies with
zero re-signing.
</p>
<div class="codewrap"><pre><span class="add">+ # screen_locker/_log_io.py (new)</span>
+ def load_workout_log(log_file) -> dict[str, list[dict]]:
+ normalized = {}
+ for date, value in read_raw_log(log_file).items():
+ if isinstance(value, list):
+ normalized[date] = [e for e in value if isinstance(e, dict)]
+ elif isinstance(value, dict):
+ normalized[date] = [value] # legacy: wrap, don't rewrite
+ return normalized</pre></div>
<h3>3.2 One writer, which appends and dedups</h3>
<p>
The overwrite becomes an append behind a single chokepoint that returns a
result instead of <code>None</code> — so the caller can tell a genuinely new
workout from a duplicate, and scale the reward accordingly.
</p>
<div class="codewrap"><pre><span class="del">- logs[date] = entry # overwrite</span>
<span class="add">+ workout_id = _derive_workout_id(date, workout_data)
+ if workout_id is not None and any(
+ _entry_workout_id(date, e) == workout_id for e in entries
+ ):
+ return RecordResult(appended=False, prior_entries=prior)
+ entries.append(entry)
+ return RecordResult(appended=True, prior_entries=prior)</span></pre></div>
<div class="card warnbox">
<strong>This bit was written twice.</strong> The first version compared
<code>e.get("workout_id")</code> directly. Legacy entries predate that field,
so theirs is <code>None</code> — un-matchable. The moment the PC started
publishing history, the 08:30 timer ingested the squash back and appended a
<em>second</em> copy of it. It had been dismissed in the plan as a "known
minor, accepted" risk; it fired within the hour, on real data.
<code>_entry_workout_id()</code> now <em>derives</em> an existing entry's id
when it has none, so a legacy row matches its own synced twin.
</div>
<h3>3.3 The counting rule</h3>
<p>
The anti-gaming asymmetry from section 2, in the one function that both the
lock and the banked bonus consult:
</p>
<div class="codewrap"><pre>for date_str, entries in load_workout_log(log_file).items():
...
has_manual = False
for entry in entries:
wtype = entry.get("workout_data", {}).get("type", "")
if wtype in VERIFIED_WORKOUT_TYPES:
count += 1 <span class="add"># each verified workout counts</span>
elif wtype == MANUAL_WORKOUT_TYPE:
has_manual = True
if has_manual:
count += 1 <span class="add"># all of a day's manuals count as one</span></pre></div>
<h3>3.4 The reward, with two guards</h3>
<p>
<code>_apply_workout_credit</code> now scales to the day: the first counted
workout earns the base <strong>+2h</strong>; an <em>additional same-day
verified</em> one earns <strong>+1h</strong>; an additional manual earns
nothing. The old "+1h when <code>weekly_count &gt; 4</code>" gate was removed —
weekly volume is the banked bonus's job, and paying for it twice was the bug
hiding in plain sight. The credit fires only if the write actually appended
(<em>id guard</em>) and the entry is dated today (<em>date guard</em>) — so a
back-dated backfill raises the count but never pushes tonight's shutdown.
</p>
<p>
The tests caught a real defect here: the unlock screen still labelled the +1h
<code>#{weekly_count - 4}</code>, which under the new rule can render
<em>negative</em>.
</p>
<h3>3.5 The sync, derived from the log</h3>
<p>
Record id = the workout's own <code>workout_id</code>. HLC = derived from the
entry's own timestamp — which makes a re-push <em>byte-identical</em>, so the
repo never churns. That determinism is what lets the push run on every startup
without turning the sync repo into a commit firehose.
</p>
<div class="codewrap"><pre><span class="add">+ hlc = Hlc.new_tick(_PC_DEVICE_ID, wall_time_ms=_entry_wall_ms(entry, date))
+ log[record_id] = Record(id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)})</span></pre></div>
<p>
And nothing about it is silent any more:
</p>
<div class="codewrap"><pre><span class="add">+ @dataclass(frozen=True)
+ class PushResult:
+ pushed: bool
+ record_count: int
+ reason: str # always a sentence a human can act on</span></pre></div>
<h3>3.6 Two recoveries, one pattern</h3>
<p>
The phone kept a Keystore token and mirrored it to
<code>/sdcard</code> — but <code>load()</code> only consulted the mirror when
the Keystore was <strong>empty</strong>, never when its token was
present-but-<em>rejected</em>. A stale entry could shadow a good backup forever
while the UI insisted all was well. Now a 401 triggers one retry from the
mirror before anyone is asked to re-authorize.
</p>
<p>
The same pattern then closed a sharper hole. <code>active_session</code> — which
set you're on, and the reps done — lived only in app-private SQLite. A
<code>pm clear</code> wiped it <em>mid-workout</em>, and <code>backup.json</code>
didn't help because it mirrors only <em>completed</em> history. The state had to
be re-entered by hand. The persistence granularity was already right (it saves
on every set tap); only the <em>location</em> was wrong.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">app-private (wiped)</div>
SQLite <code>active_session</code><br>
Keystore <code>sync.token</code>
</div>
<div class="arrow">→</div>
<div class="box">
<div class="t">/sdcard (survives)</div>
<code>active_session.json</code><br>
<code>sync_token</code><br>
<code>backup.json</code>
</div>
</div>
<p style="font-size:.82rem;color:var(--muted);margin:.5rem 0 0">
On launch, an empty table re-seeds itself from the mirror. Set 4 of the
Romanian Deadlift, reps <code>[8,8,8,8]</code>, survives an uninstall.
</p>
</div>
<h3>3.7 The rule that outlives the fix</h3>
<div class="codewrap"><pre><span class="add">+ # scripts/check_silent_failures.py — pre-commit hook `no-silent-failures`
+ def _handler_is_loud(handler) -> bool:
+ """True if the handler re-raises or logs loudly about the failure."""
+ return any(
+ isinstance(node, ast.Raise) or _is_loud_log_call(node)
+ for node in ast.walk(handler)
+ )</span></pre></div>
<p>
There's deliberately no escape hatch, because <code>noqa</code> is banned
repo-wide. Two ironies for the record: the checker's own docstring contained
the literal string <code>#&nbsp;noqa</code> and tripped the noqa-blocker, and
<code>_log_io.py</code> — written for this very change — violated the new rule.
Both were invisible while untracked, since <code>git ls-files</code> hides
untracked files from the hooks, and only surfaced once committed.
</p>
<h2 id="quiz">4. Quiz</h2>
<p style="color:var(--muted);font-size:.9rem">
Five questions on the reasoning. Score: <span id="score">0 / 0</span>
</p>
<div id="quiz"></div>
<script>
/* ---------------- micro-world: the weekly counting rule ---------------- */
(function () {
const DAYS = ["Mon 13", "Tue 14", "Wed 15", "Thu 16"];
const MIN = 4;
let state = DAYS.map(() => ({ verified: 0, manual: 0 }));
const daysEl = document.getElementById("days");
const verdictEl = document.getElementById("verdict");
function count() {
// Mirrors count_weekly_workouts: each verified counts; manuals cap at 1/day.
return state.reduce((n, d) => n + d.verified + (d.manual > 0 ? 1 : 0), 0);
}
function render() {
daysEl.innerHTML = "";
state.forEach((d, i) => {
const el = document.createElement("div");
el.className = "day";
const contrib = d.verified + (d.manual > 0 ? 1 : 0);
el.innerHTML =
"<h4>" + DAYS[i] + "</h4>" +
'<div class="slot"><span class="pill v">verified</span> ' + d.verified + "</div>" +
'<div class="slot"><span class="pill m">manual</span> ' + d.manual +
(d.manual > 1 ? ' <span style="color:var(--warn)">(capped)</span>' : "") + "</div>" +
'<div class="slot" style="margin-top:.3rem;color:var(--muted)">counts: <strong>' +
contrib + "</strong></div>";
const row = document.createElement("div");
row.className = "btnrow";
const bv = document.createElement("button");
bv.textContent = "+ verified";
bv.onclick = () => { state[i].verified++; render(); };
const bm = document.createElement("button");
bm.textContent = "+ manual";
bm.onclick = () => { state[i].manual++; render(); };
row.append(bv, bm);
el.append(row);
daysEl.append(el);
});
const n = count();
const locked = n < MIN;
verdictEl.innerHTML =
'<div>weekly count: <span class="big">' + n + "</span> / " + MIN + "</div>" +
'<div style="margin-top:.4rem">lock this week: ' +
(locked
? '<span class="pill x">FIRES</span>'
: '<span class="pill v">skipped — minimum met</span>') +
"</div>" +
'<div style="margin-top:.4rem;font-size:.84rem;color:var(--muted)">' +
"Each verified workout adds 1. All of a day's manual entries add 1 between them." +
"</div>";
}
document.getElementById("reset").onclick = () => {
state = DAYS.map(() => ({ verified: 0, manual: 0 })); render();
};
document.getElementById("preset-real").onclick = () => {
// Jul 13: squash (manual) + the 9.8 km run (verified) => that day counts 2.
state = DAYS.map(() => ({ verified: 0, manual: 0 }));
state[0] = { verified: 1, manual: 1 };
render();
};
document.getElementById("preset-cheat").onclick = () => {
// Four self-reports on one morning: the whole point of the cap.
state = DAYS.map(() => ({ verified: 0, manual: 0 }));
state[0] = { verified: 0, manual: 4 };
render();
};
render();
})();
/* ---------------- quiz ---------------- */
(function () {
const QS = [
{
stem: "The log moved from {date: entry} to {date: [entry]}. Why does load_workout_log wrap legacy dict values on read instead of rewriting the file up front?",
opts: [
"A rewrite needs the HMAC key, which is not always available at read time.",
"Wrapping leaves each entry's signed bytes untouched, so old HMACs verify.",
"The file is gitignored, so a rewrite would be lost on the next checkout.",
"SQLite locks the file during reads, so an in-place rewrite may corrupt it."
],
correct: 1,
rat: "Wrapping never changes the bytes compute_entry_hmac signed, so zero re-signing is needed."
},
{
stem: "A single day holds 2 verified workouts and 3 manual ones. What does that day contribute to the weekly count?",
opts: [
"5 — every counted workout counts on its own, as multi/day implies.",
"2 — only machine-verified workouts count toward the weekly total.",
"3 — each verified counts; the manual entries count once in total.",
"1 — the day contributes exactly one, matching the old day-based rule."
],
correct: 2,
rat: "Verified workouts stack (2); all of a day's manual entries collapse to a single 1."
},
{
stem: "Why is each pushed record's HLC derived from the entry's own timestamp rather than the current clock?",
opts: [
"It stops the phone's clock from overriding the PC on same-day workouts.",
"GitHub rejects records whose clock is newer than the commit timestamp.",
"Re-pushing an unchanged log yields identical records, so no churn.",
"crdt_sync requires a wall_time_ms whenever a node id is also supplied."
],
correct: 2,
rat: "Determinism makes the push idempotent, so running it on every startup never spams the repo."
},
{
stem: "The new hook flags silent except handlers. Why did `if token is None: return []` still need fixing by hand?",
opts: [
"It is a guard clause, not an except handler, so the AST rule never sees it.",
"The rule ignores functions whose return type is a list rather than a result.",
"The checker skips files that were untracked when the hook last ran on them.",
"ruff's S110 already covers it, so the custom checker deliberately skips it."
],
correct: 0,
rat: "The checker walks ast.ExceptHandler nodes; a bare guard return is invisible to it."
},
{
stem: "After the PC began publishing history, the Jul 13 squash appeared twice. What went wrong?",
opts: [
"The push minted a fresh workout_id each run, so the dedup never matched.",
"The legacy entry stored no workout_id, so the id comparison found no match.",
"The 08:30 timer ran ingest twice and the second run raced the first write.",
"The manual-sync ingest skipped its record-id check for pre-migration rows."
],
correct: 1,
rat: "Its stored id was None, so it could not match its own synced copy — the id is now derived."
}
];
const quizEl = document.getElementById("quiz");
const scoreEl = document.getElementById("score");
let answered = 0, right = 0;
QS.forEach((q, qi) => {
const wrap = document.createElement("div");
wrap.className = "q";
const stem = document.createElement("div");
stem.className = "stem";
stem.textContent = (qi + 1) + ". " + q.stem;
wrap.append(stem);
const rat = document.createElement("p");
rat.className = "rat";
q.opts.forEach((text, oi) => {
const b = document.createElement("button");
b.className = "opt";
b.textContent = text;
b.onclick = () => {
if (wrap.dataset.done) return;
wrap.dataset.done = "1";
answered++;
if (oi === q.correct) right++;
wrap.querySelectorAll(".opt").forEach((o, i) => {
o.disabled = true;
if (i === q.correct) o.classList.add("correct");
else if (i === oi) o.classList.add("wrong");
});
rat.textContent = (oi === q.correct ? "Correct. " : "Not quite. ") + q.rat;
rat.classList.add("show");
scoreEl.textContent = right + " / " + answered;
};
wrap.append(b);
});
wrap.append(rat);
quizEl.append(wrap);
});
})();
</script>
</body>
</html>

View File

@ -1,686 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Check Phone learns to look backward, and forgives shaky GPS</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1a1a; --muted: #5b6470; --line: #e2e6ea;
--card: #f6f8fa; --accent: #0b6bcb; --good: #1a7f37; --bad: #b42318;
--warn: #9a6700; --code: #f2f4f7;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14171a; --fg: #e6e9ec; --muted: #9aa4b0; --line: #2b3138;
--card: #1b1f24; --accent: #6cb6ff; --good: #4ac26b; --bad: #ff7b72;
--warn: #d4a72c; --code: #1e2329;
}
}
* { box-sizing: border-box; }
body {
margin: 0 auto; padding: 2rem 1rem 5rem; max-width: min(48rem, 92vw);
background: var(--bg); color: var(--fg); line-height: 1.65;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
h1 { font-size: 1.9rem; line-height: 1.25; margin: 0 0 .4rem; }
h2 { font-size: 1.4rem; margin: 2.6rem 0 .8rem; padding-top: .6rem;
border-top: 1px solid var(--line); }
h3 { font-size: 1.08rem; margin: 1.6rem 0 .5rem; }
.sub { color: var(--muted); margin: 0 0 1.5rem; }
a { color: var(--accent); }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
code { background: var(--code); padding: .12em .35em; border-radius: 4px;
font-size: .88em; }
.codewrap { overflow-x: auto; background: var(--code); border: 1px solid var(--line);
border-radius: 8px; margin: .8rem 0; }
pre { margin: 0; padding: .85rem 1rem; white-space: pre-wrap; overflow-x: auto;
font-size: .84rem; line-height: 1.5; }
.add { color: var(--good); }
.del { color: var(--bad); }
nav.toc { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: .9rem 1.1rem; margin: 1.5rem 0 2rem; }
nav.toc ol { margin: .4rem 0 0; padding-left: 1.2rem; }
nav.toc li { margin: .25rem 0; }
.card { background: var(--card); border: 1px solid var(--line);
border-radius: 10px; padding: 1rem 1.1rem; margin: 1.2rem 0; }
.note { border-left: 3px solid var(--accent); }
.warnbox { border-left: 3px solid var(--warn); }
.badbox { border-left: 3px solid var(--bad); }
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
.tablewrap { overflow-x: auto; margin: 1rem 0; }
th, td { border: 1px solid var(--line); padding: .45rem .6rem; text-align: left; }
th { background: var(--card); }
/* diagram primitives */
.diagram { margin: 1.2rem 0; }
.row { display: flex; gap: .6rem; align-items: stretch; flex-wrap: wrap; }
.box { border: 1px solid var(--line); border-radius: 8px; padding: .55rem .7rem;
background: var(--card); font-size: .84rem; flex: 1 1 0; min-width: 8.5rem; }
.box .t { font-weight: 600; font-size: .78rem; color: var(--muted);
text-transform: uppercase; letter-spacing: .03em; margin-bottom: .3rem; }
.arrow { display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 1.3rem; padding: .2rem 0; }
.down { text-align: center; color: var(--muted); font-size: 1.2rem; margin: .1rem 0; }
.pill { display: inline-block; border-radius: 999px; padding: .08em .55em;
font-size: .76rem; border: 1px solid var(--line); }
.pill.v { color: var(--good); border-color: var(--good); }
.pill.m { color: var(--warn); border-color: var(--warn); }
.pill.x { color: var(--bad); border-color: var(--bad); }
/* micro-world */
.sim { border: 1px solid var(--line); border-radius: 10px; padding: 1rem;
background: var(--card); }
.sim label { display: block; font-size: .84rem; margin: .7rem 0 .25rem; }
.sim .grp { border: 1px solid var(--line); border-radius: 8px; padding: .6rem .7rem;
background: var(--bg); margin: .6rem 0; }
.sim select, .sim input[type=range] { width: 100%; }
.rangeval { font-size: .8rem; color: var(--muted); }
.btnrow { display: flex; gap: .3rem; margin-top: .5rem; flex-wrap: wrap; }
button { font: inherit; font-size: .82rem; padding: .3rem .6rem; cursor: pointer;
border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--fg); }
button:hover { border-color: var(--accent); }
button.primary { border-color: var(--accent); color: var(--accent); font-weight: 600; }
.trace { margin-top: .8rem; padding: .7rem .9rem; border-radius: 8px;
background: var(--bg); border: 1px solid var(--line); font-size: .85rem; }
.trace .step { padding: .35rem 0; border-bottom: 1px dashed var(--line); }
.trace .step:last-child { border-bottom: none; }
.trace .step .k { color: var(--muted); font-size: .78rem; }
.verdict-line { margin-top: .5rem; font-weight: 600; }
/* quiz */
.q { margin: 1.4rem 0; }
.q .stem { font-weight: 600; margin-bottom: .5rem; }
.opt { display: block; width: 100%; text-align: left; margin: .3rem 0;
padding: .5rem .7rem; border-radius: 8px; border: 1px solid var(--line);
background: var(--bg); color: var(--fg); cursor: pointer; font-size: .9rem; }
.opt:disabled { cursor: default; }
.opt.correct { border-color: var(--good); background: color-mix(in srgb, var(--good) 12%, var(--bg)); }
.opt.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, var(--bg)); }
.rat { font-size: .85rem; color: var(--muted); margin: .4rem 0 0; display: none; }
.rat.show { display: block; }
#score { font-weight: 600; }
</style>
</head>
<body>
<h1>Check Phone learns to look backward, and forgives shaky GPS</h1>
<p class="sub">
<code>c277325</code> · 12 files · +583 / −78 · 2026-07-18
</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what Check Phone actually checks</a></li>
<li><a href="#intuition">Intuition — a same-day blind spot, and a shaky GPS trace</a></li>
<li><a href="#code">Code — the change, by concern</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">1. Background — what Check Phone actually checks</h2>
<p>
<strong>screen-locker</strong> locks the screen until a weekly workout
quota is met. The status window has a voluntary "Check Phone" button
(<code>screen_locker/_status_view_verify.py</code>,
<code>PhoneCheckMixin</code>) that, on click, pulls real data off your
Android phone over ADB and — if it verifies — logs it and applies the
reward. It never trusts a typed claim; it always pulls the actual file
first. Two sources feed it:
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">StrongLifts</div>
Pulls <code>workout_result.json</code> off the phone.
<code>_verify_phone_workout</code> in
<code>_phone_verification.py</code>.
</div>
<div class="box">
<div class="t">RunnerUp</div>
Pulls the real <code>.tcx</code> file from
<code>/sdcard/Documents/RunnerUp/</code>.
<code>_verify_runnerup_workout</code> in
<code>_runnerup_verification.py</code>.
</div>
</div>
</div>
<p>
Both of those functions were written to answer one specific question:
<em>did you work out today?</em> They match on today's date only —
StrongLifts by comparing the JSON's <code>date</code> field, RunnerUp by
grepping filenames for today's date string. That's the right question for
the locked screen, which decides whether to unlock <em>right now</em>. But
the voluntary "Check Phone" button reused those same today-only functions,
even though what it's really trying to answer is broader: <em>is this
week's quota met?</em>
</p>
<p>
The quota itself, from <code>_weekly_check.py</code>, follows an
anti-gaming rule established in the previous change to this repo: each
<span class="pill v">verified</span> workout (StrongLifts or RunnerUp)
counts individually, however many happen on one day, because they're
machine-checked and can't be faked. A <span class="pill m">manual</span>
self-report counts at most once per day. The weekly minimum is 4.
</p>
<p>
A week-aware scanner for RunnerUp already existed —
<code>_scan_and_fill_week_runnerup</code> walks every day from Monday to
today, and for each one still ADB-pulls and validates the real TCX file
before writing anything. It was wired into the automatic login check and
the <code>--status</code> CLI, but never into the "Check Phone" button.
Nothing equivalent existed for StrongLifts at all.
</p>
<h2 id="intuition">2. Intuition — a same-day blind spot, and a shaky GPS trace</h2>
<p>
Here's what actually happened. Wednesday's status window connected to the
phone and clicked Check Phone. The phone had a real RunnerUp run from
<strong>yesterday</strong> — a 4.9&nbsp;km run recorded the evening before,
after the button's earlier check that day had already failed. The result:
</p>
<div class="card badbox">
<code>Phone check (not_verified): StrongLifts: Workout JSON is from
2026-07-17, not today · RunnerUp: No RunnerUp activity found for today</code>
</div>
<p>
Both messages are literally true and both are useless. There <em>is</em> a
real, verifiable run — the button just never looked at any date but today.
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">Before</div>
StrongLifts today? no →<br>
RunnerUp today? no →<br>
<span style="color:var(--bad)">give up</span>
</div>
<div class="box">
<div class="t">After</div>
StrongLifts today? no →<br>
RunnerUp today? no →<br>
<span style="color:var(--good)">scan Mon…today for anything unlogged</span>
</div>
</div>
</div>
<p>
The week-scan fallback reuses the existing RunnerUp scanner and a new,
symmetric StrongLifts one — both still pull and validate the real file via
ADB, they just stop requiring the date to be <em>today</em> and instead
accept anything from Monday through today that isn't logged yet.
</p>
<h3>The second problem the first one uncovered</h3>
<p>
Testing this against the real phone surfaced a second issue: that 4.9&nbsp;km
run should count, but <code>MIN_RUN_DISTANCE_KM</code> is 5.0. GPS traces
measure distance by summing straight-line hops between sampled points, so
tight turns, tree cover, and urban canyons make the recorded distance
consistently <em>shorter</em> than the run actually was. A real 5&nbsp;km run can
legitimately log as 4.9. So a 5% tolerance was added — applied to distance
only, since duration comes from the device clock and has no such noise:
</p>
<div class="diagram">
<div class="row">
<div class="box">
<div class="t">recorded</div>
<span style="font-size:1.3rem;font-weight:700">4.90&nbsp;km</span>
</div>
<div class="arrow">×1.05 →</div>
<div class="box">
<div class="t">tolerant distance</div>
<span style="font-size:1.3rem;font-weight:700">5.145&nbsp;km</span>
</div>
<div class="arrow">≥ 5.0 →</div>
<div class="box" style="border-color:var(--good)">
<div class="t">verified</div>
<span class="pill v">counts</span>
</div>
</div>
</div>
<p>
Play with the whole chain below — it mirrors
<code>_verify_phone_then_runnerup</code>'s real order: StrongLifts today,
then RunnerUp today, then the week-scan fallback, using the same 5%
distance rule at every RunnerUp step.
</p>
<div class="sim diagram" id="sim">
<div class="grp">
<label><input type="checkbox" id="sl-today"> StrongLifts JSON dated <strong>today</strong></label>
</div>
<div class="grp">
<label><input type="checkbox" id="ru-today"> RunnerUp TCX dated <strong>today</strong></label>
<label for="ru-today-km">distance (km) <span class="rangeval" id="ru-today-km-val">4.9</span></label>
<input type="range" id="ru-today-km" min="3" max="6" step="0.1" value="4.9">
</div>
<div class="grp">
<label><input type="checkbox" id="week-gap" checked> Unlogged workout earlier this week</label>
<label for="week-type">source</label>
<select id="week-type">
<option value="runnerup">RunnerUp run</option>
<option value="stronglifts">StrongLifts session</option>
</select>
<div id="week-km-wrap">
<label for="week-km">distance (km) <span class="rangeval" id="week-km-val">4.9</span></label>
<input type="range" id="week-km" min="3" max="6" step="0.1" value="4.9">
</div>
</div>
<div class="btnrow">
<button class="primary" id="run-check">Click "Check Phone"</button>
<button id="reset-sim">Reset</button>
</div>
<div class="trace" id="trace"></div>
</div>
<h2 id="code">3. Code — the change, by concern</h2>
<h3>3.1 Splitting the date-check out of StrongLifts validation</h3>
<p>
<code>_validate_json_data</code> used to do two jobs at once: check the
date, then check the exercises/duration/succeeded content. The week-scan
needs the second job without the first, so it was split:
</p>
<div class="codewrap"><pre><span class="add">+ def _validate_json_content(self, data: dict) -> tuple[str, str]:
+ """...no date check..."""
+ if not data.get("exercises"):
+ return "no_exercises", "No exercises found in the workout JSON"
+ ...
def _validate_json_data(self, data: dict) -> tuple[str, str]:
<span class="del">- today = time.strftime("%Y-%m-%d")</span>
<span class="del">- if data.get("date") != today: return "stale", ...</span>
<span class="del">- if not data.get("exercises"): ...</span>
<span class="add">+ today = time.strftime("%Y-%m-%d")
+ if data.get("date") != today:
+ return "stale", f"Workout JSON is from {data.get('date')}, not today"
+ return self._validate_json_content(data)</span></pre></div>
<p>
<code>_validate_json_data</code> — the live, today-only check used by the
locked screen's unlock chain — keeps behaving exactly as before. It's now
just a thin date gate in front of the shared content check.
</p>
<h3>3.2 A week-scan backfill for StrongLifts (new — nothing existed before)</h3>
<p>
RunnerUp's <code>_scan_and_fill_week_runnerup</code> can find multiple
unlogged days because RunnerUp writes one <code>.tcx</code> file per
activity. StrongLifts only has <em>one</em> <code>workout_result.json</code>
snapshot on the phone at a time, so its equivalent can only ever backfill
one day per call — that's not a limitation of the fix, it's what the data
actually allows:
</p>
<div class="codewrap"><pre><span class="add">+ def _try_fill_stronglifts_for_week(self, log_file: Path) -> int:
+ if not self._has_adb_device():
+ return 0
+ data = self._pull_workout_app_json()
+ date_str = data.get("date") if data else None
+ if not date_str:
+ return 0
+ today = datetime.now(tz=timezone.utc).astimezone().date()
+ week_start = today - timedelta(days=today.weekday())
+ entry_date = date.fromisoformat(date_str) # ValueError -> 0, logged
+ if not week_start <= entry_date <= today:
+ return 0
+ status, msg = self._validate_json_content(data) # no date gate
+ if status != "verified":
+ return 0
+ ...
+ if write_signed_entry(log_file, date_str, workout_data).appended:
+ return 1
+ return 0</span></pre></div>
<p>
<code>write_signed_entry</code> dedups by <code>workout_id</code> (here
<code>"phone_verified:{date}"</code>), so re-scanning an already-filled day
is a safe no-op — calling this twice in a row correctly returns
<code>1</code> then <code>0</code>.
</p>
<h3>3.3 Wiring both week-scans into the button</h3>
<p>
The old return type was a bare 4-tuple, which had no room for "nothing
verified today, but something got backfilled." A small frozen dataclass
replaces it, and a new helper runs both scanners and applies whatever
bonus is earned — reusing the exact prev/new-count math the login
auto-check and <code>--status</code> already use, specifically <em>not</em>
routing through <code>_apply_workout_credit</code>, which always files
under <em>today</em> by design and would mis-date a backfilled entry:
</p>
<div class="codewrap"><pre><span class="add">+ @dataclass(frozen=True)
+ class PhoneCheckOutcome:
+ credited_type: str | None
+ status: str
+ phone_message: str
+ runnerup_message: str | None
+ week_fill_message: str | None = None
+ def _backfill_week_and_apply_bonus(verifier) -> str | None:
+ prev_count = count_weekly_workouts(verifier.log_file)
+ filled = verifier._scan_and_fill_week_runnerup(verifier.log_file)
+ filled += verifier._try_fill_stronglifts_for_week(verifier.log_file)
+ if not filled:
+ return None
+ new_count = count_weekly_workouts(verifier.log_file)
+ bonus = max(0, new_count - max(WEEKLY_WORKOUT_MINIMUM, prev_count))
+ if bonus > 0:
+ verifier._adjust_shutdown_time_by(bonus)
+ return f"Auto-filled {filled} workout(s) from earlier this week." + (
+ f" +{bonus}h shutdown time." if bonus > 0 else ""
+ )</span></pre></div>
<p>
<code>_verify_phone_then_runnerup</code> calls this only after both
today-checks fail, and <code>_on_phone_check_result</code> branches on it:
a verified-today result still goes through <code>_apply_workout_credit</code>
as before; a <code>week_fill_message</code> is shown as-is, because the
backfill step already wrote the entry and applied its own bonus — running
credit again there would double it.
</p>
<h3>3.4 The RunnerUp GPS tolerance</h3>
<div class="codewrap"><pre> distance_km = data["distance_m"] / 1000
<span class="add">+ if distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) < MIN_RUN_DISTANCE_KM:</span>
<span class="del">- if distance_km < MIN_RUN_DISTANCE_KM:</span>
msg = f"Run was {distance_km:.1f} km — need {MIN_RUN_DISTANCE_KM:.0f}+ km"
return "too_short", msg
<span class="add">+ if distance_km < MIN_RUN_DISTANCE_KM:
+ _logger.info("...within %.0f%% GPS tolerance — accepted.", ...)</span></pre></div>
<p>
<code>RUNNERUP_DISTANCE_TOLERANCE = 0.05</code> lives in
<code>_constants.py</code> next to the minimum it adjusts. The log line on
a tolerance-assisted pass exists so a below-threshold-but-accepted run is
still visible in the logs, never a silent pass — the entry itself still
stores the true, un-inflated distance.
</p>
<div class="note" style="border-left:4px solid #b58900;padding:0.75rem 1rem;margin:1.5rem 0;background:#fdf6e3">
<strong>Superseded 2026-08-14.</strong> The numbers on this page describe the
rule as it stood on 2026-07-18 and are kept for that history. The thresholds
and their <em>shape</em> have both since changed: duration and distance were
an <strong>AND</strong> here (30+ min <em>and</em> 5.0+ km); they are now an
<strong>OR</strong> — a run qualifies at
<code>MIN_RUN_DISTANCE_KM = 3.5</code> (inclusive, still with the 5% GPS
tolerance described above) <em>or</em> at
<code>MIN_RUN_DURATION_MINUTES = 40</code> (strict, no tolerance). The
30-minute floor every run had to clear is gone, so a fast 5&nbsp;km now
passes too. The interactive demo and quiz below still use the old 5.0&nbsp;km
AND-rule.
</div>
<h3>3.5 The CLI bug this surfaced (unrelated file, same root cause)</h3>
<p>
Verifying the fix against the real phone produced a week with two
workouts on one day for the first time. That's when
<code>_status.py</code>'s <code>--status</code> CLI printed
<em>"Need 2 more to reach the minimum (4)"</em> for a week that was
actually 4/4 — the GUI, which uses <code>count_weekly_workouts</code>
directly, showed the correct number.
</p>
<div class="codewrap"><pre><span class="del">- before_count = 0
- for i in range(7):
- ...
- if _print_day_line(d, ...):
- before_count += 1 # capped at 1 per day, regardless of
- # how many workouts that day held</span>
<span class="add">+ for i in range(7):
+ ...
+ _print_day_line(d, ...) # display only now
+ before_count = count_weekly_workouts(log_file) # the real anti-gaming count</span></pre></div>
<p>
<code>before_count</code> had been derived from <code>_print_day_line</code>'s
boolean return — one checkmark per day, regardless of how many workouts
that day held. It happened to agree with the real count for years, because
until this change no day ever legitimately held two <em>verified</em>
entries. The fix makes the CLI compute the same weekly total the GUI
already used, so the two views can no longer disagree.
</p>
<h2 id="quiz">4. Quiz</h2>
<p style="color:var(--muted);font-size:.9rem">
Five questions on the reasoning. Score: <span id="score">0 / 0</span>
</p>
<div id="quiz"></div>
<script>
/* ---------------- micro-world: the Check Phone chain ---------------- */
(function () {
const TOLERANCE = 0.05;
const MIN_KM = 5.0;
const slToday = document.getElementById("sl-today");
const ruToday = document.getElementById("ru-today");
const ruTodayKm = document.getElementById("ru-today-km");
const ruTodayKmVal = document.getElementById("ru-today-km-val");
const weekGap = document.getElementById("week-gap");
const weekType = document.getElementById("week-type");
const weekKmWrap = document.getElementById("week-km-wrap");
const weekKm = document.getElementById("week-km");
const weekKmVal = document.getElementById("week-km-val");
const traceEl = document.getElementById("trace");
function passesDistance(km) {
return km * (1 + TOLERANCE) >= MIN_KM;
}
function syncLabels() {
ruTodayKmVal.textContent = parseFloat(ruTodayKm.value).toFixed(1);
weekKmVal.textContent = parseFloat(weekKm.value).toFixed(1);
weekKmWrap.style.display = weekType.value === "runnerup" ? "block" : "none";
}
[ruTodayKm, weekKm, weekType].forEach((el) => el.addEventListener("input", syncLabels));
syncLabels();
function step(label, detail, ok) {
return '<div class="step"><span class="k">' + label + "</span> — " + detail +
(ok === true ? ' <span class="pill v">pass</span>' :
ok === false ? ' <span class="pill x">fail</span>' : "") + "</div>";
}
function run() {
let html = "";
// 1. StrongLifts today
if (slToday.checked) {
html += step("1. StrongLifts today", "JSON dated today, content valid", true);
finish(html, "phone_verified", "Credited today: StrongLifts verified.");
return;
}
html += step("1. StrongLifts today", "no JSON dated today", false);
// 2. RunnerUp today
if (ruToday.checked) {
const km = parseFloat(ruTodayKm.value);
const tol = (km * (1 + TOLERANCE)).toFixed(2);
const ok = passesDistance(km);
html += step(
"2. RunnerUp today",
km.toFixed(1) + " km × 1.05 = " + tol + " km " + (ok ? "≥" : "<") + " 5.0 km",
ok
);
if (ok) {
finish(html, "runnerup_verified", "Credited today: RunnerUp verified.");
return;
}
} else {
html += step("2. RunnerUp today", "no TCX dated today", false);
}
// 3. Week-scan fallback
if (weekGap.checked) {
if (weekType.value === "stronglifts") {
html += step("3. Week-scan (StrongLifts)", "unlogged day, content valid", true);
finish(html, "week_fill", "Auto-filled 1 workout from earlier this week.");
return;
}
const km = parseFloat(weekKm.value);
const tol = (km * (1 + TOLERANCE)).toFixed(2);
const ok = passesDistance(km);
html += step(
"3. Week-scan (RunnerUp)",
km.toFixed(1) + " km × 1.05 = " + tol + " km " + (ok ? "≥" : "<") + " 5.0 km",
ok
);
if (ok) {
finish(html, "week_fill", "Auto-filled 1 workout from earlier this week.");
return;
}
} else {
html += step("3. Week-scan", "nothing unlogged this week", false);
}
finish(html, "none",
"StrongLifts: Workout JSON is from earlier, not today · " +
"RunnerUp: No RunnerUp activity found for today");
}
function finish(html, kind, message) {
const cls = kind === "none" ? "x" : "v";
html += '<div class="verdict-line">Result: <span class="pill ' + cls + '">' +
message + "</span></div>";
traceEl.innerHTML = html;
}
document.getElementById("run-check").onclick = run;
document.getElementById("reset-sim").onclick = () => {
slToday.checked = false;
ruToday.checked = false;
ruTodayKm.value = 4.9;
weekGap.checked = true;
weekType.value = "runnerup";
weekKm.value = 4.9;
syncLabels();
traceEl.innerHTML = "";
};
})();
/* ---------------- quiz ---------------- */
(function () {
const QS = [
{
stem: "A 4.9 km run is logged today, and no StrongLifts JSON exists for today. What does Check Phone report?",
opts: [
"runnerup_verified — 4.9 km times 1.05 clears the 5.0 km line.",
"not_verified — a 4.9 km run stays under the 5.0 km minimum.",
"phone_verified — RunnerUp falls back to the StrongLifts checker.",
"week_fill — today's date always routes to the week-scan path."
],
correct: 0,
rat: "The 5% tolerance is applied before comparing to MIN_RUN_DISTANCE_KM, so today's own RunnerUp check already passes it — the week-scan fallback is never reached."
},
{
stem: "Why does _try_fill_stronglifts_for_week return at most 1, while _scan_and_fill_week_runnerup can return more?",
opts: [
"StrongLifts entries are capped at one credit per week by policy.",
"The phone holds one snapshot; RunnerUp writes one file per run.",
"Only RunnerUp results carry a date, so StrongLifts can't span days.",
"ADB restricts a single pull command to one remote file at a time."
],
correct: 1,
rat: "RunnerUp writes a dated .tcx per activity, so several unlogged days can each supply one; StrongLifts only ever has the single latest snapshot to pull."
},
{
stem: "Why does the week-scan backfill skip _apply_workout_credit and call _adjust_shutdown_time_by directly instead?",
opts: [
"_apply_workout_credit needs a live Tk window a worker thread lacks.",
"_apply_workout_credit always files the entry under today's own date.",
"_adjust_shutdown_time_by is the only method the bare verifier exposes.",
"Skipping it avoids clearing the sick-day debt on a backfilled entry."
],
correct: 1,
rat: "Its own docstring says so: it 'always files under today' as the intra-day reward path, which would mis-date a backfilled entry from an earlier day."
},
{
stem: "Before this change, why did _status.py's CLI summary agree with the GUI for years despite using a different formula?",
opts: [
"Both formulas give identical totals for any log file's contents.",
"The CLI recomputed its total from count_weekly_workouts either way.",
"No day had ever held two verified entries until this very change.",
"The CLI only ran weekly, before a second same-day workout could occur."
],
correct: 2,
rat: "A checkmark-per-day count and a per-workout count only diverge once some day holds more than one verified entry — which this very change made possible for the first time."
},
{
stem: "In the Check Phone chain, in what order are the three checks tried?",
opts: [
"RunnerUp today, then StrongLifts today, then the week-scan fallback.",
"The week-scan fallback first, then StrongLifts today, then RunnerUp today.",
"StrongLifts today, then RunnerUp today, then the week-scan fallback.",
"All three run together, and the first one to finish wins the credit."
],
correct: 2,
rat: "_verify_phone_then_runnerup checks StrongLifts first, falls back to RunnerUp, and only reaches the week-scan when neither today-check verifies."
}
];
const quizEl = document.getElementById("quiz");
const scoreEl = document.getElementById("score");
let answered = 0, right = 0;
QS.forEach((q, qi) => {
const wrap = document.createElement("div");
wrap.className = "q";
const stem = document.createElement("div");
stem.className = "stem";
stem.textContent = (qi + 1) + ". " + q.stem;
wrap.append(stem);
const rat = document.createElement("p");
rat.className = "rat";
q.opts.forEach((text, oi) => {
const b = document.createElement("button");
b.className = "opt";
b.textContent = text;
b.onclick = () => {
if (wrap.dataset.done) return;
wrap.dataset.done = "1";
answered++;
if (oi === q.correct) right++;
wrap.querySelectorAll(".opt").forEach((o, i) => {
o.disabled = true;
if (i === q.correct) o.classList.add("correct");
else if (i === oi) o.classList.add("wrong");
});
rat.textContent = (oi === q.correct ? "Correct. " : "Not quite. ") + q.rat;
rat.classList.add("show");
scoreEl.textContent = right + " / " + answered;
};
wrap.append(b);
});
wrap.append(rat);
quizEl.append(wrap);
});
})();
</script>
</body>
</html>

View File

@ -1,51 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>screen-locker — change explanations</title>
<style>
:root{--bg:#fbfbfd;--fg:#1a1a1f;--muted:#5b5b6b;--card:#fff;--line:#e4e4ec;
--accent:#6b4fd6;--accent-soft:#efeaff;--shadow:0 1px 3px rgba(0,0,0,.08),0 8px 24px rgba(0,0,0,.05);}
@media (prefers-color-scheme:dark){:root{--bg:#131318;--fg:#e9e9f0;--muted:#a2a2b4;--card:#1c1c24;
--line:#2c2c38;--accent:#a78bfa;--accent-soft:#241f38;--shadow:0 1px 3px rgba(0,0,0,.4),0 10px 30px rgba(0,0,0,.35);}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);
font:16px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
.wrap{width:min(48rem,92vw);margin:0 auto;padding:2.6rem 0 5rem}
.kicker{color:var(--accent);font-weight:700;font-size:.8rem;letter-spacing:.08em;text-transform:uppercase}
h1{font-size:1.7rem;margin:.35rem 0 .3rem}
.lead{color:var(--muted);margin:0 0 1.6rem}
.grid{display:flex;flex-direction:column;gap:.7rem}
a.card{display:flex;flex-direction:column;gap:.2rem;text-decoration:none;color:var(--fg);
background:var(--card);border:1px solid var(--line);border-radius:12px;padding:.9rem 1.1rem;box-shadow:var(--shadow)}
a.card:hover{border-color:var(--accent);background:var(--accent-soft)}
.date{font-size:.75rem;color:var(--muted);font-variant-numeric:tabular-nums;letter-spacing:.03em}
.title{font-size:1.05rem;font-weight:600;line-height:1.35}
.empty{color:var(--muted)}
footer{margin-top:2.4rem;padding-top:1.1rem;border-top:1px solid var(--line);color:var(--muted);font-size:.83rem}
</style>
</head>
<body>
<div class="wrap">
<div class="kicker">screen-locker</div>
<h1>Change explanations</h1>
<p class="lead">3 explanations · interactive walkthroughs of notable changes, newest first.</p>
<div class="grid">
<a class="card" href="2026-07-18-explanation-check-phone-week-aware.html">
<span class="date">2026-07-18</span>
<span class="title">Check Phone learns to look backward, and forgives shaky GPS</span>
</a>
<a class="card" href="2026-07-17-explanation-multi-workout-day-and-sync.html">
<span class="date">2026-07-17</span>
<span class="title">Multiple workouts per day, the sync that never ran, and a ban on silence</span>
</a>
<a class="card" href="2026-07-13-explanation-flutter-coverage-to-100.html">
<span class="date">2026-07-13</span>
<span class="title">Driving the workout app to 100% test coverage</span>
</a>
</div>
<footer>Generated by the <code>explain-diff</code> skill. Open any card to replay its walkthrough.</footer>
</div>
</body>
</html>

14
full-gate.service Normal file
View File

@ -0,0 +1,14 @@
[Unit]
Description=screen-locker full test suite (writes the green/red full stamp that gates pushes)
[Service]
Type=oneshot
# %h = kuhy's home. nightly_full_gate.sh skips under load and on a dirty tree.
ExecStart=/bin/bash %h/src/screen-locker/scripts/nightly_full_gate.sh
# Each hook step is <60 s on its own; the whole run gets its own generous cap.
TimeoutStartSec=45min
Nice=19
IOSchedulingClass=idle
CPUQuota=20%
MemoryMax=4G
Environment=FLUTTER_TEST_CONCURRENCY=2

14
full-gate.timer Normal file
View File

@ -0,0 +1,14 @@
[Unit]
Description=Nightly screen-locker full suite at 22:00
# No After=graphical-session.target: it would close an ordering cycle with
# timers.target and systemd would delete this timer's job (see
# early-bird-workout-check.timer, 2026-08-04).
[Timer]
OnCalendar=*-*-* 22:00:00
# Persistent stamps on elapse, not on success; a night skipped by the load
# guard is simply skipped. The PC is off from 23:00, so no catch-up is wanted.
Persistent=false
[Install]
WantedBy=timers.target

View File

@ -17,6 +17,8 @@ BONUS_SERVICE_NAME="earner-bonus.service"
BONUS_PATH_NAME="earner-bonus.path" BONUS_PATH_NAME="earner-bonus.path"
RUNNERUP_WATCH_NAME="runnerup-watch.service" RUNNERUP_WATCH_NAME="runnerup-watch.service"
WORKOUT_POKE_NAME="workout-poke.service" WORKOUT_POKE_NAME="workout-poke.service"
RETIRE_SERVICE_NAME="runnerup-retire.service"
RETIRE_TIMER_NAME="runnerup-retire.timer"
# Runtime dependencies. screen_lock.py imports tkinter at module scope. On Arch # Runtime dependencies. screen_lock.py imports tkinter at module scope. On Arch
# the tkinter MODULE ships inside the `python` package, but the shared library # the tkinter MODULE ships inside the `python` package, but the shared library
@ -73,7 +75,10 @@ ensure_runtime_deps() {
_pip_runtime_dep gatelock \ _pip_runtime_dep gatelock \
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.10.0#subdirectory=gatelock" "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.10.0#subdirectory=gatelock"
_pip_runtime_dep crdt_sync \ _pip_runtime_dep crdt_sync \
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync" "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync"
# The shared credit logo every lock surface shows (_credit.py).
_pip_runtime_dep kuhy_credit \
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit"
} }
ensure_runtime_deps ensure_runtime_deps
@ -147,6 +152,12 @@ cp "$SCRIPT_DIR/$RUNNERUP_WATCH_NAME" "$USER_SERVICE_DIR/$RUNNERUP_WATCH_NAME"
bash "$SCRIPT_DIR/scripts/workout_poke_keygen.sh" bash "$SCRIPT_DIR/scripts/workout_poke_keygen.sh"
cp "$SCRIPT_DIR/$WORKOUT_POKE_NAME" "$USER_SERVICE_DIR/$WORKOUT_POKE_NAME" cp "$SCRIPT_DIR/$WORKOUT_POKE_NAME" "$USER_SERVICE_DIR/$WORKOUT_POKE_NAME"
# The RunnerUp retirement: a week after the workout app's first credited run
# it backs the old app's exports up and uninstalls it from the phone. A daily
# timer, because the phone is not always attached; a no-op until then.
cp "$SCRIPT_DIR/$RETIRE_SERVICE_NAME" "$USER_SERVICE_DIR/$RETIRE_SERVICE_NAME"
cp "$SCRIPT_DIR/$RETIRE_TIMER_NAME" "$USER_SERVICE_DIR/$RETIRE_TIMER_NAME"
# Update paths in the service file to use absolute paths # Update paths in the service file to use absolute paths
REPO_ROOT="$SCRIPT_DIR" REPO_ROOT="$SCRIPT_DIR"
sed -i "s|WorkingDirectory=.*|WorkingDirectory=$REPO_ROOT|" "$USER_SERVICE_DIR/$SERVICE_NAME" sed -i "s|WorkingDirectory=.*|WorkingDirectory=$REPO_ROOT|" "$USER_SERVICE_DIR/$SERVICE_NAME"
@ -159,25 +170,17 @@ systemctl --user daemon-reload
# Enable the service to start on login (one-shot, no periodic timer) # Enable the service to start on login (one-shot, no periodic timer)
systemctl --user enable "$SERVICE_NAME" systemctl --user enable "$SERVICE_NAME"
# Enable the early bird re-check timer # Timers: early bird re-check, periodic re-check, workout sync, the instant
systemctl --user enable --now "$EARLY_BIRD_TIMER_NAME" # bonus pass on ledger writes, and the daily RunnerUp retirement retry
systemctl --user enable --now "$EARLY_BIRD_TIMER_NAME" "$LOCKER_TIMER_NAME" \
"$SYNC_TIMER_NAME" "$BONUS_PATH_NAME" "$RETIRE_TIMER_NAME"
# Enable the periodic re-check timer # Instant RunnerUp credit on upload, and the LAN workout poke listener
systemctl --user enable --now "$LOCKER_TIMER_NAME" # (restart picks up new code)
for unit in "$RUNNERUP_WATCH_NAME" "$WORKOUT_POKE_NAME"; do
# Enable the periodic workout sync systemctl --user enable "$unit"
systemctl --user enable --now "$SYNC_TIMER_NAME" systemctl --user restart "$unit"
done
# Enable the instant bonus pass on ledger writes
systemctl --user enable --now "$BONUS_PATH_NAME"
# Enable the instant RunnerUp credit on upload (restart picks up a new script)
systemctl --user enable "$RUNNERUP_WATCH_NAME"
systemctl --user restart "$RUNNERUP_WATCH_NAME"
# Enable the LAN workout poke listener (restart picks up new code)
systemctl --user enable "$WORKOUT_POKE_NAME"
systemctl --user restart "$WORKOUT_POKE_NAME"
# Verify enforcement is actually armed. enable can silently no-op when systemd # Verify enforcement is actually armed. enable can silently no-op when systemd
# breaks an ordering cycle by deleting the timer's job -- exactly what happened # breaks an ordering cycle by deleting the timer's job -- exactly what happened

View File

@ -7,11 +7,13 @@ requires-python = ">=3.14"
# crdt-sync: shared CRDT merge scheme + sync transports, also used by # crdt-sync: shared CRDT merge scheme + sync transports, also used by
# diet_guard; here for phone-workout sync, Firebase RTDB only since 2026-10-09 # diet_guard; here for phone-workout sync, Firebase RTDB only since 2026-10-09
dependencies = [ dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.11.0#subdirectory=gatelock", "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync", "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time", "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.4.0#subdirectory=sickdays", "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
] ]
[project.scripts] [project.scripts]
@ -265,6 +267,9 @@ addopts = [
# repo's 400-line-per-file cap) -- see its own docstring. # repo's 400-line-per-file cap) -- see its own docstring.
"-p", "-p",
"screen_locker.tests.test_sync_fixtures", "screen_locker.tests.test_sync_fixtures",
# A `-k` run is a subset: only whole-suite runs need fail_under = 100.
"-p",
"screen_locker.tests._subset_coverage",
] ]
filterwarnings = [ filterwarnings = [
"error", "error",

View File

@ -17,6 +17,8 @@ UNITS=(
"earner-bonus.service" "earner-bonus.service"
"runnerup-watch.service" "runnerup-watch.service"
"workout-poke.service" "workout-poke.service"
"runnerup-retire.timer"
"runnerup-retire.service"
) )
for unit in "${UNITS[@]}"; do for unit in "${UNITS[@]}"; do

View File

@ -2,26 +2,28 @@
# Runtime: tkinter/subprocess/socket/sqlite3 (stdlib) plus gatelock (below). # Runtime: tkinter/subprocess/socket/sqlite3 (stdlib) plus gatelock (below).
bandit==1.9.4 bandit==1.9.4
codespell==2.4.3 codespell==2.4.3
coverage==7.17.0 coverage==7.17.4
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.11.0#subdirectory=gatelock gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
mcp==2.3.0 mcp==2.3.0
mypy==2.4.1 mypy==2.4.1
pre-commit==4.7.0 pre-commit==4.7.0
pylint==4.1.3 pylint==4.1.4
pytest==9.2.0 pytest==9.2.0
pytest-cov==7.1.0 pytest-cov==7.1.0
pytest-randomly==5.0.0 pytest-randomly==5.1.0
pytest-sugar==1.1.1 pytest-sugar==1.1.1
pytest-xdist==3.8.0 pytest-xdist==3.8.0
# Direct dependency since the Firebase session recovery exchanges a refresh # Direct dependency since the Firebase session recovery exchanges a refresh
# token over the REST endpoint; crdt-sync already pulls requests in, but this # token over the REST endpoint; crdt-sync already pulls requests in, but this
# module imports it itself, so it is declared rather than assumed. # module imports it itself, so it is declared rather than assumed.
requests==2.34.2 requests==2.34.2
ruff==0.17.3 ruff==0.17.6
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.4.0#subdirectory=sickdays sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
types-requests==2.33.0.20261030 types-requests==2.33.0.20261030
# Direct dependency since the Firebase session stream (_session_stream) catches # Direct dependency since the Firebase session stream (_session_stream) catches
# urllib3's own errors on the long-lived SSE read; requests pulls it in, but # urllib3's own errors on the long-lived SSE read; requests pulls it in, but

15
runnerup-retire.service Normal file
View File

@ -0,0 +1,15 @@
[Unit]
Description=Back up and uninstall the stock RunnerUp app a week after the workout app's first credited run
[Service]
Type=oneshot
# screen_locker is pip-installed (editable), like workout-sync.service, so no
# WorkingDirectory/PYTHONPATH. Headless: no DISPLAY, no Tk, no lock screen.
#
# Exit 0 for "not due yet", "no app run credited yet" and "phone not attached"
# (the timer retries), non-zero when a human is needed: invalid import marker,
# adb missing, a failed backup or a refused uninstall. That shows up in
# `systemctl --user --failed`. Every skip says why in the journal:
# journalctl --user -u runnerup-retire
# State and the anchor: python3 -m screen_locker.runnerup_retire --status
ExecStart=/usr/bin/python3 -m screen_locker.runnerup_retire

18
runnerup-retire.timer Normal file
View File

@ -0,0 +1,18 @@
[Unit]
Description=Retry the RunnerUp retirement daily until the phone has been cleaned up
# No After=graphical-session.target: timers.target is ordered before it, and
# that After= closes a cycle systemd resolves by deleting this timer's job
# (see early-bird-workout-check.timer for the 2026-08-04 incident).
[Timer]
# The phone is not always on USB, so a failed or skipped pass is simply tried
# again: shortly after boot and once a day. Most passes are an instant no-op
# (not due yet, or already done), so the timer stays installed.
OnBootSec=10min
OnCalendar=*-*-* 19:00:00
# Persistent=true: a PC that was off at 19:00 still gets that day's pass.
Persistent=true
[Install]
WantedBy=timers.target

View File

@ -0,0 +1,140 @@
"""A day's activities summed under the one crediting rule (see ``_walk_tcx``).
The day counts as the workout once EITHER its summed distance reaches
``MIN_RUN_DISTANCE_KM`` (within the GPS tolerance) OR its summed moving time
reaches the shared duration bar. The sport only labels messages.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from screen_locker._constants import (
MIN_RUN_DISTANCE_KM,
MIN_WORKOUT_DURATION_MINUTES,
RUNNERUP_DISTANCE_TOLERANCE,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
if TYPE_CHECKING:
from collections.abc import Iterable
# RunnerUp's sport codes, for labels only (the label never decides credit).
SPORT_NAMES: dict[int, str] = {
0: "Running",
1: "Biking",
2: "Other",
3: "Orienteering",
4: "Walking",
5: "Treadmill",
6: "Gym",
7: "Stationary Bike",
}
def distance_qualifies(distance_km: float) -> bool:
"""Whether a distance meets the minimum, with the GPS tolerance."""
return distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
def moving_qualifies(moving_minutes: float) -> bool:
"""Whether moving time meets the shared duration bar (leeway included)."""
return moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
def _distance_metres(activity: dict[str, Any]) -> float:
"""Credited metres; the root-DB path has no trackpoints, so its total stands in."""
return float(activity.get("track_distance_m", activity.get("distance_m", 0.0)))
def _moving_seconds(activity: dict[str, Any]) -> float:
"""Moving seconds; the root-DB path has no trackpoints, so wall-clock stands in."""
return float(activity.get("moving_seconds", activity.get("duration_seconds", 0.0)))
@dataclass(frozen=True)
class ActivityDay:
"""A day's activities, summed.
Attributes:
legs: Distinct activities (deduplicated by the activity's ``Id``: the
WebDAV copy and the phone's copy are the same activity).
moving_minutes: Their summed moving time.
distance_km: Their summed distance.
completed_at: Unix time the activity that took the day over the bar
ended -- when the workout was actually done -- or ``None`` if the
day never got there (or the activity recorded no end).
all_walks: Whether every activity was a walk (label only).
sport: The sport code when the day is a single non-walk activity.
metres: The summed distance in metres, unrounded (feeds the signed
progress row; ``distance_km`` is the same figure over 1000).
moving_seconds: The summed moving seconds, likewise.
"""
legs: int
moving_minutes: float
distance_km: float
completed_at: float | None
all_walks: bool = False
sport: int = -1
metres: float = 0.0
moving_seconds: float = 0.0
@property
def qualifies(self) -> bool:
"""Whether the day counts as its workout: distance OR moving time."""
return distance_qualifies(self.distance_km) or moving_qualifies(
self.moving_minutes
)
def message(self) -> str:
"""The verification line, in the RunnerUp verifier's own style."""
if self.all_walks:
return (
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
if self.legs == 1:
name = SPORT_NAMES.get(self.sport, str(self.sport))
return f"{name}: {self.distance_km:.1f} km in {self.moving_minutes:.0f} min"
return (
f"Activity: {self.legs} activities, {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
def activity_shortfall(day: ActivityDay) -> str:
"""Why a day's activity did not count yet."""
return (
f"{day.message()} -- need {MIN_RUN_DISTANCE_KM:g}+ km or "
f"{MIN_WORKOUT_DURATION_MINUTES}+ min moving"
)
def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay:
"""Sum parsed exports (``parse_tcx_file`` dicts) into one :class:`ActivityDay`."""
unique: dict[str, dict[str, Any]] = {}
for activity in activities:
unique.setdefault(str(activity.get("activity_id") or id(activity)), activity)
ordered = sorted(unique.values(), key=lambda a: a.get("ended_at") or 0.0)
moving = 0.0
metres = 0.0
completed_at: float | None = None
for activity in ordered:
moving += _moving_seconds(activity)
metres += _distance_metres(activity)
if completed_at is None and (
moving_qualifies(moving / 60) or distance_qualifies(metres / 1000)
):
completed_at = activity.get("ended_at")
return ActivityDay(
legs=len(ordered),
moving_minutes=moving / 60,
distance_km=metres / 1000,
completed_at=completed_at,
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
metres=metres,
moving_seconds=moving,
)

View File

@ -24,7 +24,8 @@ import sys
from screen_locker._decision_log import LockDecision, record_decision from screen_locker._decision_log import LockDecision, record_decision
from screen_locker._decision_reasons import reasons_extra from screen_locker._decision_reasons import reasons_extra
from screen_locker._morning_session import has_workout_skip_today from screen_locker._hold import workout_hold_active
from screen_locker._morning_session import MorningSkip, has_workout_skip_today
from screen_locker._night_lockdown import has_evening_lockdown_today from screen_locker._night_lockdown import has_evening_lockdown_today
from screen_locker._sick import stands_down_workout from screen_locker._sick import stands_down_workout
from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day
@ -73,6 +74,7 @@ class _ReasonsMixin:
"relaxed_day": is_relaxed_day, "relaxed_day": is_relaxed_day,
"weekly_minimum_met": lambda: has_weekly_minimum(self.log_file), "weekly_minimum_met": lambda: has_weekly_minimum(self.log_file),
"evening_lockdown_today": has_evening_lockdown_today, "evening_lockdown_today": has_evening_lockdown_today,
"test_hold_active": workout_hold_active,
}, },
) )
@ -151,6 +153,34 @@ class AutoUpgradeMixin(_ReasonsMixin):
return False return False
return True return True
def _stand_down_for_carrot(self, skip: MorningSkip) -> None:
"""Take an armed lock down because the carrot landed after it armed.
Does what the ``wake_alarm_skip`` rung above does -- bank the pending
marker so the post-carrot run still tries the phone workout, record the
decision -- then leaves through the locker's normal ``close`` (the same
one a credited workout and a test hold use): lock window released,
instance lock dropped, exit 0. Nothing is credited or penalised.
"""
self._save_early_bird_pending()
record_decision(
LockDecision(
locked=False,
reason="wake_alarm_skip_late",
detail=f"Morning session carrot landed after the lock armed: {skip}.",
extra={
"exempt_until": skip.exempt_until.isoformat(),
"outcome": skip.outcome,
},
)
)
_logger.warning(
"Morning-session carrot appeared while the lock was up (%s) — "
"taking the lock down; the early-bird marker is banked.",
skip,
)
self.close()
def _try_auto_upgrade_early_bird(self) -> bool: def _try_auto_upgrade_early_bird(self) -> bool:
"""Try phone then RunnerUp to upgrade an early_bird log entry.""" """Try phone then RunnerUp to upgrade an early_bird log entry."""
try: try:

View File

@ -0,0 +1,76 @@
"""An armed lock stands down when wake-alarm's signed carrot lands late.
2026-11-07: the lock armed at 07:49:17 because today's signed
``morning_session.json`` had not landed yet (the refresher lost a network
race). It landed at 07:50:00 (``in_progress``, exempt until 09:13) and nothing
ever re-read it, so the morning session ran under a fullscreen lock. The
startup ladder reads the file once; this is the same verdict, re-asked every
``POLL_MS`` while the window is up.
The decision stays wake-alarm's (signature ok, dated today, now < exempt_until);
this module only decides *when to ask* -- 05:00-11:00 local, the hours the
refresher runs -- and never waits, since it sits on the Tk loop. The file is
read through the ``_morning_session`` module attribute so the test suite's
redirected path applies.
"""
from __future__ import annotations
from datetime import UTC, datetime
import logging
from typing import TYPE_CHECKING
from screen_locker import _morning_session
if TYPE_CHECKING:
from collections.abc import Callable
from tkinter import Misc
__all__ = ["POLL_MS", "watch_for_carrot"]
_logger = logging.getLogger(__name__)
POLL_MS = 15_000
# Local minutes after midnight; mirrors gatelock.morning_session.MORNING_WINDOW.
_WINDOW_START_MIN = 5 * 60
_WINDOW_END_MIN = 11 * 60
def _local_now() -> datetime:
return datetime.now(tz=UTC).astimezone()
def _in_window(now: datetime) -> bool:
return _WINDOW_START_MIN <= now.hour * 60 + now.minute < _WINDOW_END_MIN
def watch_for_carrot(
root: Misc, on_carrot: Callable[[_morning_session.MorningSkip], None]
) -> None:
"""Hand a late-landing signed carrot to ``on_carrot`` within one poll.
``on_carrot`` is the locker's own stand-down (bank the early-bird marker,
record the decision, then the normal ``close``). Polls on the Tk loop (no
thread) and stops re-arming once it fires. A failed read is logged and the
poll goes on: one bad read must not end the only thing watching.
"""
def _tick() -> None:
now = _local_now()
if _in_window(now):
try:
skip = _morning_session.morning_skip_today(now, wait=False)
except (OSError, ValueError, TypeError, KeyError) as exc:
_logger.warning(
"Could not read the morning session while the lock is up "
"(%s) — keeping the lock and trying again in %d s",
exc,
POLL_MS // 1000,
)
skip = None
if skip is not None:
on_carrot(skip)
return
root.after(POLL_MS, _tick)
root.after(POLL_MS, _tick)

View File

@ -13,6 +13,7 @@ from pathlib import Path
import sys import sys
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _errors
from screen_locker._constants import SHUTDOWN_BASE_FILE from screen_locker._constants import SHUTDOWN_BASE_FILE
from screen_locker._decision_log import record_no_decision from screen_locker._decision_log import record_no_decision
from screen_locker._manual_cli import run_manual_log from screen_locker._manual_cli import run_manual_log
@ -111,6 +112,7 @@ def main(locker_cls: type[ScreenLocker], argv: list[str]) -> None:
level=logging.INFO, level=logging.INFO,
format="%(levelname)s %(name)s: %(message)s", format="%(levelname)s %(name)s: %(message)s",
) )
_errors.install()
if "--status" in argv: if "--status" in argv:
run_status(_headless_locker(locker_cls)) run_status(_headless_locker(locker_cls))

View File

@ -6,7 +6,6 @@ Single source of truth for the leaf checks walked by
mixins delegate their read-only checks to the functions here; this module mixins delegate their read-only checks to the functions here; this module
never touches ADB, sudo, subprocess, or the network, and never writes to never touches ADB, sudo, subprocess, or the network, and never writes to
disk. disk.
``explain_lock_decision`` re-derives the same ordered chain for the status ``explain_lock_decision`` re-derives the same ordered chain for the status
view. One branch is a deliberate simplification: when an early-bird pending view. One branch is a deliberate simplification: when an early-bird pending
marker has expired, the real code attempts a live phone/RunnerUp marker has expired, the real code attempts a live phone/RunnerUp
@ -39,6 +38,7 @@ from screen_locker._compliance_trace import (
describe_degraded_sources, describe_degraded_sources,
) )
from screen_locker._day import today_str as local_day from screen_locker._day import today_str as local_day
from screen_locker._hold import workout_hold_active
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Sequence
@ -114,6 +114,12 @@ _CHAIN: tuple[_Step, ...] = (
"No morning-session skip in force.", "No morning-session skip in force.",
"Morning session earned a skip — lock skipped.", "Morning session earned a skip — lock skipped.",
), ),
_Step(
"test_hold_active",
"A declared test hold is active.",
"No test hold active.",
"Test hold active — no workout window until it ends.",
),
_Step( _Step(
"relaxed_day_already_skipped", "relaxed_day_already_skipped",
"Relaxed day already dismissed via Skip — No Penalty today.", "Relaxed day already dismissed via Skip — No Penalty today.",
@ -161,6 +167,7 @@ def _chain_flags(
"sick_day": is_sick_day_today(local_dt.date()), "sick_day": is_sick_day_today(local_dt.date()),
"already_logged": has_logged_today(log_file, today=today_str), "already_logged": has_logged_today(log_file, today=today_str),
"wake_alarm_skip": wake_skip, "wake_alarm_skip": wake_skip,
"test_hold_active": workout_hold_active(local_dt),
"relaxed_day_already_skipped": relaxed_day "relaxed_day_already_skipped": relaxed_day
and is_relaxed_day_skipped_today(log_file, today=today_str), and is_relaxed_day_skipped_today(log_file, today=today_str),
"relaxed_day": relaxed_day, "relaxed_day": relaxed_day,

View File

@ -73,11 +73,11 @@ WORKOUT_DURATION_ACCEPT_MINUTES = (
) )
RUNNERUP_PACKAGES = ("org.runnerup", "org.runnerup.free") RUNNERUP_PACKAGES = ("org.runnerup", "org.runnerup.free")
RUNNERUP_DB_SDCARD_TMP = "/sdcard/.runnerup_tmp_verification.db" RUNNERUP_DB_SDCARD_TMP = "/sdcard/.runnerup_tmp_verification.db"
# A run qualifies on EITHER criterion — they are an OR, not an AND. A short # A day's activity (run or walk alike) qualifies on EITHER criterion — they are
# but long-lasting run counts, and so does a fast 5 km that takes under the # an OR, not an AND. A short but long-lasting session counts, and so does a
# duration bar. Do not reinstate an AND here: it would reject exactly the # fast 5 km that takes under the duration bar. Do not reinstate an AND here:
# slow-run case this pair exists to allow. The duration arm is the shared # it would reject exactly the slow case this pair exists to allow. The
# MIN_WORKOUT_DURATION_MINUTES above; only the distance arm is run-specific. # duration arm is the shared MIN_WORKOUT_DURATION_MINUTES above (moving time).
MIN_RUN_DISTANCE_KM = 3.5 # inclusive: "as low as 3.5 km" MIN_RUN_DISTANCE_KM = 3.5 # inclusive: "as low as 3.5 km"
# GPS distance tracking undershoots on tight turns/tree cover/urban canyons; # GPS distance tracking undershoots on tight turns/tree cover/urban canyons;
# a run within 5% of the minimum is accepted rather than rejected on # a run within 5% of the minimum is accepted rather than rejected on
@ -105,11 +105,22 @@ SHUTDOWN_BASE_FILE = Path(__file__).resolve().parent / "shutdown_base.json"
REST_DAY_FILE = Path(__file__).resolve().parent / "rest_days.json" REST_DAY_FILE = Path(__file__).resolve().parent / "rest_days.json"
REST_DAYS_PER_ISO_WEEK = 2 REST_DAYS_PER_ISO_WEEK = 2
GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json" GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json"
# A day's RunnerUp walks (commute legs) count as the workout once their # Every GPS activity (run or walk, whatever its TCX sport) is judged the same
# MOVING time reaches WORKOUT_DURATION_ACCEPT_MINUTES (the shared bar above); # way: a day's activities count as the workout once their summed distance
# moving = trackpoint pairs at walking speed. # reaches MIN_RUN_DISTANCE_KM OR their summed MOVING time reaches
WALK_SPEED_MPS = (0.5, 3.0) # WORKOUT_DURATION_ACCEPT_MINUTES. Moving = trackpoint pairs seen within
# WALK_MAX_GAP_SECONDS and travelled at least this fast (slower is standing
# still). A pair faster than MAX_MOVING_SPEED_MPS (25 km/h, the app's running
# jump filter) is a vehicle or a GPS jump and counts neither moving time NOR
# distance, for every activity. The Dart app mirrors the bounds.
MIN_MOVING_SPEED_MPS = 0.5
MAX_MOVING_SPEED_MPS = 25 / 3.6
WALK_MAX_GAP_SECONDS = 30 WALK_MAX_GAP_SECONDS = 30
# Speed is judged over windows of at least this long (1 s fixes jitter), and a
# window longer than WALK_MAX_GAP_SECONDS (a GPS dropout) only counts as
# moving time at this speed or faster, so standing through a gap earns nothing.
TRACK_WINDOW_SECONDS = 10
MIN_DROPOUT_SPEED_MPS = 1.0
# Workout records this PC must keep deleted in the sync store, pushed as # Workout records this PC must keep deleted in the sync store, pushed as
# tombstones on every tick (see _sync_tombstones for why once is not enough). # tombstones on every tick (see _sync_tombstones for why once is not enough).
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json" SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"

35
screen_locker/_credit.py Normal file
View File

@ -0,0 +1,35 @@
"""kuhy's shared credit logo on screen-locker's Tk windows.
kuhy, 2026-11-21: the logo goes "everywhere in every single app, desktop
program", lockers too (``kuhy_credit`` README, kuhyx/utils). The widget is
the shared ``kuhy_credit.tk.KuhyCredit``; this module only fixes where it
sits so every window puts it in the same corner. A click on its panel opens
the site in a browser tab, which stays behind the fullscreen lock until the
lock closes.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from kuhy_credit.tk import KuhyCredit
if TYPE_CHECKING:
import tkinter as tk
from gatelock import LockConfig
def place_credit(parent: tk.Misc, config: LockConfig) -> KuhyCredit:
"""Place the logo in ``parent``'s bottom-right corner, above its siblings.
``parent`` must be the toplevel (a lock surface or a plain window), never
a content frame a flow clears and repaints. Call it after the window's
full-size viewport exists: siblings stack in creation order, so the logo
lands above it. (``KuhyCredit.lift`` is a Canvas item raise, not a
window raise, so it cannot do this.)
"""
pad = config.space("xl")
credit = KuhyCredit(parent, theme="dark", size=config.type_px("display"))
credit.place(relx=1, rely=1, x=-pad, y=-pad, anchor="se")
return credit

View File

@ -6,11 +6,8 @@ that credits a workout ends in
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`, :meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`,
which calls :func:`notify_workout_credit` once per newly earned credit slot. which calls :func:`notify_workout_credit` once per newly earned credit slot.
The gaming figure is ``earned_time.resolve`` over screen-locker's own answers The body shows the shutdown only: the gaming budget is gone (earned_time
(:func:`screen_locker._shutdown_target.gather` -- the same sum the daily reset 0.22.0), so there is no second figure to feel.
writes), so no budget math lives here. steam-backlog-enforcer resolves the
same registry with its own transports and holds a day's high-water mark, so
its figure can sit above this one, never below on a normal day.
A notification is a courtesy, never part of crediting: any failure (no DBus, A notification is a courtesy, never part of crediting: any failure (no DBus,
no notify-send, a hang) is logged at warning and swallowed. no notify-send, a hang) is logged at warning and swallowed.
@ -22,50 +19,34 @@ from datetime import date
import logging import logging
import shutil import shutil
import subprocess import subprocess
from typing import TYPE_CHECKING, Final from typing import Final
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import hhmm, span from screen_locker._earned import hhmm, span
from screen_locker._grace_floor import tonight_minutes from screen_locker._grace_floor import tonight_minutes
from screen_locker._shutdown_target import gather
if TYPE_CHECKING:
from pathlib import Path
_logger: Final = logging.getLogger(__name__) _logger: Final = logging.getLogger(__name__)
TITLE: Final = "Workout credited \N{FLEXED BICEPS}" # textgate: glyphs + numbers (colour emoji are safe in the notification
# daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h)" /
# "Credit applied (details unavailable)".
TITLE: Final = "\N{FLEXED BICEPS} \N{CHECK MARK}"
_SHUTDOWN: Final = "\N{POWER SYMBOL}"
_NOTIFY_TIMEOUT_SECONDS: Final = 5 _NOTIFY_TIMEOUT_SECONDS: Final = 5
_MINUTES_PER_HOUR: Final = 60.0
def gaming_minutes_today(log_file: Path | None) -> int | None:
"""Today's gaming budget per the earned_time registry, or ``None``.
``None`` (logged) when the inputs cannot be read; the notification then
shows the shutdown time alone.
"""
try:
target = gather(date.fromisoformat(today_str()), log_file)
except (OSError, ValueError, KeyError) as exc:
_logger.warning(
"Could not compute today's gaming budget for the credit "
"notification (%s) — showing the shutdown time only",
exc,
)
return None
return int(target.resolution.gaming_minutes)
def credit_body( def credit_body(
before: tuple[int, int, int] | None, before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None, after: tuple[int, int, int] | None,
gaming_minutes: int | None, reward: int | None = None,
) -> str: ) -> str:
"""``Shutdown 23:00 (+2h) · gaming 7.0h`` -- whichever parts are known. """``⏻ 23:00 (+2h)`` -- whichever parts are known.
``before``/``after`` are the shutdown config around the credit; the delta ``before``/``after`` are the shutdown config around the credit. The delta
is tonight's actual move, so a capped or rest-day credit shows ``+0h``. is what the workout earned: tonight's actual move, so a capped or rest-day
credit shows ``+0h``, but never more than ``reward``: the late-credit rule
(gone 2026-11-18) once moved 18:00 to 21:58 and the toast read "+3h58m"
for a 2h run.
""" """
parts: list[str] = [] parts: list[str] = []
if after is None: if after is None:
@ -76,14 +57,14 @@ def credit_body(
else: else:
day = date.fromisoformat(today_str()) day = date.fromisoformat(today_str())
tonight = tonight_minutes(after, day) tonight = tonight_minutes(after, day)
text = f"Shutdown {hhmm(tonight)}" text = f"{_SHUTDOWN} {hhmm(tonight)}"
if before is not None: if before is not None:
moved = max(0, tonight - tonight_minutes(before, day)) moved = max(0, tonight - tonight_minutes(before, day))
if reward is not None:
moved = min(moved, reward)
text += f" (+{span(moved)})" text += f" (+{span(moved)})"
parts.append(text) parts.append(text)
if gaming_minutes is not None: return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
parts.append(f"gaming {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
return " \N{MIDDLE DOT} ".join(parts) or "Credit applied (details unavailable)"
def send_notification(title: str, body: str) -> bool: def send_notification(title: str, body: str) -> bool:
@ -118,8 +99,8 @@ def send_notification(title: str, body: str) -> bool:
def notify_workout_credit( def notify_workout_credit(
before: tuple[int, int, int] | None, before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None, after: tuple[int, int, int] | None,
log_file: Path | None, reward: int | None,
) -> bool: ) -> bool:
"""Notify a newly earned workout credit. Never raises.""" """Notify a newly earned workout credit. Never raises."""
body = credit_body(before, after, gaming_minutes_today(log_file)) body = credit_body(before, after, reward)
return send_notification(TITLE, body) return send_notification(TITLE, body)

View File

@ -0,0 +1,117 @@
"""An open lock window closes itself the moment today's workout is credited.
2026-11-16: the window opened at 07:55:17. kuhy logged a manual workout on the
phone; at 07:59:04 the separate ``_session_stream`` daemon credited it (log row
written, shutdown moved). The open window never noticed: TRY AGAIN only asked
StrongLifts/ADB/HTTP, so it kept saying "stale" and kuhy marked a sick day to
get out. The startup ladder reads ``log.json`` once; this is the same verdict
(``has_logged_today``, HMAC-checked) re-asked whenever the file changes.
Event-driven on the Tk loop, no thread, no new dependency: each poll is one
``stat`` of the log; the file is parsed only when its (mtime, size, inode)
moved. The credit itself was already written by whoever logged it, so closing
here writes nothing and applies nothing -- it just takes the window down.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker._decision_log import LockDecision, record_decision
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
from tkinter import Misc
__all__ = ["POLL_MS", "CreditStandDownMixin", "watch_for_credit"]
_logger = logging.getLogger(__name__)
# Well inside the 10 s an open window may take to notice a credit.
POLL_MS = 3_000
_UNSEEN: tuple[int, ...] = (-1,)
_ABSENT: tuple[int, ...] = ()
def _signature(log_file: Path) -> tuple[int, ...] | None:
"""(mtime_ns, size, inode) of the log: ``()`` when absent, None on error."""
# exists() first: a log nobody has written yet is normal, not a fault, and
# a bare ``except FileNotFoundError`` would be a silent swallow.
if not log_file.exists():
return _ABSENT
try:
stat = log_file.stat()
except OSError as exc:
_logger.warning(
"Could not stat %s while the lock is up (%s) — keeping the lock "
"and trying again in %d s",
log_file,
exc,
POLL_MS // 1000,
)
return None
return (stat.st_mtime_ns, stat.st_size, stat.st_ino)
def watch_for_credit(
root: Misc,
log_file: Path,
has_logged: Callable[[], bool],
on_credit: Callable[[], None],
) -> None:
"""Hand a credit that landed while the window is up to ``on_credit``.
The first poll always checks (a row may land between startup and arming);
after that ``has_logged`` runs only when the log's signature changed. A
failed check is logged and the poll goes on: one bad read must not end the
only thing watching. Stops re-arming once it fires.
"""
seen = _UNSEEN
def _tick() -> None:
nonlocal seen
sig = _signature(log_file)
if sig is not None and sig != seen:
seen = sig
try:
if has_logged():
on_credit()
return
except (OSError, ValueError, TypeError, KeyError) as exc:
_logger.warning(
"Could not check %s for a credit while the lock is up "
"(%s) — keeping the lock and trying again in %d s",
log_file,
exc,
POLL_MS // 1000,
)
seen = _UNSEEN
root.after(POLL_MS, _tick)
root.after(POLL_MS, _tick)
class CreditStandDownMixin:
"""The locker's side: leave through the normal ``close`` once credited."""
def _stand_down_for_credit(self) -> None:
"""Take the window down because today's workout is already credited.
Same exit as a credited workout, a test hold or a late carrot: lock
window released, instance lock dropped, exit 0. No row, no credit, no
penalty -- the logger of the workout already did all of that.
"""
record_decision(
LockDecision(
locked=False,
reason="workout_credited_elsewhere",
detail="Today's workout was credited while the lock was up.",
)
)
_logger.warning(
"Today's workout was credited by another process while the lock "
"was up — taking the lock down without writing a second credit."
)
self.close()

View File

@ -0,0 +1,87 @@
"""A gate's signed progress, read for the shutdown sum (``earned_time`` 0.24.0).
A gate signs "done N of M for day D" in its own ledger; ``earned_time`` pays a
no that share of a yes and owns every other pay rule (``term_for``; none is
priced here). A day with no such row pays by yes/no exactly as before. Two
readers here, one per caller:
* :func:`progress_for` -- the whole day's map, for ``earned_time.resolve``
(the daily reset, the sick floor and the preview);
* :func:`term_minutes` -- one earner's pay, for the live pass, which has to
know what it may pay *now* before it subtracts what it already applied.
The workout is left out of the map on purpose: ``WorkoutCreditMixin`` applies
it per unit, so a share paid by the reset alone would be wiped or doubled.
Both look the readers up at call time: an installed ``earned_time`` older than
0.24 pays by yes/no, logged once, never raises.
"""
from __future__ import annotations
import functools
import logging
from typing import TYPE_CHECKING
import earned_time
from screen_locker import _earned
from screen_locker._gate_off import gate_off
if TYPE_CHECKING:
from datetime import date
_logger = logging.getLogger(__name__)
@functools.cache
def _warn_no_progress() -> None:
"""Once per process: the installed earned_time predates progress."""
_logger.warning(
"earned_time has no progress reader (needs >= 0.24); every bonus pays "
"all-or-nothing"
)
def progress_for(day: date) -> dict[str, earned_time.Progress] | None:
"""Each non-workout earner's signed progress on ``day``; ``None`` if none.
``None`` for no row at all (so ``resolve`` is called exactly as before)
and on an ``earned_time`` without ``progress_map``.
"""
fn = getattr(earned_time, "progress_map", None)
if fn is None:
_warn_no_progress()
return None
earners = tuple(
e for e in _earned.registry(day) if e.name != earned_time.WORKOUT.name
)
found: dict[str, earned_time.Progress] = fn(
day,
_earned.LEDGER_HOME,
_earned.HMAC_KEY_FILE,
earners=earners,
gate_off={e.name for e in earners if gate_off(e, day)},
)
return found or None
def term_minutes(earner: earned_time.Earner, day: date, *, answer: bool | None) -> int:
"""The shutdown minutes ``earner`` earned on ``day``, priced by the library.
``earned_time.term_for`` owns every rule (a yes pays the rung, a no the
signed progress's share, ``None`` nothing, the review's dated rule); this
only reads the fact it needs. Before 0.24 it is the old yes/no.
"""
term_for = getattr(earned_time, "term_for", None)
read = getattr(earned_time, "read_progress", None)
if term_for is None or read is None:
_warn_no_progress()
return _earned.first_minutes(earner, day) if answer else 0
fact = read(
earner,
_earned.ledger_file(earner),
_earned.HMAC_KEY_FILE,
day,
gate_off=gate_off(earner, day),
)
return int(term_for(earner, day, answer=answer, progress=fact).shutdown_minutes)

33
screen_locker/_errors.py Normal file
View File

@ -0,0 +1,33 @@
"""Error and slow-wait reporting for screen-locker (utils DOCS-app-errors.md).
``install`` runs once from the CLI entry point: uncaught, thread and Tk
callback errors, and a Tk loop frozen over 1 s, go to the app-errors spool,
from which the PC's ingest files a board ticket. Only the CLI installs it, so
tests that build a lock window never touch the real spool.
"""
from __future__ import annotations
from dataclasses import dataclass
from gatelock import error_report
APP = "screen-locker"
REPO = "kuhyx/screen-locker"
@dataclass
class _Slot:
"""Holds the process's reporter once installed."""
reporter: error_report.Reporter | None = None
#: The installed reporter (``SLOT.reporter``); None until ``install``.
SLOT = _Slot()
def install() -> error_report.Reporter:
"""Hook this process's errors once; return the reporter."""
SLOT.reporter = error_report.install(APP, REPO)
return SLOT.reporter

View File

@ -1,7 +1,10 @@
"""Live shutdown credit for counted gate earners: paid per unit, as it lands. """Live shutdown credit for counted gate earners: paid per unit, as it lands.
A flat earner (LeetCode, reading) pays once a day, stamped A flat earner (LeetCode, reading) pays by its signed progress (a credited
``<name>_bonus_date``. A counted gate earner -- the Automation tutor, one day pays in full), stamped ``<name>_bonus_minutes`` with the minutes the
config already holds; each pass pays only the rise. ``<name>_bonus_date`` is
the legacy stamp (the full bonus, written before progress existed) and is
still honoured. A counted gate earner -- the Automation tutor, one
signed ledger row per verified 15-minute block -- pays per unit, so its stamp signed ledger row per verified 15-minute block -- pays per unit, so its stamp
is ``<name>_bonus_units``: the day, and how many units the config already is ``<name>_bonus_units``: the day, and how many units the config already
holds. The live pass pays only the difference, priced by holds. The live pass pays only the difference, priced by
@ -32,10 +35,32 @@ _logger = logging.getLogger(__name__)
def date_stamp(earner: earned_time.Earner) -> str: def date_stamp(earner: earned_time.Earner) -> str:
"""The once-per-day key of a flat earner's live pass in the state file.""" """The legacy key: a flat earner's full bonus applied on that date."""
return f"{earner.name}_bonus_date" return f"{earner.name}_bonus_date"
def minutes_stamp(earner: earned_time.Earner) -> str:
"""The key of the minutes a flat earner's live pass applied on a date."""
return f"{earner.name}_bonus_minutes"
def applied_minutes(
state: dict[str, Any], earner: earned_time.Earner, today: str, full: int
) -> int:
"""Minutes of ``earner``'s bonus the config already holds today.
The legacy date stamp means the FULL bonus (so a deploy between two
passes never pays twice); else the minutes stamp of today; else 0.
"""
if state.get(date_stamp(earner)) == today:
return full
raw = state.get(minutes_stamp(earner))
if not isinstance(raw, dict) or raw.get("date") != today:
return 0
minutes = raw.get("minutes")
return minutes if isinstance(minutes, int) and minutes > 0 else 0
def units_stamp(earner: earned_time.Earner) -> str: def units_stamp(earner: earned_time.Earner) -> str:
"""The per-day key of ``earner``'s applied units in the state file.""" """The per-day key of ``earner``'s applied units in the state file."""
return f"{earner.name}_bonus_units" return f"{earner.name}_bonus_units"
@ -53,13 +78,17 @@ def applied_units(state: dict[str, Any], earner: earned_time.Earner, today: str)
def reset_stamps(terms: Iterable[earned_time.Term], today: str) -> dict[str, object]: def reset_stamps(terms: Iterable[earned_time.Term], today: str) -> dict[str, object]:
"""The stamps for what a daily reset already wrote into the config. """The stamps for what a daily reset already wrote into the config.
A flat earner that paid is stamped with the date, a counted gate with A flat earner that paid is stamped with the minutes it paid (a partial
its units, so the live pass does not add either a second time today. pay is not the full bonus, so never the date), a counted gate with its
units, so the live pass does not add either a second time today.
""" """
stamps: dict[str, object] = {} stamps: dict[str, object] = {}
for t in terms: for t in terms:
if t.earner.kind == "flat" and t.shutdown_minutes: if t.earner.kind == "flat" and t.shutdown_minutes:
stamps[date_stamp(t.earner)] = today stamps[minutes_stamp(t.earner)] = {
"date": today,
"minutes": t.shutdown_minutes,
}
elif t.earner.kind == "counted" and is_gate(t.earner) and t.answer: elif t.earner.kind == "counted" and is_gate(t.earner) and t.answer:
stamps[units_stamp(t.earner)] = {"date": today, "units": t.answer} stamps[units_stamp(t.earner)] = {"date": today, "units": t.answer}
return stamps return stamps

113
screen_locker/_glyphs.py Normal file
View File

@ -0,0 +1,113 @@
"""The locker's pictograms: one place, so a glyph means one thing everywhere.
textgate (kuhy, 2026-11-08): nothing he sees carries words. Every screen is
built from these plus numbers, each paired with a palette colour as the
second channel (success / warning / danger / muted). Plain geometric
characters only: a colour-emoji fallback font can crash Tk 8.6, so no
U+1Fxxx and nothing with an emoji presentation by default.
"""
from __future__ import annotations
from typing import Final
LIFT: Final = "●━━●" # a barbell: the StrongLifts workout / "go work out"
RUN: Final = "⇝" # a RunnerUp run
PHONE: Final = "▯" # the phone (adb)
WAIT: Final = "⋯" # checking / unlocking in progress
OK: Final = "✓"
FAIL: Final = "✗"
RETRY: Final = "↻"
CLOSE: Final = "✕"
BACK: Final = "↩"
GO: Final = "▶"
SKIP: Final = "↷"
SYNC: Final = "⇅" # a sync backend (Firebase)
CLOCK: Final = "◷" # time, the system clock
SHORT: Final = "◔" # a session shorter than the minimum
FORM: Final = "≡" # the manual-workout evidence form
SICK: Final = "✚" # a sick day
SHUTDOWN: Final = "⏻" # the PC's shutdown time
STREAK: Final = "▰" # one week of the streak
WEEK_DONE: Final = "●" # a counted day
WEEK_SICK: Final = "✚" # a sick day in the week row
WEEK_EMPTY: Final = "○" # a day with nothing counted
HEAT: Final = "▲" # the outdoor temperature
LOCK: Final = "■" # the lock fired
UNLOCK: Final = "□" # the lock stood down
OPTIONAL: Final = "◇" # Tue-Thu: a workout is optional today
GIFT: Final = "+" # an earned reward, always followed by its amount
# Button glyph text -> the one hover word (textgate tooltip exception). Keys
# are the exact strings passed to the locker's buttons.
TOOLTIP: Final[dict[str, str]] = {
PHONE: "Phone",
FORM: "Manual",
RETRY: "Retry",
CLOSE: "Close",
BACK: "Back",
SKIP: "Skip",
SICK: "Sick",
OK: "Submit",
f"{GO} {LIFT}": "Workout",
GO: "Workout",
}
# Startup phone-check status -> the glyph that replaces its sentence.
STATUS_GLYPH: Final[dict[str, str]] = {
"too_short": SHORT,
"clock_tampered": f"{CLOCK}{FAIL}",
"stale": f"{CLOCK}{FAIL}",
"no_exercises": f"{LIFT} 0",
"not_verified": FAIL,
"no_phone": f"{PHONE}{FAIL}",
"error": f"{PHONE}{FAIL}",
}
# log.json entry ``type`` -> glyph, for the status window's day cells.
ENTRY_GLYPH: Final[dict[str, str]] = {
"phone_verified": LIFT,
"strength": LIFT,
"pc_workout_verified": LIFT,
"runnerup_verified": RUN,
"running": RUN,
"manual_workout": FORM,
"heat_skip": HEAT,
"relaxed_day_skip": SKIP,
"early_bird": OK,
}
# Lock-decision stage (``_compliance_state._STEPS`` names) -> glyph. A stage
# not listed shows only the lock/unlock square and its colour.
STAGE_GLYPH: Final[dict[str, str]] = {
"scheduled_skip": SKIP,
"early_bird_pending_expired": CLOCK,
"early_bird_window_open": CLOCK,
"sick_day": SICK,
"already_logged": OK,
"wake_alarm_skip": CLOCK,
"test_hold_active": WAIT,
"relaxed_day_already_skipped": f"{OPTIONAL}{SKIP}",
"relaxed_day": OPTIONAL,
"weekly_minimum_met": WEEK_DONE,
"evening_lockdown_today": SHUTDOWN,
"would_lock": LIFT,
}
def entry_glyphs(types: tuple[str, ...]) -> str:
"""Glyphs for a day's entry types; an unknown type shows as ``OK``."""
return " ".join(ENTRY_GLYPH.get(t, OK) for t in types)
def dots(done: int, total: int) -> str:
"""``●●○○ 2/4``: progress as filled dots plus the numbers (two channels)."""
filled = max(0, min(done, total))
return f"{WEEK_DONE * filled}{WEEK_EMPTY * (total - filled)} {done}/{total}"
def status_glyph(status: str) -> str:
"""Return the glyph for a phone-check *status* (``FAIL`` if unknown)."""
return STATUS_GLYPH.get(status, FAIL)

View File

@ -1,10 +1,9 @@
"""When the day's first task was done, and the day's floor lift. """When the day's first task was done, and the day's floor lift.
The grace floor (first task + 60 min) is gone since 2026-10-17: a credit at The grace floor (first task + 60 min) is gone since 2026-10-17. The
or after tonight's shutdown now counts from its own time late-credit rule that replaced it (a credit after tonight's shutdown counted
(:mod:`screen_locker._late_credit`), which is what the floor approximated, from its own time) went on 2026-11-18: every credit adds to tonight's
and the floor's lift then absorbed minutes the late credit had already shutdown, and unpaid gates hold the PC behind the evening chain until 23:00.
restarted from (LeetCode late at 19:00, reading at 19:30: 20:10, not 20:20).
What stays: :func:`first_done_at` (shown by the preview and the reset log) What stays: :func:`first_done_at` (shown by the preview and the reset log)
and the lift file. The lift is ``0`` on every day now (no floor lifts the and the lift file. The lift is ``0`` on every day now (no floor lifts the

View File

@ -9,6 +9,8 @@ from typing import TYPE_CHECKING
from gatelock import LockConfig, bind_activate, bind_cancel from gatelock import LockConfig, bind_activate, bind_cancel
from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
from screen_locker._credit import place_credit
from screen_locker._tooltip import attach_tooltip
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
@ -42,39 +44,35 @@ def build_heat_skip_content(
outer = tk.Frame(parent, bg=_COLORS.palette.bg) outer = tk.Frame(parent, bg=_COLORS.palette.bg)
outer.place(relx=0.5, rely=0.5, anchor="center") outer.place(relx=0.5, rely=0.5, anchor="center")
# textgate: glyphs + numbers only, warning colour as the second channel.
# Was "\u2600 Too hot to workout?" / "<city>: 31\u00b0C (threshold: 30\u00b0C)" /
# "Skip today's workout due to extreme heat?". Plain geometric glyphs,
# not the sun (U+2600 can fall back to a colour-emoji font and crash Tk).
tk.Label( tk.Label(
outer, outer,
text="\u2600 Too hot to workout?", text="\u25b2",
font=_COLORS.font("body", bold=True, family=_FONT), font=_COLORS.font("display", bold=True, family=_FONT),
bg=_COLORS.palette.bg, bg=_COLORS.palette.bg,
fg=_COLORS.palette.warning, fg=_COLORS.palette.warning,
).pack(pady=(0, _COLORS.space("sm"))) ).pack(pady=(0, _COLORS.space("sm")))
tk.Label( tk.Label(
outer, outer,
text=( # The city name was dropped too: the reading is what matters.
f"{HEAT_SKIP_CITY}: {temp:.0f}\u00b0C" text=f"{temp:.0f}\u00b0C \u2265 {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C",
f" (threshold: {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C)"
),
font=_COLORS.font("body", family=_FONT), font=_COLORS.font("body", family=_FONT),
bg=_COLORS.palette.bg, bg=_COLORS.palette.bg,
fg=_COLORS.palette.muted, fg=_COLORS.palette.warning,
).pack(pady=_COLORS.space("xs")) ).pack(pady=_COLORS.space("xs"))
tk.Label(
outer,
text="Skip today's workout due to extreme heat?",
font=_COLORS.font("body", family=_FONT),
bg=_COLORS.palette.bg,
fg=_COLORS.palette.muted,
).pack(pady=(_COLORS.space("xs"), 0))
btn_frame = tk.Frame(outer, bg=_COLORS.palette.bg) btn_frame = tk.Frame(outer, bg=_COLORS.palette.bg)
btn_frame.pack(pady=_COLORS.space("lg")) btn_frame.pack(pady=_COLORS.space("lg"))
# Was "Skip workout" (warning fill) / "No, I'll workout" (neutral fill).
skip_button = tk.Button( skip_button = tk.Button(
btn_frame, btn_frame,
text="Skip workout", name="skip",
text="\u21b7",
command=on_skip, command=on_skip,
bg=_COLORS.palette.warning, bg=_COLORS.palette.warning,
fg=_COLORS.palette.on_fill, fg=_COLORS.palette.on_fill,
@ -86,10 +84,12 @@ def build_heat_skip_content(
**_COLORS.focus_kwargs(), **_COLORS.focus_kwargs(),
) )
skip_button.pack(side="left", padx=_COLORS.space("sm")) skip_button.pack(side="left", padx=_COLORS.space("sm"))
attach_tooltip(skip_button, "Skip")
decline_button = tk.Button( decline_button = tk.Button(
btn_frame, btn_frame,
text="No, I'll workout", name="decline",
text="▶",
command=on_decline, command=on_decline,
bg=_COLORS.palette.field_bg, bg=_COLORS.palette.field_bg,
fg=_COLORS.palette.fg, fg=_COLORS.palette.fg,
@ -101,6 +101,7 @@ def build_heat_skip_content(
**_COLORS.focus_kwargs(), **_COLORS.focus_kwargs(),
) )
decline_button.pack(side="left", padx=_COLORS.space("sm")) decline_button.pack(side="left", padx=_COLORS.space("sm"))
attach_tooltip(decline_button, "Workout")
# This modal grabs input and sits fullscreen with no window decoration, so # This modal grabs input and sits fullscreen with no window decoration, so
# the keyboard is the only way out for a pointerless user. It used to # the keyboard is the only way out for a pointerless user. It used to
@ -130,7 +131,7 @@ class HeatSkipMixin:
# Use the root itself (not a Toplevel) so we can go fullscreen. # Use the root itself (not a Toplevel) so we can go fullscreen.
# This window is destroyed before the main GateRoot is created. # This window is destroyed before the main GateRoot is created.
root = tk.Tk() root = tk.Tk()
root.title("Extreme Heat") root.title("")
root.configure(bg=_COLORS.palette.bg) root.configure(bg=_COLORS.palette.bg)
root.attributes("-fullscreen", True) root.attributes("-fullscreen", True)
root.attributes("-topmost", True) root.attributes("-topmost", True)
@ -146,6 +147,7 @@ class HeatSkipMixin:
root.destroy() root.destroy()
build_heat_skip_content(root, temp, on_skip=_on_skip, on_decline=_on_no) build_heat_skip_content(root, temp, on_skip=_on_skip, on_decline=_on_no)
place_credit(root, _COLORS)
bind_cancel(root, _on_no) bind_cancel(root, _on_no)
root.mainloop() root.mainloop()

86
screen_locker/_hold.py Normal file
View File

@ -0,0 +1,86 @@
"""A declared test hold keeps the workout locker from showing any window.
``holds`` (kuhyx/utils, ``holds-v0.1.0``) is the shared "a proctored test is
running, leave the PC usable" switch. Every workout-locker path -- the relaxed
day's optional prompt, the strict lock and the early-bird re-check -- runs
through ``_startup_checks._check_non_verify_exits``, so one rung there covers
them all. It sits BELOW the reset/bonus/ingest/early-bird bookkeeping: a hold
only suppresses the window, never a credit or a penalty term.
Fail closed: if ``holds`` cannot be imported or read, there is no hold and the
locker behaves exactly as it did before, with an ERROR in the journal. A hold
that fails open would be a free escape from the gate.
"""
from __future__ import annotations
import importlib
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
from datetime import datetime
from tkinter import Misc
__all__ = ["HOLD_REASON", "skip_during_hold", "watch_for_hold", "workout_hold_active"]
_logger = logging.getLogger(__name__)
HOLD_REASON = "test_hold_active"
_GATE = "workout"
# Well inside the 60 s a hold may take to lift an open window.
POLL_MS = 30_000
def workout_hold_active(now: datetime | None = None) -> bool:
"""Whether a declared hold covers the workout gate right now."""
try:
# Imported at call time so a missing package fails closed, per call.
holds = importlib.import_module("holds")
return bool(holds.covers(_GATE, now))
except ImportError, OSError, ValueError, TypeError, KeyError:
_logger.exception(
"Could not read the test holds — treating it as no hold, so "
"the workout locker behaves as normal"
)
return False
def skip_during_hold(record_skip: Callable[..., None]) -> bool:
"""Skip enforcement while a hold is active.
Takes the locker's ``_record_skip`` (which exits the process) rather than
the locker, like ``_night_lockdown``. Returns True when the skip was
recorded, False when the ladder may go on.
"""
if not workout_hold_active():
return False
record_skip(
HOLD_REASON,
"A declared test hold is active — no workout prompt or lock window "
"until it ends (credit and penalty bookkeeping already ran).",
)
return True
def watch_for_hold(root: Misc, close: Callable[[], None]) -> None:
"""Close an already-open window within one poll of a hold starting.
``close`` is the locker's own ``close`` -- it tears the window down and
exits 0 without writing a credit or a penalty, so a hold that interrupts
an open prompt/lock changes nothing but the screen. Polls on the Tk loop
(no thread) and stops re-arming once it fires.
"""
def _tick() -> None:
if workout_hold_active():
_logger.warning(
"A test hold started while the workout window was open — "
"closing it without credit or penalty."
)
close()
return
root.after(POLL_MS, _tick)
root.after(POLL_MS, _tick)

View File

@ -1,106 +0,0 @@
"""A credit at or after tonight's shutdown counts from its own time.
Shutting down must never make a finished task impossible to submit (kuhy,
2026-10-17). The config is read-add-write, so a credit landing after the
shutdown used to add its minutes to a time already past: LeetCode at 19:00
after an 18:00 shutdown made 19:00, and the machine stayed locked. Now such
a credit moves tonight to ``its own time + its reward``, capped at the
ceiling -- only the ceiling (23:00) is hard.
The anchor is the credit's own time (a run's end, a ledger row's), never the
moment a sync applied it, so a late upload does not buy extra time. Past the
shutdown the grace and sick lifts are spent: the caller clears the lift.
"""
from __future__ import annotations
from datetime import date, datetime
import logging
import time
from typing import TYPE_CHECKING
from screen_locker._ceiling import ceiling
from screen_locker._day import today_str
from screen_locker._earned import hhmm
from screen_locker._grace_floor import save_lift, tonight_minutes
_logger = logging.getLogger(__name__)
def _now() -> float:
"""The clock a credit without its own time is stamped with."""
return time.time()
def late_tonight(
config: tuple[int, int, int], day: date, at: float, minutes: int
) -> int | None:
"""Tonight's new shutdown for a late credit, or ``None`` if it is not late.
Late means timed on ``day`` at or after tonight's shutdown: the check
script locks at ``now >= shutdown``, so a credit exactly on it is late.
"""
moment = datetime.fromtimestamp(at).astimezone()
if moment.date() != day:
return None
done = moment.hour * 60 + moment.minute
if done < tonight_minutes(config, day):
return None
return min(ceiling(day), done + minutes)
class LateCreditMixin:
"""Late credits and sick-day credits; composed into ShutdownMixin."""
if TYPE_CHECKING:
def _read_shutdown_config(self) -> tuple[int, int, int] | None:
raise NotImplementedError
def _write_shutdown_config(
self, mon_wed: int, thu_sun: int, morning_end: int, *, restore: bool = ...
) -> bool:
raise NotImplementedError
def _apply_sick_floor(self) -> bool: ...
def _raise_on_sick_day(self, minutes: int, at: float | None) -> bool:
"""A sick day's credit: raise to the derived target, never add.
The credit's row is already in the target (``_sick_floor``), so adding
its minutes on top would pay it twice; a late one still counts from
its own time. True even when nothing moved (capped, or already there):
the credit is accounted for, and a failed write is retried by the next
tick's sick pass.
"""
self._apply_sick_floor()
late = self._late_write(minutes, at)
return True if late is None else late
def _late_write(self, minutes: int, at: float | None) -> bool | None:
"""Write a late credit's shutdown; ``None`` when it is not late."""
day = date.fromisoformat(today_str())
try:
config = self._read_shutdown_config()
except (OSError, ValueError) as exc:
# The add path reads it again inside its own guard and fails there.
_logger.warning("Late credit: cannot read shutdown config (%s)", exc)
return None
if config is None:
return None # the add path reads it again and reports it
target = late_tonight(config, day, _now() if at is None else at, minutes)
if target is None:
return None
mon_wed, thu_sun, morning = config
if not self._write_shutdown_config(
max(mon_wed, target), max(thu_sun, target), morning, restore=True
):
_logger.warning("Late credit: failed to write shutdown config")
return False
save_lift(0) # past the shutdown, the floors' lift is spent
_logger.info(
"Late credit: shutdown %s -> %s (earned at or after tonight's).",
hhmm(tonight_minutes(config, day)),
hhmm(target),
)
return True

View File

@ -32,6 +32,7 @@ from screen_locker._manual_workout_checks import (
from screen_locker._manual_workout_types import ( from screen_locker._manual_workout_types import (
MANUAL_WORKOUT_TYPE, MANUAL_WORKOUT_TYPE,
SPORT_CHOICES, SPORT_CHOICES,
SPORT_GLYPHS,
SPORT_LABELS, SPORT_LABELS,
SPORT_OTHER, SPORT_OTHER,
SPORT_TABLE_TENNIS, SPORT_TABLE_TENNIS,
@ -44,6 +45,7 @@ from screen_locker._manual_workout_types import (
__all__ = [ __all__ = [
"MANUAL_WORKOUT_TYPE", "MANUAL_WORKOUT_TYPE",
"SPORT_CHOICES", "SPORT_CHOICES",
"SPORT_GLYPHS",
"SPORT_LABELS", "SPORT_LABELS",
"SPORT_OTHER", "SPORT_OTHER",
"SPORT_TABLE_TENNIS", "SPORT_TABLE_TENNIS",

View File

@ -13,6 +13,7 @@ the form shows a "scheduled" screen that returns to the host's cancelled hook
from __future__ import annotations from __future__ import annotations
import logging
import tkinter as tk import tkinter as tk
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
@ -29,6 +30,16 @@ from screen_locker._ui_widgets import disable_paste
if TYPE_CHECKING: if TYPE_CHECKING:
from screen_locker._manual_workout import ManualWorkoutDraft from screen_locker._manual_workout import ManualWorkoutDraft
# textgate: plain glyphs (no colour emoji: Tk 8.6 can crash on them).
SCHEDULED_GLYPH = "✓"
"""Heading of the scheduled screen (success colour)."""
BACK_GLYPH = "↩"
"""The scheduled screen's only button: back to the form's host."""
REJECTED_GLYPH = "✗"
"""Form rejected (danger); was the validator's sentence (now logged)."""
_logger = logging.getLogger(__name__)
class ManualWorkoutDateMixin: class ManualWorkoutDateMixin:
"""Date row, budget gate and future-dated submission of the manual form.""" """Date row, budget gate and future-dated submission of the manual form."""
@ -59,9 +70,10 @@ class ManualWorkoutDateMixin:
) )
entry.pack(side="right", padx=self._colors.space("xs")) entry.pack(side="right", padx=self._colors.space("xs"))
disable_paste(entry) disable_paste(entry)
# Was "Workout date (today to +7 days):" -- a day square + the range.
tk.Label( tk.Label(
row, row,
text="Workout date (today to +7 days):", text="□ +0…+7",
font=self._colors.font("label"), font=self._colors.font("label"),
fg=self._colors.palette.fg, fg=self._colors.palette.fg,
bg=self._colors.palette.bg, bg=self._colors.palette.bg,
@ -80,37 +92,45 @@ class ManualWorkoutDateMixin:
if error is None and not future: if error is None and not future:
error = budget_error(self.log_file, date) error = budget_error(self.log_file, date)
if error is not None: if error is not None:
self._mw_error_label.config(text=error) self._mw_reject(error)
return True return True
if not future: if not future:
return False return False
result = schedule_future_workout(self.log_file, draft, date) result = schedule_future_workout(self.log_file, draft, date)
if not result.scheduled: if not result.scheduled:
self._mw_error_label.config(text=result.reason) self._mw_reject(result.reason)
return True return True
self._show_manual_workout_scheduled(result.reason) _logger.info("Manual workout scheduled for %s: %s", date, result.reason)
self._show_manual_workout_scheduled(date)
return True return True
def _show_manual_workout_scheduled(self, reason: str) -> None: def _mw_reject(self, reason: str) -> None:
"""Confirm a future entry and go back; it does NOT unlock anything.""" """Show the form's fail mark; the reason goes to the log (textgate)."""
_logger.warning("Manual workout date/budget rejected: %s", reason)
self._mw_error_label.config(text=REJECTED_GLYPH)
def _show_manual_workout_scheduled(self, date: str) -> None:
"""Confirm a future entry and go back; it does NOT unlock anything.
Shows the scheduled *date* (content) under the tick; the scheduler's
sentence is logged by the caller.
"""
self.clear_container() self.clear_container()
# Was "✓ Workout Scheduled" + "Nothing is credited today. It counts by
# itself on that date, and can be deleted in the phone app until
# then." + an "OK" button: a green tick, the reason, a back arrow.
self._label( self._label(
"✓ Workout Scheduled", SCHEDULED_GLYPH,
role="display", role="display",
scale=1.3, scale=1.3,
color=self._colors.palette.success, color=self._colors.palette.success,
pad="lg", pad="lg",
) )
self._text(reason, role="subtitle", color=self._colors.palette.success) self._text(date, role="subtitle", color=self._colors.palette.success)
self._text(
"Nothing is credited today. It counts by itself on that date, and "
"can be deleted in the phone app until then.",
color=self._colors.palette.muted,
)
row = self._button_row() row = self._button_row()
self._button( self._button(
row, row,
"OK", BACK_GLYPH,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._on_manual_workout_cancelled, command=self._on_manual_workout_cancelled,
width=12, width=12,

View File

@ -23,12 +23,24 @@ from screen_locker import _manual_workout
from screen_locker._constants import ( from screen_locker._constants import (
MANUAL_WORKOUT_REFLECTION_MIN_CHARS, MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
) )
from screen_locker._manual_workout_date import ManualWorkoutDateMixin from screen_locker._manual_workout_date import (
BACK_GLYPH,
REJECTED_GLYPH,
ManualWorkoutDateMixin,
)
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
# textgate glyphs (plain Unicode, no colour emoji: Tk 8.6 can crash on them).
FORM_GLYPH = "≡"
"""Form heading (accent); was "Log Manual Workout"."""
EXHAUSTED_GLYPH = "✕"
"""Budget used up (danger); was the "budget exhausted" sentence."""
SUBMIT_GLYPH = "✓"
"""Submit button (accent fill); was "SUBMIT"."""
_SPORT_LABEL_TO_CODE = { _SPORT_LABEL_TO_CODE = {
label: code for code, label in _manual_workout.SPORT_LABELS.items() label: code for code, label in _manual_workout.SPORT_LABELS.items()
} }
@ -44,12 +56,11 @@ class ManualWorkoutDialogMixin(
def _show_manual_workout_form(self) -> None: def _show_manual_workout_form(self) -> None:
"""Render the manual-workout evidence form, or a budget-exhausted note.""" """Render the manual-workout evidence form, or a budget-exhausted note."""
self.clear_container() self.clear_container()
self._label("Log Manual Workout", color=self._colors.palette.accent, pad="xs") # textgate: glyphs, colours second. Was "Log Manual Workout" heading /
# "Manual-workout budget exhausted for this window." / "BACK".
self._label(FORM_GLYPH, color=self._colors.palette.accent, pad="xs")
if self._mw_budget_closed(): if self._mw_budget_closed():
self._text( self._label(EXHAUSTED_GLYPH, color=self._colors.palette.danger, pad="xs")
"Manual-workout budget exhausted for this window.",
color=self._colors.palette.danger,
)
self._text( self._text(
_manual_workout.budget_summary(self.log_file), _manual_workout.budget_summary(self.log_file),
color=self._colors.palette.muted, color=self._colors.palette.muted,
@ -57,7 +68,7 @@ class ManualWorkoutDialogMixin(
row = self._button_row() row = self._button_row()
self._button( self._button(
row, row,
"BACK", BACK_GLYPH,
bg=self._colors.palette.field_bg, bg=self._colors.palette.field_bg,
command=self._on_manual_workout_cancelled, command=self._on_manual_workout_cancelled,
width=12, width=12,
@ -87,24 +98,23 @@ class ManualWorkoutDialogMixin(
self._mw_rpe_var = tk.IntVar(value=5) self._mw_rpe_var = tk.IntVar(value=5)
self._mw_text_widgets: dict[str, tk.Text] = {} self._mw_text_widgets: dict[str, tk.Text] = {}
self._mw_section(form, "Basics") # textgate: every prompt is a glyph; optional fields are in
# parentheses; section headings are plain rules. The old prompts were
# the Basics heading, start and end time, the location heading and
# name, how you got there, the cost in PLN, the optional reservation
# phone number, and the activity-details heading.
self._mw_section(form)
self._mw_sport_row(form) self._mw_sport_row(form)
self._mw_vars["start_time"] = self._mw_entry( self._mw_vars["start_time"] = self._mw_entry(form, "◷▶", focus=True)
form, "Start time (HH:MM):", focus=True self._mw_vars["end_time"] = self._mw_entry(form, "◷■")
)
self._mw_vars["end_time"] = self._mw_entry(form, "End time (HH:MM):")
self._mw_section(form, "Location & logistics") self._mw_section(form)
self._mw_vars["location_name"] = self._mw_entry(form, "Location name:") self._mw_vars["location_name"] = self._mw_entry(form, "⌖")
self._mw_vars["transport_method"] = self._mw_entry( self._mw_vars["transport_method"] = self._mw_entry(form, "⇄")
form, "How did you get there?" self._mw_vars["cost"] = self._mw_entry(form, "¤")
) self._mw_vars["reservation_phone"] = self._mw_entry(form, "(▯#)")
self._mw_vars["cost"] = self._mw_entry(form, "Cost (e.g. 40 PLN):")
self._mw_vars["reservation_phone"] = self._mw_entry(
form, "Reservation phone number (if booked by phone, optional):"
)
self._mw_section(form, "Activity details") self._mw_section(form)
# Both sport sub-frames occupy the same full-width grid slot; only the # Both sport sub-frames occupy the same full-width grid slot; only the
# selected one is shown (see _on_mw_sport_changed). # selected one is shown (see _on_mw_sport_changed).
act_row = self._mw_next_full_row(form) act_row = self._mw_next_full_row(form)
@ -124,33 +134,22 @@ class ManualWorkoutDialogMixin(
self._build_table_tennis_fields(self._mw_tt_frame) self._build_table_tennis_fields(self._mw_tt_frame)
self._build_other_sport_fields(self._mw_other_frame) self._build_other_sport_fields(self._mw_other_frame)
self._mw_rpe_row(form) self._mw_rpe_row(form)
self._mw_vars["techniques_practiced"] = self._mw_entry( # Was "Techniques/focus areas practiced (optional):", "Warm-up
form, "Techniques/focus areas practiced (optional):" # duration (optional):", "Pain or injury notes (optional, ...)".
) self._mw_vars["techniques_practiced"] = self._mw_entry(form, "(◎)")
self._mw_vars["warm_up_minutes"] = self._mw_entry( self._mw_vars["warm_up_minutes"] = self._mw_entry(form, "(∿)")
form, "Warm-up duration (optional):" self._mw_vars["pain_or_injury"] = self._mw_entry(form, "(↯)")
)
self._mw_vars["pain_or_injury"] = self._mw_entry(
form, "Pain or injury notes (optional, default none):"
)
self._on_mw_sport_changed( self._on_mw_sport_changed(
_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS] _manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
) )
self._mw_section(form, "Reflection") # Was "Reflection", "What went well / What to improve / Overall
self._mw_text_widgets["went_well"] = self._mw_textbox( # feeling about the session (min N chars):".
form, self._mw_section(form)
f"What went well (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):", least = f"≥{MANUAL_WORKOUT_REFLECTION_MIN_CHARS}"
) self._mw_text_widgets["went_well"] = self._mw_textbox(form, f"+ {least}")
self._mw_text_widgets["to_improve"] = self._mw_textbox( self._mw_text_widgets["to_improve"] = self._mw_textbox(form, f"↑ {least}")
form, self._mw_text_widgets["overall_feeling"] = self._mw_textbox(form, f"~ {least}")
f"What to improve (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
)
self._mw_text_widgets["overall_feeling"] = self._mw_textbox(
form,
"Overall feeling about the session "
f"(min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
)
self._mw_error_label = self._text( self._mw_error_label = self._text(
"", role="label", color=self._colors.palette.danger, pad="xs" "", role="label", color=self._colors.palette.danger, pad="xs"
@ -158,14 +157,14 @@ class ManualWorkoutDialogMixin(
button_row = self._button_row() button_row = self._button_row()
self._button( self._button(
button_row, button_row,
"SUBMIT", SUBMIT_GLYPH,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._submit_manual_workout_form, command=self._submit_manual_workout_form,
width=12, width=12,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
self._button( self._button(
button_row, button_row,
"BACK", BACK_GLYPH,
bg=self._colors.palette.field_bg, bg=self._colors.palette.field_bg,
command=self._on_manual_workout_cancelled, command=self._on_manual_workout_cancelled,
width=12, width=12,
@ -212,7 +211,9 @@ class ManualWorkoutDialogMixin(
) )
error = _manual_workout.validate_manual_workout(draft) error = _manual_workout.validate_manual_workout(draft)
if error is not None: if error is not None:
self._mw_error_label.config(text=error) # textgate: the reason is logged; the form shows the fail mark.
_logger.warning("Manual workout form rejected: %s", error)
self._mw_error_label.config(text=REJECTED_GLYPH)
return return
if self._mw_handled_by_date(draft): if self._mw_handled_by_date(draft):
return return

View File

@ -49,17 +49,11 @@ class ManualWorkoutSportFieldsMixin:
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS] value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
) )
row = tk.Frame(parent, bg=self._colors.palette.bg) row = tk.Frame(parent, bg=self._colors.palette.bg)
tk.Label( # textgate: the "Sport:" caption is gone; the radio row is the cue.
row, for code, label in _manual_workout.SPORT_LABELS.items():
text="Sport:",
font=self._colors.font("body"),
fg=self._colors.palette.fg,
bg=self._colors.palette.bg,
).pack(side="left", padx=self._colors.space("xs"))
for label in _manual_workout.SPORT_LABELS.values():
tk.Radiobutton( tk.Radiobutton(
row, row,
text=label, text=_manual_workout.SPORT_GLYPHS[code],
value=label, value=label,
variable=self._mw_sport_var, variable=self._mw_sport_var,
# Radiobutton's command takes no argument -- bind the label. # Radiobutton's command takes no argument -- bind the label.
@ -97,25 +91,25 @@ class ManualWorkoutSportFieldsMixin:
def _build_table_tennis_fields(self, parent: tk.Widget) -> None: def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
"""Build the table-tennis-specific score/equipment fields.""" """Build the table-tennis-specific score/equipment fields."""
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:") # textgate: was "Matches won/lost:", "Sets won/lost:", "Racket used:",
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:") # "Balls used:". Match / set glyph + win / loss mark.
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:") self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "◍✓")
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:") self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "◍✗")
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:") self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "▤✓")
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:") self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "▤✗")
self._mw_vars["racket"] = self._mw_entry(parent, "◖")
self._mw_vars["balls"] = self._mw_entry(parent, "•")
def _build_other_sport_fields(self, parent: tk.Widget) -> None: def _build_other_sport_fields(self, parent: tk.Widget) -> None:
"""Build the generic "other sport" fields.""" """Build the generic "other sport" fields."""
self._mw_vars["activity_type_other"] = self._mw_entry( # Was "What sport/activity:" / "What was done (min N chars):" /
parent, "What sport/activity:" # "Equipment used (optional):"; optional fields are in parentheses.
) self._mw_vars["activity_type_other"] = self._mw_entry(parent, "✱")
self._mw_text_widgets["activity_details"] = self._mw_textbox( self._mw_text_widgets["activity_details"] = self._mw_textbox(
parent, parent,
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):", f"✱≡ ≥{MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS}",
)
self._mw_vars["equipment"] = self._mw_entry(
parent, "Equipment used (optional):"
) )
self._mw_vars["equipment"] = self._mw_entry(parent, "(⊡)")
def _current_mw_sport(self) -> str: def _current_mw_sport(self) -> str:
"""Return the internal sport code for the currently-selected label.""" """Return the internal sport code for the currently-selected label."""

View File

@ -37,6 +37,12 @@ SPORT_LABELS: dict[str, str] = {
SPORT_TABLE_TENNIS: "Table tennis", SPORT_TABLE_TENNIS: "Table tennis",
SPORT_OTHER: "Other", SPORT_OTHER: "Other",
} }
# What the form paints for each sport (textgate); SPORT_LABELS stays the
# radio value and the data, never painted.
SPORT_GLYPHS: dict[str, str] = {
SPORT_TABLE_TENNIS: "◍",
SPORT_OTHER: "✱",
}
def _today_iso() -> str: def _today_iso() -> str:
@ -133,12 +139,16 @@ def budget_summary(
*, *,
today: str | None = None, today: str | None = None,
) -> str: ) -> str:
"""One-line UI summary string for the manual-workout budget.""" """One-line UI summary of the manual-workout budget: glyph and numbers.
``≡ used/7-day budget · used/30-day budget`` (textgate; was
``Manual: 0/2w · 0/10m``). The shorter window always comes first.
"""
week = count_in_window(log_file, 7, today=today) week = count_in_window(log_file, 7, today=today)
month = count_in_window(log_file, 30, today=today) month = count_in_window(log_file, 30, today=today)
return ( return (
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · " f"≡ {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m" f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
) )

View File

@ -66,17 +66,10 @@ class ManualWorkoutFormWidgetsMixin:
counters[id(parent)] = idx + 2 counters[id(parent)] = idx + 2
return idx // 2 return idx // 2
def _mw_section(self, parent: tk.Widget, title: str) -> None: def _mw_section(self, parent: tk.Widget) -> None:
"""Add a full-width section heading inside the form.""" """Add a full-width rule between form sections (was a heading)."""
label = tk.Label( rule = tk.Frame(parent, bg=self._colors.palette.accent, height=2)
parent, self._mw_grid(parent, rule, full=True)
text=title,
font=self._colors.font("body", bold=True),
fg=self._colors.palette.accent,
bg=self._colors.palette.bg,
anchor="w",
)
self._mw_grid(parent, label, full=True)
def _mw_entry( def _mw_entry(
self, parent: tk.Widget, label: str, *, focus: bool = False self, parent: tk.Widget, label: str, *, focus: bool = False
@ -190,10 +183,8 @@ class ManualWorkoutFormWidgetsMixin:
row = tk.Frame(parent, bg=self._colors.palette.bg) row = tk.Frame(parent, bg=self._colors.palette.bg)
tk.Label( tk.Label(
row, row,
text=( # Was "RPE — perceived exertion (1-10):": effort bars + range.
f"RPE — perceived exertion " text=f"▁▃▅▇ {MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}",
f"({MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}):"
),
font=self._colors.font("label"), font=self._colors.font("label"),
fg=self._colors.palette.fg, fg=self._colors.palette.fg,
bg=self._colors.palette.bg, bg=self._colors.palette.bg,

View File

@ -5,7 +5,7 @@ leetcode-guard and book-guard (diet-guard deliberately does not opt in); this
module only binds screen-locker's path, which the test suite redirects, and module only binds screen-locker's path, which the test suite redirects, and
the ladder rung that honours it. the ladder rung that honours it.
Why: once tonight's lockdown has fired, a late credit (``_late_credit``) can Why: once tonight's lockdown has fired, a credit that moves the shutdown can
lift it -- and re-locking behind the workout gate the same evening would make lift it -- and re-locking behind the workout gate the same evening would make
a finished workout impossible to submit. Only an EVENING lock counts (local a finished workout impossible to submit. Only an EVENING lock counts (local
date today, >= 12:00); the 04:01 morning re-lock does not. Missing or garbage date today, >= 12:00); the 04:01 morning re-lock does not. Missing or garbage

View File

@ -25,7 +25,6 @@ from screen_locker._constants import (
SHUTDOWN_BASE_FILE, SHUTDOWN_BASE_FILE,
SHUTDOWN_CONFIG_FILE, SHUTDOWN_CONFIG_FILE,
) )
from screen_locker._credit_notify import gaming_minutes_today
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import hhmm from screen_locker._earned import hhmm
from screen_locker._extra_benefits import process_week_transition from screen_locker._extra_benefits import process_week_transition
@ -38,7 +37,6 @@ from screen_locker.screen_lock import ScreenLocker
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable, Mapping from collections.abc import Iterable, Mapping
from pathlib import Path
from screen_locker._workout_credit import WorkoutCreditResult from screen_locker._workout_credit import WorkoutCreditResult
@ -49,7 +47,6 @@ __all__ = [
"credit_manual_workouts", "credit_manual_workouts",
"credit_session", "credit_session",
"credit_sessions", "credit_sessions",
"current_gaming_minutes",
"current_shutdown", "current_shutdown",
] ]
@ -120,11 +117,6 @@ def current_shutdown() -> str | None:
return hhmm(tonight_minutes(config, date.fromisoformat(today_str()))) return hhmm(tonight_minutes(config, date.fromisoformat(today_str())))
def current_gaming_minutes(log_file: Path) -> int | None:
"""Today's gaming budget (``None`` and a warning when it cannot be summed)."""
return gaming_minutes_today(log_file)
def _precheck(record_id: str, payload: Mapping[str, object]) -> str | None: def _precheck(record_id: str, payload: Mapping[str, object]) -> str | None:
"""Why the session can never count, or ``None`` if it can. """Why the session can never count, or ``None`` if it can.

View File

@ -46,21 +46,19 @@ def _reply(
outcome: _poke_credit.PokeOutcome, outcome: _poke_credit.PokeOutcome,
*, *,
sandbox: bool = False, sandbox: bool = False,
snapshot: tuple[str | None, int | None] = (None, None), shutdown: str | None = None,
) -> dict[str, object]: ) -> dict[str, object]:
"""The contract's response shape; ``pc_ms`` is filled in by the handler. """The contract's response shape; ``pc_ms`` is filled in by the handler.
``snapshot`` is (tonight's shutdown ``HH:MM``, gaming minutes); refusals ``shutdown`` is tonight's shutdown ``HH:MM``; refusals leave it null
leave it null rather than tell an unverified caller anything. rather than tell an unverified caller anything.
""" """
shutdown, gaming = snapshot
return { return {
"ok": outcome.ok, "ok": outcome.ok,
"credited": outcome.credited, "credited": outcome.credited,
"duplicate": outcome.duplicate, "duplicate": outcome.duplicate,
"sandbox": sandbox, "sandbox": sandbox,
"shutdown": shutdown, "shutdown": shutdown,
"gaming_budget_minutes": gaming,
"pc_ms": 0, "pc_ms": 0,
"reason": outcome.reason, "reason": outcome.reason,
} }
@ -77,7 +75,6 @@ def _refused(reason: str) -> dict[str, object]:
def _process(request: PokeRequest) -> dict[str, object]: def _process(request: PokeRequest) -> dict[str, object]:
"""Credit (or, for a sandbox request, only answer) one verified poke.""" """Credit (or, for a sandbox request, only answer) one verified poke."""
locker = _poke_credit.fresh_locker()
if request.sandbox: if request.sandbox:
outcome = _poke_credit.PokeOutcome( outcome = _poke_credit.PokeOutcome(
ok=True, ok=True,
@ -90,10 +87,7 @@ def _process(request: PokeRequest) -> dict[str, object]:
return _reply( return _reply(
outcome, outcome,
sandbox=request.sandbox, sandbox=request.sandbox,
snapshot=( shutdown=_poke_credit.current_shutdown(),
_poke_credit.current_shutdown(),
_poke_credit.current_gaming_minutes(locker.log_file),
),
) )

View File

@ -0,0 +1,89 @@
"""The workout's signed "progress" row: how far a too-short verified day got.
Writer only. The row is inert today -- no reader in ``earned_time`` looks at
``kind: "progress"`` yet -- and it never touches a bonus, a shutdown time, a
stamp or the web payload. It records ``done`` of ``target`` for one day, in
integers, from the verified RunnerUp TCX only::
{"kind": "progress", "entry_id": "progress:<day>:<done>:<target>",
"day": <day>, "amount": 0,
"detail": {"source": "workout", "for_day": <day>,
"done": "<digits>", "target": "<digits>"}}
The larger of the two fractions (distance / distance bar, moving time / time
bar) is the one recorded, so ``done``/``target`` is metres over metres or
seconds over seconds. The bars come from ``_constants`` and appear only inside
the signed row: they are never logged or shown (the constants file keeps a
deliberate leeway hidden). The ADVERTISED bars are the targets, not the
looser accept bars, so a row never reveals the leeway.
Signing, locking and idempotence on ``entry_id`` are the credit rows' own
(:func:`screen_locker._workout_ledger.append_rows`); a second short run the
same day has a larger ``done`` and so a new id.
"""
from __future__ import annotations
import logging
from typing import Any
from screen_locker._constants import MIN_RUN_DISTANCE_KM, MIN_WORKOUT_DURATION_MINUTES
from screen_locker._workout_ledger import append_rows
_logger = logging.getLogger(__name__)
SOURCE = "workout"
def progress_pair(metres: float, moving_seconds: float) -> tuple[int, int] | None:
"""``(done, target)`` of the leading fraction, or ``None`` with nothing done.
Both fractions are compared exactly, by cross-multiplying integers; a tie
goes to distance. ``done`` is floored and capped at its ``target``.
"""
distance_target = round(MIN_RUN_DISTANCE_KM * 1000)
time_target = MIN_WORKOUT_DURATION_MINUTES * 60
distance_done = min(int(max(metres, 0.0)), distance_target)
time_done = min(int(max(moving_seconds, 0.0)), time_target)
if distance_done * time_target >= time_done * distance_target:
done, target = distance_done, distance_target
else:
done, target = time_done, time_target
return (done, target) if done > 0 else None
def progress_row(for_day: str, done: int, target: int) -> dict[str, Any] | None:
"""The unsigned progress row; ``None`` when nothing was done."""
if done <= 0:
return None
return {
"kind": "progress",
"entry_id": f"progress:{for_day}:{done}:{target}",
"day": for_day,
"amount": 0,
"detail": {
"source": SOURCE,
"for_day": for_day,
"done": str(done),
"target": str(target),
},
}
def record_progress(for_day: str, metres: float, moving_seconds: float) -> None:
"""Append the day's progress row; never raises, never changes a verdict.
Call only for a day verified from RunnerUp TCX data and judged too short.
A row that cannot be signed or written is logged at warning or above by
``append_rows``; any other failure is logged here.
"""
try:
pair = progress_pair(metres, moving_seconds)
row = progress_row(for_day, *pair) if pair is not None else None
if row is not None:
append_rows([row])
except Exception: # pylint: disable=broad-exception-caught # a progress row must never change the verdict
_logger.exception(
"Could not write the progress row for %s; the workout verdict is unchanged",
for_day,
)

View File

@ -15,7 +15,8 @@ import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from screen_locker._log_mixin import write_signed_entry from screen_locker._log_mixin import write_signed_entry
from screen_locker._walk_tcx import walk_day, walk_shortfall from screen_locker._progress_row import record_progress
from screen_locker._walk_tcx import activity_day, activity_shortfall
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
@ -72,66 +73,48 @@ class RunnerUpBackfillMixin:
Returns True if a new verified entry was appended for ``date_str``. Returns True if a new verified entry was appended for ``date_str``.
""" """
walks: list[dict[str, Any]] = [] activities = [
for remote in self._find_runnerup_exports_for_date(date_str): data
data = self._pull_and_parse_tcx(remote) for remote in self._find_runnerup_exports_for_date(date_str)
if data is None: if (data := self._pull_and_parse_tcx(remote)) is not None
continue ]
if data.get("walking"): return self._try_fill_day(date_str, activities, log_file, on_ingested)
# Never one walk at a time: a day's walks are summed below.
walks.append(data)
continue
status, msg = self._validate_runnerup_data(data)
if status != "verified":
_logger.warning(
"RunnerUp export %s for %s did not qualify (%s): %s",
remote,
date_str,
status,
msg,
)
continue
workout_data = {
"type": "runnerup_verified",
"source": f"Auto-scanned: {msg}",
"distance_km": round(data["distance_m"] / 1000, 2),
"duration_minutes": round(data["duration_seconds"] / 60, 1),
"completed_at": data.get("ended_at"),
}
return _record(log_file, date_str, workout_data, on_ingested)
return self._try_fill_walks(date_str, walks, log_file, on_ingested)
@staticmethod @staticmethod
def _try_fill_walks( def _try_fill_day(
date_str: str, date_str: str,
walks: list[dict[str, Any]], activities: list[dict[str, Any]],
log_file: Path, log_file: Path,
on_ingested: OnIngestedCallback | None, on_ingested: OnIngestedCallback | None,
) -> bool: ) -> bool:
"""Append the day's walking as its RunnerUp workout, once it adds up. """Append the day's activity as its RunnerUp workout, once it adds up.
Same type and so the same ``runnerup_verified:{date}`` slot as a run: One rule for runs and walks alike (see :mod:`screen_locker._walk_tcx`):
a walk and a run on one day are one RunnerUp credit, exactly as two the day's activities are summed, never judged one file at a time. They
runs already were. share the ``runnerup_verified:{date}`` slot, so a walk and a run on
one day are one RunnerUp credit. ``activity: walking`` is kept for the
phone's history display only; it never decides credit.
""" """
if not walks: if not activities:
return False return False
day = walk_day(walks) day = activity_day(activities)
if not day.qualifies: if not day.qualifies:
_logger.warning( _logger.warning(
"RunnerUp walks for %s do not count yet: %s", "RunnerUp activity for %s does not count yet: %s",
date_str, date_str,
walk_shortfall(day), activity_shortfall(day),
) )
record_progress(date_str, day.metres, day.moving_seconds)
return False return False
workout_data = { workout_data: dict[str, Any] = {
"type": "runnerup_verified", "type": "runnerup_verified",
"activity": "walking",
"source": f"Auto-scanned: {day.message()}", "source": f"Auto-scanned: {day.message()}",
"distance_km": round(day.distance_km, 2), "distance_km": round(day.distance_km, 2),
"duration_minutes": round(day.moving_minutes, 1), "duration_minutes": round(day.moving_minutes, 1),
"completed_at": day.completed_at, "completed_at": day.completed_at,
} }
if day.all_walks:
workout_data["activity"] = "walking"
return _record(log_file, date_str, workout_data, on_ingested) return _record(log_file, date_str, workout_data, on_ingested)
def _scan_and_fill_week_runnerup( def _scan_and_fill_week_runnerup(

View File

@ -0,0 +1,215 @@
"""Retire the stock RunnerUp app a week after the PC first credits an app run.
kuhy's workout_app records runs itself now. Once the PC has credited one of
them, RunnerUp is redundant: seven days later (``GRACE``) it is backed up and
uninstalled, but only if the app has imported the RunnerUp history (a marker
the app writes) and that import matches what ``processed/`` holds. With no
anchor (no app run ever credited) it never uninstalls.
The phone is not always on USB, so ``runnerup-retire.timer`` retries daily
until this succeeds. Every outcome is a typed :class:`RetireResult` whose
reason is logged at the level it deserves: ``info`` for the normal "not due
yet", ``warning`` for a skip that needs attention, ``error`` for a failure.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from screen_locker._runnerup_retire_adb import PACKAGE, AdbError
from screen_locker._runnerup_retire_result import LEVEL, Outcome, RetireResult
from screen_locker._runnerup_retire_state import load_state, save_state
from screen_locker._runnerup_retire_tcx import app_run_ends, check_marker, find_anchor
if TYPE_CHECKING:
from screen_locker._runnerup_retire_adb import PhoneLike
from screen_locker._runnerup_retire_state import RetireState
_logger = logging.getLogger(__name__)
GRACE = timedelta(days=7)
STATE_FILE = Path.home() / ".local" / "state" / "screen-locker" / "runnerup_retire.json"
WATCH_DIR = Path.home() / "data" / "cloud" / "RunnerUp"
LOG_FILE = Path(__file__).resolve().parent / "log.json"
MARKER_NAME = ".workout_app_import.json"
@dataclass(frozen=True)
class Paths:
"""Every on-disk location, so tests (and ``--status``) can redirect them."""
state_file: Path
watch_dir: Path
log_file: Path
@classmethod
def default(cls) -> Paths:
"""The live locations (read at call time so tests can patch them)."""
return cls(STATE_FILE, WATCH_DIR, LOG_FILE)
@property
def processed(self) -> Path:
"""Where endurain-import files the RunnerUp exports it has handled."""
return self.watch_dir / "processed"
@property
def marker(self) -> Path:
"""The app's historic-import marker."""
return self.watch_dir / MARKER_NAME
def anchor_dirs(self) -> tuple[Path, Path]:
"""Where an app run's TCX can sit: the drop dir, then ``processed/``."""
return (self.watch_dir, self.processed)
def derive_anchor(paths: Paths, state: RetireState) -> datetime | None:
"""The stored anchor, else the first credit of an app run found on disk."""
return state.anchor or find_anchor(paths.log_file, paths.anchor_dirs())
def _finish(paths: Paths, state: RetireState, now: datetime, why: str) -> None:
save_state(
paths.state_file, replace(state, done_at=now.isoformat(), done_reason=why)
)
def _probe(phone: PhoneLike) -> RetireResult | tuple[str, bool]:
"""``(serial, installed)`` if the phone answers, else the result explaining why."""
if not phone.available():
return RetireResult(
Outcome.ADB_MISSING, "adb is not installed (pacman -S android-tools)"
)
try:
device = phone.find_device()
if device.serial is None:
return RetireResult(
Outcome.DEVICE_ABSENT, f"{device.reason}; retrying next run"
)
return device.serial, phone.installed(device.serial)
except AdbError as exc:
_logger.exception("RunnerUp retirement: asking the phone failed")
return RetireResult(
Outcome.PHONE_ERROR, f"asking the phone failed: {exc}", logged=True
)
def _backup(
paths: Paths, phone: PhoneLike, state: RetireState, serial: str, now: datetime
) -> RetireState | RetireResult:
"""Back the phone's exports up once; a later retry reuses a finished backup."""
if state.backup_path and Path(state.backup_path).is_dir():
return state
final = paths.watch_dir / f"runnerup_phone_backup_{now:%Y-%m-%d}"
try:
made, files = phone.backup(serial, final)
except (AdbError, OSError) as exc:
_logger.exception("RunnerUp retirement: backup failed")
return RetireResult(Outcome.BACKUP_FAILED, f"backup failed: {exc}", logged=True)
_logger.info("Backed up %d RunnerUp TCX files to %s", files, made)
state = replace(state, backup_path=str(made))
save_state(paths.state_file, state)
return state
def _retire(
paths: Paths, phone: PhoneLike, state: RetireState, now: datetime, *, dry_run: bool
) -> RetireResult:
"""Everything after "it is due and the marker is good": the phone steps."""
probed = _probe(phone)
if isinstance(probed, RetireResult):
return probed
serial, present = probed
if not present:
if not dry_run:
_finish(paths, state, now, f"{PACKAGE} was already absent")
return RetireResult(Outcome.ALREADY_GONE, f"{PACKAGE} is already absent")
if dry_run:
return RetireResult(
Outcome.DRY_RUN, "would back up and uninstall (no changes made)"
)
backed = _backup(paths, phone, state, serial, now)
if isinstance(backed, RetireResult):
return backed
try:
phone.uninstall(serial)
except AdbError as exc:
_logger.exception("RunnerUp retirement: uninstall failed")
return RetireResult(
Outcome.UNINSTALL_FAILED, f"uninstall failed: {exc}", logged=True
)
_finish(paths, backed, now, f"uninstalled after backup to {backed.backup_path}")
return RetireResult(
Outcome.UNINSTALLED,
f"{PACKAGE} uninstalled; backup in {backed.backup_path}",
)
def _no_anchor(paths: Paths) -> RetireResult:
"""Why there is no anchor; a missing source is a warning, not "nothing yet"."""
absent = [str(p) for p in (paths.watch_dir, paths.log_file) if not p.exists()]
if absent:
return RetireResult(
Outcome.SOURCES_MISSING,
f"cannot look for app runs, missing: {', '.join(absent)}",
)
seen = len(app_run_ends(paths.anchor_dirs()))
return RetireResult(
Outcome.NO_ANCHOR,
f"no app-recorded run credited yet ({seen} app TCX on disk); nothing to retire",
)
def _gate(
paths: Paths, state: RetireState, now: datetime, *, dry_run: bool
) -> RetireState | RetireResult:
"""The no-phone checks; a state back means "due, marker good: go on"."""
if state.done_at:
return RetireResult(
Outcome.ALREADY_DONE, f"done {state.done_at}: {state.done_reason}"
)
anchor = derive_anchor(paths, state)
if anchor is None:
return _no_anchor(paths)
if not state.anchor_at:
state = replace(state, anchor_at=anchor.isoformat())
if not dry_run:
save_state(paths.state_file, state)
due = anchor + GRACE
if now < due:
return RetireResult(
Outcome.NOT_DUE, f"due {due:%Y-%m-%d %H:%M} (anchor {anchor:%Y-%m-%d})"
)
marker = check_marker(paths.marker, paths.processed)
if not marker.ok:
return RetireResult(
Outcome.MARKER_INVALID, f"{marker.reason}; NOT uninstalling"
)
return state
def run_retire(
paths: Paths,
phone: PhoneLike,
now: datetime | None = None,
*,
dry_run: bool = False,
) -> RetireResult:
"""One pass: uninstall RunnerUp if (and only if) every condition holds."""
when = now or datetime.now(UTC)
gated = _gate(paths, load_state(paths.state_file), when, dry_run=dry_run)
if isinstance(gated, RetireResult):
result = gated
else:
result = _retire(paths, phone, gated, when, dry_run=dry_run)
if not result.logged:
_logger.log(
LEVEL.get(result.outcome, logging.INFO),
"RunnerUp retirement: %s: %s",
result.outcome.value,
result.reason,
)
return result

View File

@ -0,0 +1,181 @@
"""The phone side of the RunnerUp retirement: find it, back it up, uninstall.
Every call carries ``-s <serial>`` and goes through one ``run`` seam, so tests
never touch a device. adb's exit code is not trusted for the uninstall: it
counts only when the output says ``Success`` AND ``pm list packages`` no
longer lists the package.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
from pathlib import Path
import shutil
import subprocess
from typing import TYPE_CHECKING, Any, NoReturn, Protocol
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
PHONE_SERIAL = "23181JEGR08034"
PACKAGE = "org.runnerup.free"
REMOTE_DIR = "/sdcard/Documents/RunnerUp"
_ADB_TIMEOUT_S = 50
# The whole export history (TCX + GPX) over wifi adb; the oneshot unit has no
# start timeout, so a slow pull is allowed to finish.
_PULL_TIMEOUT_S = 900
class AdbError(RuntimeError):
"""An adb call failed; the message says what and why."""
def _fail(message: str) -> NoReturn:
raise AdbError(message)
@dataclass(frozen=True)
class Device:
"""Outcome of looking for the phone: the adb serial to use, or why not."""
serial: str | None
reason: str
class PhoneLike(Protocol):
"""What the retirement needs from a phone (tests substitute a fake)."""
def available(self) -> bool:
"""Whether adb can be run at all."""
def find_device(self) -> Device:
"""The attached phone, or why there is none."""
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Whether RunnerUp is on the phone."""
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Pull the exports to ``final``."""
def uninstall(self, dev: str) -> None:
"""Uninstall RunnerUp or raise ``AdbError``."""
class Phone:
"""adb calls against one phone, with the process runner injectable."""
def __init__(
self,
serial: str = PHONE_SERIAL,
*,
which: Callable[[str], str | None] = shutil.which,
run: Callable[..., Any] = subprocess.run,
) -> None:
"""Pin the phone's serial; ``which``/``run`` are the test seams."""
self.serial = serial
self._which = which
self._run = run
def available(self) -> bool:
"""Whether an ``adb`` binary is on PATH."""
return self._which("adb") is not None
def _adb(self, *args: str, timeout: int = _ADB_TIMEOUT_S) -> str:
cmd = ["adb", *args]
try:
done = self._run(
cmd, capture_output=True, text=True, timeout=timeout, check=False
)
except (OSError, subprocess.TimeoutExpired) as exc:
msg = f"{' '.join(cmd)} did not run: {exc}"
raise AdbError(msg) from exc
if done.returncode:
detail = (done.stdout + done.stderr).strip()
_fail(f"{' '.join(cmd)} exited {done.returncode}: {detail}")
return str(done.stdout)
def _is_phone(self, serial: str) -> bool:
"""Whether an ``adb devices`` entry is the phone.
USB and mDNS serials embed the phone's serial; a plain ``ip:port``
wifi entry does not, so that one is asked for its ``ro.serialno``.
"""
if self.serial in serial:
return True
if ":" not in serial:
return False
try:
asked = self._adb("-s", serial, "shell", "getprop", "ro.serialno")
except AdbError as exc:
_logger.warning("Could not read the serial of %s (%s)", serial, exc)
return False
return asked.strip() == self.serial
def find_device(self) -> Device:
"""The attached phone, over USB or wifi (a wireless serial embeds it)."""
listing = self._adb("devices")
states: list[str] = []
for line in listing.splitlines()[1:]:
serial, _, state = line.partition("\t")
if not self._is_phone(serial):
continue
if state.strip() == "device":
return Device(serial, "attached")
states.append(state.strip())
if states:
return Device(None, f"phone is {'/'.join(states)}, not ready")
return Device(None, f"phone {self.serial} is not attached")
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Whether the package is on the phone (exact ``package:`` line).
``hidden`` adds ``-u`` so an app that focus mode hides or disables
still counts as present; it must not be mistaken for an uninstall.
"""
flag = ["-u"] if hidden else []
out = self._adb("-s", dev, "shell", "pm", "list", "packages", *flag, PACKAGE)
return f"package:{PACKAGE}" in out.split()
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Pull the phone's export folder next to ``final``; return (dir, tcx count).
Pulled into a staging dir and renamed only once every phone ``.tcx``
is on disk, so a half backup never looks like a finished one. The
result is a subfolder, never top-level: a top-level ``*.tcx`` would be
credited by runnerup-watch.
"""
listing = self._adb("-s", dev, "shell", "ls", REMOTE_DIR)
wanted = sum(1 for n in listing.split() if n.endswith(".tcx"))
staging = final.with_name(final.name + ".partial")
shutil.rmtree(staging, ignore_errors=True)
staging.mkdir(parents=True)
self._adb("-s", dev, "pull", REMOTE_DIR, str(staging), timeout=_PULL_TIMEOUT_S)
pulled = staging / Path(REMOTE_DIR).name
got = len(list(pulled.rglob("*.tcx"))) if pulled.is_dir() else -1
if got < wanted:
_fail(f"backup pulled {got} of {wanted} TCX files into {staging}")
target, n = final, 1
while target.exists():
n += 1
target = final.with_name(f"{final.name}-{n}")
pulled.rename(target)
staging.rmdir()
return target, got
def uninstall(self, dev: str) -> None:
"""Uninstall the package and prove it is gone, or raise ``AdbError``."""
try:
out = self._adb("-s", dev, "uninstall", PACKAGE)
except AdbError as exc:
# adb exits 1 with "Failure [DELETE_FAILED_...]": keep that reason
# (a device-owner policy can block it) in the error.
msg = f"uninstall refused: {exc}"
raise AdbError(msg) from exc
if "Success" not in out:
_fail(f"uninstall did not report Success: {out.strip()!r}")
if self.installed(dev, hidden=False):
_fail(f"{PACKAGE} is still listed after uninstall")
_logger.info("Uninstalled %s from %s", PACKAGE, dev)

View File

@ -0,0 +1,62 @@
"""Outcomes of one RunnerUp-retirement pass, and how loudly each is logged."""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import logging
__all__ = ["LEVEL", "Outcome", "RetireResult"]
class Outcome(StrEnum):
"""How a run ended; the value is what the journal shows."""
UNINSTALLED = "uninstalled"
ALREADY_GONE = "already-gone"
ALREADY_DONE = "already-done"
NO_ANCHOR = "no-anchor"
SOURCES_MISSING = "sources-missing"
NOT_DUE = "not-due"
DRY_RUN = "dry-run"
DEVICE_ABSENT = "device-absent"
MARKER_INVALID = "marker-invalid"
ADB_MISSING = "adb-missing"
PHONE_ERROR = "phone-error"
BACKUP_FAILED = "backup-failed"
UNINSTALL_FAILED = "uninstall-failed"
# Level per outcome; the failures also make the unit exit non-zero.
LEVEL = {
Outcome.DEVICE_ABSENT: logging.WARNING,
Outcome.SOURCES_MISSING: logging.WARNING,
Outcome.MARKER_INVALID: logging.WARNING,
Outcome.ADB_MISSING: logging.ERROR,
Outcome.PHONE_ERROR: logging.ERROR,
Outcome.BACKUP_FAILED: logging.ERROR,
Outcome.UNINSTALL_FAILED: logging.ERROR,
}
_NONZERO = frozenset(
{
Outcome.MARKER_INVALID,
Outcome.ADB_MISSING,
Outcome.PHONE_ERROR,
Outcome.BACKUP_FAILED,
Outcome.UNINSTALL_FAILED,
}
)
@dataclass(frozen=True)
class RetireResult:
"""What happened and why, in a sentence a human can act on."""
outcome: Outcome
reason: str
logged: bool = False # the failure was already logged where it was caught
@property
def ok(self) -> bool:
"""False for outcomes the unit should surface as failed."""
return self.outcome not in _NONZERO

View File

@ -0,0 +1,71 @@
"""The retirement's own memory: the anchor, the backup, the done stamp.
One small JSON file (path: ``_runnerup_retire.STATE_FILE``). Written
atomically and only by a real run (``--status`` and ``--dry-run`` never write),
so the file is also the proof that a run happened. The anchor is stored once
and never moved: a later, earlier-looking credit must not push the deadline.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, fields
from datetime import datetime
import json
import logging
import os
from pathlib import Path
import tempfile
_logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class RetireState:
"""What a previous run recorded (all ISO strings, empty until known)."""
anchor_at: str = ""
backup_path: str = ""
done_at: str = ""
done_reason: str = ""
@property
def anchor(self) -> datetime | None:
"""The stored anchor as an aware datetime, or None."""
return datetime.fromisoformat(self.anchor_at) if self.anchor_at else None
def load_state(path: Path) -> RetireState:
"""Read the state; a missing file is a fresh start, a bad one is loud."""
if not path.exists():
return RetireState()
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
_logger.warning(
"Retire state %s is unreadable (%s): starting from scratch, so the "
"anchor is re-derived and the uninstall re-checked",
path,
exc,
)
return RetireState()
if not isinstance(raw, dict):
_logger.warning("Retire state %s is not a JSON object: ignored", path)
return RetireState()
known = {f.name for f in fields(RetireState)}
clean = {k: v for k, v in raw.items() if k in known and isinstance(v, str)}
try:
state = RetireState(**clean)
_ = state.anchor
except ValueError as exc:
_logger.warning("Retire state %s holds a bad anchor (%s): ignored", path, exc)
return RetireState()
return state
def save_state(path: Path, state: RetireState) -> None:
"""Atomically replace the state file (creates the directory on first write)."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".retire-", suffix=".tmp")
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(asdict(state), handle, indent=2)
Path(tmp).replace(path)

View File

@ -0,0 +1,210 @@
"""What the RunnerUp retirement reads off disk: app runs, the marker, the anchor.
Split from :mod:`screen_locker._runnerup_retire` (250-line cap). Everything
here is read-only; nothing touches the phone.
Telling the two sources apart is done on the TCX *content* (``<Author>`` or
``<Creator>`` named ``kuhy workout_app``, the app's ``kRunSourceName``), never
on the file name: the app may name its files however it likes.
The anchor is "when the PC first CREDITED an app run". The credit chokepoint
(``log.json``) stores a run's TCX end as ``completed_at`` on its
``runnerup_verified`` entry and stamps the entry itself with the moment the PC
wrote it. So the anchor is the ``timestamp`` of the entry whose
``completed_at`` equals an app TCX's last trackpoint. Joining on the end time
(not the day) is what makes a same-day RunnerUp run, which fills the day's one
credit slot first, correctly yield no anchor for the app run.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
import json
import logging
import re
from typing import TYPE_CHECKING, Any
from screen_locker._log_io import load_workout_log
from screen_locker._runnerup_tcx import parse_tcx_file
if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
_logger = logging.getLogger(__name__)
APP_SOURCE_NAME = "kuhy workout_app"
_APP_RE = re.compile(
rb"<(?:Author|Creator)\b[^>]*>\s*<Name>\s*"
+ re.escape(APP_SOURCE_NAME.encode())
+ rb"\s*</Name>"
)
# The WebDAV copy of a RunnerUp export may carry the device name
# (RunnerUp_Pixel_6a_2026-...) that the phone's own copy lacks.
_DEVICE_PREFIX = re.compile(r"^RunnerUp_(?:[A-Za-z0-9]+_)*?(?=\d{4}-\d{2}-\d{2}-)")
_END_TOLERANCE_S = 1.0
def run_key(name: str) -> str:
"""A run's identity: its file name without any device-name prefix."""
return _DEVICE_PREFIX.sub("RunnerUp_", name)
def list_tcx(directory: Path) -> list[Path]:
"""Finished ``*.tcx`` files directly in ``directory`` (dotfiles are partial)."""
if not directory.is_dir():
return []
return sorted(
p for p in directory.glob("*.tcx") if p.is_file() and not p.name.startswith(".")
)
def is_app_tcx(path: Path) -> bool:
"""Whether the TCX names the new app as its author or creator."""
try:
data = path.read_bytes()
except OSError as exc:
_logger.warning(
"Cannot read %s (%s): counting it as a RunnerUp file", path, exc
)
return False
return bool(_APP_RE.search(data))
def _ended_at(path: Path) -> float | None:
"""The run's end exactly as the credit path computed it (same parser)."""
data = parse_tcx_file(str(path))
if data is None or data.get("ended_at") is None:
_logger.warning("App TCX %s has no usable end time: it cannot anchor", path)
return None
return float(data["ended_at"])
def _credited_at(entry: dict[str, Any]) -> datetime | None:
try:
stamp = datetime.fromisoformat(str(entry["timestamp"]))
except (KeyError, ValueError) as exc:
_logger.warning("Credit entry has no usable timestamp (%r): skipped", exc)
return None
return stamp if stamp.tzinfo else stamp.astimezone()
def _as_unix(raw: object) -> float | None:
"""A unix time from a number or numeric string (the log stores both)."""
if isinstance(raw, int | float) and not isinstance(raw, bool):
return float(raw)
if isinstance(raw, str) and re.fullmatch(r"\d+(\.\d+)?", raw):
return float(raw)
return None
def _credit_ends(log_file: Path) -> list[tuple[float, datetime]]:
"""``(TCX end, PC credit time)`` of every credited run that recorded its end."""
found: list[tuple[float, datetime]] = []
for entries in load_workout_log(log_file).values():
for entry in entries:
data = entry.get("workout_data") or {}
if data.get("type") != "runnerup_verified":
continue
end = _as_unix(data.get("completed_at"))
if end is None:
continue # an older entry that never stored its run's end
when = _credited_at(entry)
if when is not None:
found.append((end, when))
return found
def app_run_ends(dirs: Iterable[Path]) -> list[float]:
"""The end time of every app-authored TCX that has a usable one."""
return [
end
for directory in dirs
for path in list_tcx(directory)
if is_app_tcx(path) and (end := _ended_at(path)) is not None
]
def find_anchor(log_file: Path, dirs: Iterable[Path]) -> datetime | None:
"""When the PC first credited an app-recorded run, or None if it never did."""
ends = app_run_ends(dirs)
credited = [
when
for run_end, when in _credit_ends(log_file)
if any(abs(run_end - end) <= _END_TOLERANCE_S for end in ends)
]
return min(credited) if credited else None
@dataclass(frozen=True)
class MarkerCheck:
"""Verdict on the app's historic-import marker."""
ok: bool
reason: str
def _bad(reason: str) -> MarkerCheck:
return MarkerCheck(ok=False, reason=reason)
def _marker_names(marker: object) -> tuple[list[str] | None, str]:
"""The marker's ``tcx_names`` if its shape is valid, else a reason."""
if not isinstance(marker, dict):
return None, "marker is not a JSON object"
names, count = marker.get("tcx_names"), marker.get("count")
if not isinstance(marker.get("completed_at"), str) or not marker["completed_at"]:
return None, "marker has no completed_at"
if not isinstance(names, list) or not all(isinstance(n, str) for n in names):
return None, "marker tcx_names is not a list of names"
if isinstance(count, bool) or not isinstance(count, int) or count != len(names):
return None, f"marker count {count!r} != {len(names)} listed names"
if any("/" in n or n.startswith(".") for n in names):
return None, "marker tcx_names must be bare file names"
return names, ""
def _read_marker(marker_file: Path) -> tuple[object, str]:
"""The parsed marker JSON, or ``(None, why it could not be read)``."""
if not marker_file.exists():
why = f"{marker_file} is missing: the app has not imported yet"
else:
try:
return json.loads(marker_file.read_text(encoding="utf-8")), ""
except (OSError, ValueError) as exc:
why = f"{marker_file} is unreadable ({exc})"
_logger.warning("Import marker problem: %s", why)
return None, why
_logger.warning("Import marker problem: %s", why)
return None, why
def _compare(names: list[str], processed: Path) -> MarkerCheck:
listed = {run_key(n) for n in names}
if len(listed) != len(names):
return _bad("marker lists the same run more than once")
have = {run_key(p.name) for p in list_tcx(processed) if not is_app_tcx(p)}
if absent := sorted(listed - have):
return _bad(f"{len(absent)} listed run(s) not in processed/: {absent[:3]}")
if unlisted := sorted(have - listed):
return _bad(
f"{len(unlisted)} RunnerUp run(s) in processed/ are not in the "
f"marker ({unlisted[:3]}): re-run the app's import"
)
return MarkerCheck(ok=True, reason=f"{len(listed)} runs match")
def check_marker(marker_file: Path, processed: Path) -> MarkerCheck:
"""Validate the app's import marker against what ``processed/`` really holds.
Valid means: the file parses, ``count`` equals the number of listed names,
and the listed runs are exactly the RunnerUp-recorded (non-app) runs in
``processed/``. A run is counted once however many copies exist (the
device-prefixed WebDAV twin and the phone-named copy are one run).
"""
marker, why = _read_marker(marker_file)
if why:
return _bad(why)
names, reason = _marker_names(marker)
return _compare(names, processed) if names is not None else _bad(reason)

View File

@ -65,6 +65,11 @@ class RunnerUpTcxMixin:
shutil.rmtree(tmp_dir, ignore_errors=True) shutil.rmtree(tmp_dir, ignore_errors=True)
def _parse_tcx(self, tcx_path: str) -> dict[str, Any] | None: def _parse_tcx(self, tcx_path: str) -> dict[str, Any] | None:
"""Parse a local TCX file (see :func:`parse_tcx_file`)."""
return parse_tcx_file(tcx_path)
def parse_tcx_file(tcx_path: str) -> dict[str, Any] | None:
"""Parse a local TCX file and return activity summary dict. """Parse a local TCX file and return activity summary dict.
Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so

View File

@ -12,31 +12,27 @@ from typing import Any
from screen_locker._constants import ( from screen_locker._constants import (
MIN_RUN_DISTANCE_KM, MIN_RUN_DISTANCE_KM,
MIN_WORKOUT_DURATION_MINUTES,
RUNNERUP_DISTANCE_TOLERANCE, RUNNERUP_DISTANCE_TOLERANCE,
RUNNERUP_EXPORT_DIRS, RUNNERUP_EXPORT_DIRS,
RUNNERUP_WEBDAV_DIRS, RUNNERUP_WEBDAV_DIRS,
WORKOUT_DURATION_ACCEPT_MINUTES,
) )
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._progress_row import record_progress
from screen_locker._runnerup_backfill import RunnerUpBackfillMixin from screen_locker._runnerup_backfill import RunnerUpBackfillMixin
from screen_locker._runnerup_db import RunnerUpDbMixin from screen_locker._runnerup_db import RunnerUpDbMixin
from screen_locker._runnerup_tcx import RunnerUpTcxMixin from screen_locker._runnerup_tcx import RunnerUpTcxMixin
from screen_locker._time_check import check_clock_skew from screen_locker._time_check import check_clock_skew
from screen_locker._walk_tcx import walk_day, walk_shortfall from screen_locker._walk_tcx import (
SPORT_NAMES,
activity_day,
activity_shortfall,
distance_qualifies,
)
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
_SPORT_NAMES: dict[int, str] = { # Kept for importers; the labels live next to the one crediting rule.
0: "Running", _SPORT_NAMES = SPORT_NAMES
1: "Biking",
2: "Other",
3: "Orienteering",
4: "Walking",
5: "Treadmill",
6: "Gym",
7: "Stationary Bike",
}
# TCX uses sport name strings; map back to integer codes for unified validation. # TCX uses sport name strings; map back to integer codes for unified validation.
@ -121,73 +117,48 @@ class RunnerUpVerificationMixin(
) )
return None return None
# Try each file; return the best result (verified > validation error). # One rule for the whole day, whatever the sport or file name: the
# Walks never qualify one file at a time: they are summed below. # day's activities are summed (see _walk_tcx), never judged one file
best: tuple[str, str] | None = None # at a time.
walks: list[dict[str, Any]] = [] activities = [
for remote in exports: data
data = self._pull_and_parse_tcx(remote) for remote in exports
if data is None: if (data := self._pull_and_parse_tcx(remote)) is not None
continue ]
if data.get("walking"): if not activities:
walks.append(data) return (
continue
status, msg = self._validate_runnerup_data(data)
if status == "verified":
return status, msg
if best is None:
best = (status, msg)
if walks:
day = walk_day(walks)
if day.qualifies:
return "verified", day.message()
best = best or ("too_short", walk_shortfall(day))
# All files found but none passed validation.
return best or (
"not_verified", "not_verified",
"RunnerUp TCX export found but could not be read", "RunnerUp TCX export found but could not be read",
) )
day = activity_day(activities)
if day.qualifies:
return "verified", day.message()
# Verified TCX data, real but short: say how far it got (inert row).
record_progress(today, day.metres, day.moving_seconds)
return "too_short", activity_shortfall(day)
def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]: def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]:
"""Validate a RunnerUp activity against configured thresholds. """Validate a RunnerUp activity against configured thresholds.
Returns ``(status, message)`` following the same contract as Returns ``(status, message)`` following the same contract as
``PhoneVerificationMixin._verify_phone_workout``. ``PhoneVerificationMixin._verify_phone_workout``. The one rule is
:func:`screen_locker._walk_tcx.activity_day`; a dict without
``moving_seconds`` (the root-DB path) is judged by its duration.
""" """
sport = data["sport"] day = activity_day([data])
if not day.qualifies:
duration_min = data["duration_seconds"] / 60 return "too_short", activity_shortfall(day)
distance_km = data["distance_m"] / 1000 if day.distance_km < MIN_RUN_DISTANCE_KM and distance_qualifies(
day.distance_km
# Either criterion qualifies the run on its own (see _constants.py). ):
# Distance gets the GPS tolerance (a measurement correction); duration
# gets the shared hidden leeway (a deliberate concession). Different
# reasons, so they stay separate constants.
distance_ok = (
distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
)
duration_ok = duration_min >= WORKOUT_DURATION_ACCEPT_MINUTES
if not distance_ok and not duration_ok:
msg = (
f"Run was {distance_km:.1f} km / {duration_min:.0f} min — need "
f"{MIN_RUN_DISTANCE_KM:g}+ km or {MIN_WORKOUT_DURATION_MINUTES}+ min"
)
return "too_short", msg
if distance_ok and distance_km < MIN_RUN_DISTANCE_KM:
_logger.info( _logger.info(
"RunnerUp distance %.2f km is under the %.1f km minimum but " "RunnerUp distance %.2f km is under the %.1f km minimum but "
"within %.0f%% GPS tolerance — accepted.", "within %.0f%% GPS tolerance — accepted.",
distance_km, day.distance_km,
MIN_RUN_DISTANCE_KM, MIN_RUN_DISTANCE_KM,
RUNNERUP_DISTANCE_TOLERANCE * 100, RUNNERUP_DISTANCE_TOLERANCE * 100,
) )
return "verified", day.message()
sport_name = _SPORT_NAMES.get(sport, str(sport))
return (
"verified",
f"{sport_name}: {distance_km:.1f} km in {duration_min:.0f} min",
)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Main entry point # Main entry point

View File

@ -17,7 +17,6 @@ from screen_locker._constants import (
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import first_minutes, hhmm, span from screen_locker._earned import first_minutes, hhmm, span
from screen_locker._grace_floor import plan_absorb, save_lift from screen_locker._grace_floor import plan_absorb, save_lift
from screen_locker._late_credit import LateCreditMixin
from screen_locker._sick import is_sick from screen_locker._sick import is_sick
from screen_locker._sick_floor import SickFloorMixin from screen_locker._sick_floor import SickFloorMixin
@ -66,22 +65,31 @@ def read_shutdown_config(path: Path) -> tuple[int, int, int] | None:
return values[0], values[1], values[2] return values[0], values[1], values[2]
class ShutdownMixin(SickFloorMixin, LateCreditMixin): class ShutdownMixin(SickFloorMixin):
"""Mixin providing shutdown schedule adjustment functionality.""" """Mixin providing shutdown schedule adjustment functionality."""
def _adjust_shutdown_time_later(self, at: float | None = None) -> bool: def _raise_on_sick_day(self) -> bool:
"""A sick day's credit: raise to the derived target, never add.
The credit's row is already in the target (``_sick_floor``), so adding
its minutes on top would pay it twice. True even when nothing moved
(capped, or already there): the credit is accounted for, and a failed
write is retried by the next tick's sick pass.
"""
self._apply_sick_floor()
return True
def _adjust_shutdown_time_later(self) -> bool:
"""Push shutdown later by the first workout's reward, capped at the ceiling. """Push shutdown later by the first workout's reward, capped at the ceiling.
``at`` is when the workout ended (default now): a late one counts from The reward adds to tonight's shutdown even when the workout ended after
it (:mod:`._late_credit`). Returns True if successful, False otherwise. it (kuhy, 2026-11-18): 18:00 + 2h is 20:00 for a run ending at 19:58,
the same sum the daily reset derives. Returns True if successful.
""" """
day = date.fromisoformat(today_str()) day = date.fromisoformat(today_str())
reward = first_minutes(earned_time.WORKOUT, day) reward = first_minutes(earned_time.WORKOUT, day)
if is_sick(day): if is_sick(day):
return self._raise_on_sick_day(reward, at) return self._raise_on_sick_day()
late = self._late_write(reward, at)
if late is not None:
return late
bonus, lift = plan_absorb(reward) bonus, lift = plan_absorb(reward)
try: try:
config_values = self._read_shutdown_config() config_values = self._read_shutdown_config()
@ -101,24 +109,19 @@ class ShutdownMixin(SickFloorMixin, LateCreditMixin):
save_lift(lift) save_lift(lift)
return ok return ok
def _adjust_shutdown_time_by( def _adjust_shutdown_time_by(self, extra_minutes: int) -> bool:
self, extra_minutes: int, at: float | None = None
) -> bool:
"""Push shutdown later by *extra_minutes*, capped at the day's ceiling. """Push shutdown later by *extra_minutes*, capped at the day's ceiling.
Used for earner and extra-workout bonuses. The cap is Used for earner and extra-workout bonuses. The cap is
``earned_time.shutdown_ceiling_for(today)`` (23:00 today, lower if ``earned_time.shutdown_ceiling_for(today)`` (23:00 today, lower if
``WAKE_MINUTES`` ever moves); the helper's 23:00 stays the hard bound. ``WAKE_MINUTES`` ever moves); the helper's 23:00 stays the hard bound.
``at`` is when the credit was earned (default now): a late one counts Like the workout's, the minutes add to tonight's shutdown whenever the
from it (:mod:`._late_credit`). Returns True if successful. credit was earned. Returns True if successful.
""" """
day = date.fromisoformat(today_str()) day = date.fromisoformat(today_str())
if is_sick(day): if is_sick(day):
return self._raise_on_sick_day(extra_minutes, at) return self._raise_on_sick_day()
late = self._late_write(extra_minutes, at)
if late is not None:
return late
# A stale lift recorded before the grace floor went is spent first. # A stale lift recorded before the grace floor went is spent first.
moved, lift = plan_absorb(extra_minutes) moved, lift = plan_absorb(extra_minutes)
try: try:

View File

@ -6,7 +6,7 @@ accumulating indefinitely across days.
The base and every bonus come from the shared earner registry in force that The base and every bonus come from the shared earner registry in force that
day (``earned_time``, see :mod:`screen_locker._earned`). Nothing here is day (``earned_time``, see :mod:`screen_locker._earned`). Nothing here is
state: the file carries only stamps (``<name>_bonus_date`` for a flat state: the file carries only stamps (``<name>_bonus_minutes`` for a flat
earner, ``<name>_bonus_units`` for a counted gate, :mod:`._gate_bonus`). earner, ``<name>_bonus_units`` for a counted gate, :mod:`._gate_bonus`).
The reset re-derives what today has ALREADY earned and writes base plus that The reset re-derives what today has ALREADY earned and writes base plus that
@ -37,7 +37,6 @@ from screen_locker._day import today_str
from screen_locker._earned import ( from screen_locker._earned import (
counted_gate_earners, counted_gate_earners,
earned_today, earned_today,
first_credit_time,
first_credits, first_credits,
first_minutes, first_minutes,
flat_earners, flat_earners,
@ -45,7 +44,13 @@ from screen_locker._earned import (
registry, registry,
span, span,
) )
from screen_locker._gate_bonus import apply_counted_bonus, date_stamp, reset_stamps from screen_locker._earned_progress import term_minutes
from screen_locker._gate_bonus import (
applied_minutes,
apply_counted_bonus,
minutes_stamp,
reset_stamps,
)
from screen_locker._grace_floor import save_lift from screen_locker._grace_floor import save_lift
from screen_locker._log_io import load_workout_log from screen_locker._log_io import load_workout_log
from screen_locker._shutdown_target import gather from screen_locker._shutdown_target import gather
@ -194,20 +199,19 @@ def _apply_flat_bonus(
mixin: object, mixin: object,
earner: earned_time.Earner, earner: earned_time.Earner,
) -> bool: ) -> bool:
"""Push shutdown later by one earner's once-per-day time, if it is earned. """Push shutdown later by what one earner's bonus has earned beyond its stamp.
The daily reset only sees a bonus earned before it ran; this is the live What it has earned is ``earned_time``'s
counterpart for the usual case, where the solve or the reading lands (:func:`~screen_locker._earned_progress.term_minutes`); only the rise over
hours later and is picked up by the next timer tick. Idempotent through :func:`applied_minutes` goes out: never twice, never a claw-back.
the earner's stamp in *state_file*, which the reset sets as well when it Returns True if minutes were applied on this call.
already included the bonus.
Returns True if the bonus was applied on this call.
""" """
today = today_str() today = today_str()
day = date.fromisoformat(today)
state = _load_state(state_file) state = _load_state(state_file)
stamp = date_stamp(earner) full = first_minutes(earner, day)
if state.get(stamp) == today: applied = applied_minutes(state, earner, today, full)
if applied >= full:
return False return False
answer = earned_today(earner) answer = earned_today(earner)
if answer is None: if answer is None:
@ -215,15 +219,13 @@ def _apply_flat_bonus(
"%s state could not be checked; no shutdown time for it", earner.label "%s state could not be checked; no shutdown time for it", earner.label
) )
return False return False
if not answer: pay_now = term_minutes(earner, day, answer=answer)
if (minutes := pay_now - applied) <= 0:
return False return False
day = date.fromisoformat(today) if not mixin._adjust_shutdown_time_by(minutes):
minutes = first_minutes(earner, day)
# Anchored on the credit's own row, so a late solve counts from its time.
if not mixin._adjust_shutdown_time_by(minutes, at=first_credit_time(earner, day)):
_logger.warning("%s bonus: failed to write shutdown config.", earner.label) _logger.warning("%s bonus: failed to write shutdown config.", earner.label)
return False return False
state[stamp] = today state[minutes_stamp(earner)] = {"date": today, "minutes": pay_now}
_save_state(state_file, state) _save_state(state_file, state)
_logger.info("%s bonus: +%s shutdown time today.", earner.label, span(minutes)) _logger.info("%s bonus: +%s shutdown time today.", earner.label, span(minutes))
return True return True

View File

@ -7,8 +7,8 @@
target = earned_time.resolve(answers, sick=...) # base + every earner, capped; target = earned_time.resolve(answers, sick=...) # base + every earner, capped;
# sick: 20:00 + gaming pay # sick: 20:00 + gaming pay
A late credit (``_late_credit``) is live-only: it restarts tonight from its own Every live credit adds its minutes to tonight's config, whenever it lands
time, and the next day's reset re-derives from scratch. (2026-11-18), so the live config equals this sum until the next reset.
A declared rest day answers the workout with at least one unit, i.e. its A declared rest day answers the workout with at least one unit, i.e. its
first-unit bonus; a real workout on top of it earns only what a further unit first-unit bonus; a real workout on top of it earns only what a further unit
@ -18,11 +18,12 @@ earns. :func:`gather` reads today's real inputs; it writes nothing.
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import TYPE_CHECKING from typing import TYPE_CHECKING, Any
import earned_time import earned_time
from screen_locker._earned import first_credits, gate_answers, registry from screen_locker._earned import first_credits, gate_answers, registry
from screen_locker._earned_progress import progress_for
from screen_locker._grace_floor import first_done_at from screen_locker._grace_floor import first_done_at
from screen_locker._log_io import load_workout_log from screen_locker._log_io import load_workout_log
from screen_locker._rest_day import is_rest_day from screen_locker._rest_day import is_rest_day
@ -91,6 +92,9 @@ class DayInputs:
first_credits: Each penalised gate's first real credit first_credits: Each penalised gate's first real credit
(:func:`~screen_locker._earned.first_credits`); ``None`` resolves (:func:`~screen_locker._earned.first_credits`); ``None`` resolves
on ``penalty_from`` alone, as before earned_time 0.6. on ``penalty_from`` alone, as before earned_time 0.6.
progress: Each gate's signed "done N of M" for the day
(:func:`~screen_locker._earned_progress.progress_for`); a no
then pays that share. ``None`` pays by yes/no, as before 0.24.
""" """
day: date day: date
@ -100,6 +104,7 @@ class DayInputs:
first_done: float | None = None first_done: float | None = None
sick_day: bool = False sick_day: bool = False
first_credits: Mapping[str, date | None] | None = None first_credits: Mapping[str, date | None] | None = None
progress: Mapping[str, earned_time.Progress] | None = None
def derive(inputs: DayInputs) -> Target: def derive(inputs: DayInputs) -> Target:
@ -114,11 +119,13 @@ def derive(inputs: DayInputs) -> Target:
earners = registry(day) earners = registry(day)
starts = inputs.first_credits starts = inputs.first_credits
sick = inputs.sick_day sick = inputs.sick_day
resolution = ( # Only what is set is passed: an older earned_time has no such keyword.
earned_time.resolve(answers, day, earners, sick=sick) extra: dict[str, Any] = {}
if starts is None if starts is not None:
else earned_time.resolve(answers, day, earners, first_credits=starts, sick=sick) extra["first_credits"] = starts
) if inputs.progress:
extra["progress"] = inputs.progress
resolution = earned_time.resolve(answers, day, earners, sick=sick, **extra)
return Target( return Target(
resolution=resolution, resolution=resolution,
rest_day=inputs.rest_day, rest_day=inputs.rest_day,
@ -147,6 +154,7 @@ def gather_inputs(day: date, log_file: Path | None) -> DayInputs:
first_done=first_done_at(day, log_file, rest_day=rest_day), first_done=first_done_at(day, log_file, rest_day=rest_day),
sick_day=is_sick(day), sick_day=is_sick(day),
first_credits=first_credits(registry(day), day), first_credits=first_credits(registry(day), day),
progress=progress_for(day),
) )

View File

@ -28,6 +28,7 @@ from screen_locker._decision_log import (
) )
from screen_locker._degraded_sources import degraded_sources from screen_locker._degraded_sources import degraded_sources
from screen_locker._extra_benefits import process_week_transition from screen_locker._extra_benefits import process_week_transition
from screen_locker._hold import skip_during_hold
from screen_locker._lock_invariant import refuse_to_lock_over_logged_workout from screen_locker._lock_invariant import refuse_to_lock_over_logged_workout
from screen_locker._night_lockdown import skip_after_evening_lockdown from screen_locker._night_lockdown import skip_after_evening_lockdown
from screen_locker._shutdown_base import ( from screen_locker._shutdown_base import (
@ -125,7 +126,8 @@ class StartupChecksMixin(SyncMixin):
# before any early-exit check, so gaps are closed regardless of today's # before any early-exit check, so gaps are closed regardless of today's
# logged state (early_bird, sick_day, etc.). # logged state (early_bird, sick_day, etc.).
self._auto_fill_week_runnerup_bonus() self._auto_fill_week_runnerup_bonus()
if self._check_today_state_exits(): # Test hold: no prompt/lock/heat dialog; bookkeeping above is untouched.
if self._check_today_state_exits() or skip_during_hold(self._record_skip):
return return
# Day-of-week routing: Tue/Wed/Thu relaxed (optional), Fri-Mon enforced. # Day-of-week routing: Tue/Wed/Thu relaxed (optional), Fri-Mon enforced.
if is_relaxed_day(): if is_relaxed_day():
@ -158,7 +160,7 @@ class StartupChecksMixin(SyncMixin):
# there is no banked "skip a workout" credit — that mechanic works # there is no banked "skip a workout" credit — that mechanic works
# against the goal of maximizing weekly workouts, so it was removed. # against the goal of maximizing weekly workouts, so it was removed.
# A logged workout outranks every rung above, whatever their order. # A logged workout outranks every rung above, whatever their order.
# Then: once tonight's lockdown fired (a late credit may have lifted # Then: once tonight's lockdown fired (a credit may have lifted
# it), never re-arm behind the workout gate the same evening. # it), never re-arm behind the workout gate the same evening.
if refuse_to_lock_over_logged_workout( if refuse_to_lock_over_logged_workout(
self.has_logged_today, self._record_skip self.has_logged_today, self._record_skip

View File

@ -6,14 +6,19 @@ mixins, so the class's public surface is unchanged.
Every method here is display-only: it reads the snapshot it is handed and Every method here is display-only: it reads the snapshot it is handed and
paints widgets. Nothing in this module writes to disk or reaches the network. paints widgets. Nothing in this module writes to disk or reaches the network.
textgate: no section has a heading or a sentence any more. Each is one or
two lines of glyphs (``_glyphs``) and numbers, coloured by state. Weekdays
are positions in a Mon..Sun row, not names.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._earned import hhmm from screen_locker._earned import hhmm
from screen_locker._sync_status import format_sync_line, gather_sync_status from screen_locker._sync_status import gather_sync_status
if TYPE_CHECKING: if TYPE_CHECKING:
import tkinter as tk import tkinter as tk
@ -30,56 +35,46 @@ if TYPE_CHECKING:
class StatusSectionsMixin: class StatusSectionsMixin:
"""Renders each section of the status window from a snapshot.""" """Renders each section of the status window from a snapshot."""
def _day_cell(self, day: DayStatus) -> str:
"""One day as a glyph: its entries, sick, or an empty circle."""
if day.entry_types:
return g.entry_glyphs(day.entry_types)
return g.WEEK_SICK if day.is_sick_day else g.WEEK_EMPTY
def _section_today(self, parent: tk.Widget, day: DayStatus) -> None: def _section_today(self, parent: tk.Widget, day: DayStatus) -> None:
"""Render today's outcome.""" """Render today's outcome (was "✓ Today (Wed Nov 11): phone_verified")."""
del parent del parent
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "—") mark = g.OK if day.counted else (g.SICK if day.is_sick_day else g.FAIL)
entry_str = ", ".join(day.entry_types) or ( self._label(
"sick day" if day.is_sick_day else "no entry yet" f"{mark} {self._day_cell(day)}",
) role="title",
self._text(
f"{mark} Today ({day.label}): {entry_str}",
role="body",
color=self._colors.palette.success color=self._colors.palette.success
if day.counted if day.counted
else self._colors.palette.warning, else self._colors.palette.warning,
) )
if day.source:
# Secondary provenance note on an already-shown entry -- a
# deliberately caption-sized exception to the 16px floor.
self._text(
day.source, role="caption", color=self._colors.palette.muted, pad="xs"
)
def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None: def _section_week(self, parent: tk.Widget, week: WeeklySummary) -> None:
"""Render this ISO week's per-day breakdown and totals.""" """Render this ISO week: dots + count, then one cell per day.
Was "This Week: 2/4", a "Mon Nov 09: no entry" line per day and "Need
2 more this week." / "1 above the weekly minimum!".
"""
del parent del parent
self._label( enough = week.remaining <= 0
f"This Week: {week.counted_count}/{week.minimum}", role="body", pad="sm" self._text(
) g.dots(week.counted_count, week.minimum),
for day in week.days: role="title",
mark = "✓" if day.counted else ("😷" if day.is_sick_day else "·") color=self._colors.palette.success
entry_str = ", ".join(day.entry_types) or ( if enough
"sick day" if day.is_sick_day else "no entry" else self._colors.palette.warning,
pad="sm",
) )
self._text( self._text(
f"{mark} {day.label}: {entry_str}", " ".join(self._day_cell(day) for day in week.days),
role="body", role="body",
color=self._colors.palette.muted, color=self._colors.palette.muted,
pad="xs", pad="xs",
) )
if week.remaining > 0:
self._text(
f"Need {week.remaining} more this week.",
role="body",
color=self._colors.palette.warning,
)
elif week.extra > 0:
self._text(
f"{week.extra} above the weekly minimum!",
role="body",
color=self._colors.palette.success,
)
def _section_streak( def _section_streak(
self, parent: tk.Widget, streak: int, week_rewards: tuple[str, ...] = () self, parent: tk.Widget, streak: int, week_rewards: tuple[str, ...] = ()
@ -87,29 +82,23 @@ class StatusSectionsMixin:
"""Render the consecutive 5+-workout-week streak and this week's reward. """Render the consecutive 5+-workout-week streak and this week's reward.
Display only, and exactly the stored values (``extra_benefits_state``): Display only, and exactly the stored values (``extra_benefits_state``):
a streak of 0 is said plainly, never padded or rounded up. Nothing here a streak of 0 is shown as 0, never padded or rounded up. Nothing here
grants time or relaxes a lock. The early-bird extension is not shown: grants time or relaxes a lock. Was "🔥 N-week streak (5+ workouts a
it no longer changes anything (wake-alarm owns early bird). week)" / "No streak yet: ..." and the reward sentences.
""" """
del parent del parent
self._label("Workout streak", role="body", pad="sm")
if streak > 0:
self._text( self._text(
f"🔥 {streak}-week streak (5+ workouts a week)", f"{g.STREAK * min(streak, 10)} {streak}" if streak else f"{g.STREAK} 0",
role="body", role="body",
color=self._colors.palette.success, color=self._colors.palette.success
) if streak
else: else self._colors.palette.muted,
self._text(
"No streak yet: 5+ workouts in a week starts one.",
role="body",
color=self._colors.palette.muted,
) )
for message in week_rewards: for message in week_rewards:
# A reset is news, not a celebration: it must not be painted green. # A reset is news, not a celebration: it must not be painted green.
lost = message.startswith("Streak reset") lost = message.startswith("Streak reset")
self._text( self._text(
message, f"{g.STREAK}{g.FAIL}" if lost else f"{g.STREAK}{g.GIFT}",
role="body", role="body",
color=self._colors.palette.warning color=self._colors.palette.warning
if lost if lost
@ -119,32 +108,30 @@ class StatusSectionsMixin:
def _section_lock_explanation( def _section_lock_explanation(
self, parent: tk.Widget, expl: LockExplanation self, parent: tk.Widget, expl: LockExplanation
) -> None: ) -> None:
"""Render why the lock did/didn't fire today, plus its evaluation trace.""" """Render whether the lock fired today and the stage that decided it.
Was "Why the lock did/didn't fire" over the stage's sentence.
"""
del parent del parent
self._label("Why the lock did/didn't fire", role="body", pad="sm") square = g.LOCK if expl.fired else g.UNLOCK
self._text( self._text(
expl.reason, f"{square} {g.STAGE_GLYPH.get(expl.stage, '')}".rstrip(),
role="body", role="title",
color=self._colors.palette.danger color=self._colors.palette.danger
if expl.fired if expl.fired
else self._colors.palette.success, else self._colors.palette.success,
) )
if expl.auto_upgrade.would_attempt: if expl.auto_upgrade.would_attempt:
self._text( self._text(g.RETRY, role="label", color=self._colors.palette.warning)
f"Pending auto-upgrade: {expl.auto_upgrade.reason}",
role="label",
color=self._colors.palette.warning,
)
def _section_manual_workout_budget( def _section_manual_workout_budget(
self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus self, parent: tk.Widget, manual: ManualWorkoutBudgetStatus
) -> None: ) -> None:
"""Render rolling manual-workout budget usage.""" """Render rolling manual-workout budget usage (7-day, then 30-day)."""
del parent del parent
self._label("Manual Workout Budget", role="body", pad="sm")
self._text( self._text(
f"{manual.used_7d}/{manual.budget_7d} week · " f"{g.FORM} {manual.used_7d}/{manual.budget_7d} · "
f"{manual.used_30d}/{manual.budget_30d} month", f"{manual.used_30d}/{manual.budget_30d}",
role="body", role="body",
color=self._colors.palette.danger color=self._colors.palette.danger
if manual.exhausted if manual.exhausted
@ -152,7 +139,7 @@ class StatusSectionsMixin:
) )
def _section_sync_backend(self, parent: tk.Widget) -> None: def _section_sync_backend(self, parent: tk.Widget) -> None:
"""Render which backend this machine syncs through. """Render whether this machine's sync is healthy, and its peer count.
Read from local state only (see :mod:`screen_locker._sync_status`), so Read from local state only (see :mod:`screen_locker._sync_status`), so
opening or refreshing the window never makes a network call. Coloured opening or refreshing the window never makes a network call. Coloured
@ -162,9 +149,8 @@ class StatusSectionsMixin:
""" """
del parent del parent
status = gather_sync_status() status = gather_sync_status()
self._label("Sync backend", role="body", pad="sm")
self._text( self._text(
format_sync_line(status), f"{g.SYNC} {g.OK if status.healthy else g.FAIL} {status.peer_count}",
role="body", role="body",
color=self._colors.palette.muted color=self._colors.palette.muted
if status.healthy if status.healthy
@ -174,41 +160,25 @@ class StatusSectionsMixin:
def _section_shutdown( def _section_shutdown(
self, parent: tk.Widget, shutdown: ShutdownProjection self, parent: tk.Widget, shutdown: ShutdownProjection
) -> None: ) -> None:
"""Render tonight's live config, rest-of-week, and next-week preview.""" """Render tonight's live config, rest-of-week, and next-week preview.
Was "Live config — Mon-Wed 21:00, Thu-Sun 22:00", "Rest of week: Mon
21:00, ...", "Next week (speculative): ..." and an explanation. Now
the times only, in day order: live config bold, the rest muted.
"""
del parent del parent
self._label("Shutdown Time", role="body", pad="sm")
if shutdown.tonight is not None: if shutdown.tonight is not None:
mon_wed, thu_sun, _morning = shutdown.tonight mon_wed, thu_sun, _morning = shutdown.tonight
self._text( self._text(f"{g.SHUTDOWN} {hhmm(mon_wed)} · {hhmm(thu_sun)}", role="title")
f"Live config — Mon-Wed {hhmm(mon_wed)}, Thu-Sun {hhmm(thu_sun)}",
role="body",
)
else: else:
self._text( self._text(
"Live shutdown config unavailable.", f"{g.SHUTDOWN} {g.FAIL}",
role="body", role="title",
color=self._colors.palette.warning, color=self._colors.palette.warning,
) )
# Rest-of-week/next-week/explanation are speculative annotations, not for days in (shutdown.rest_of_week, shutdown.next_week_preview):
# the section's primary content -- a deliberate caption-sized
# exception to the 16px floor, all sharing one muted tone instead of
# three unrelated ad hoc grays.
rest_line = ", ".join(
f"{d.label} {hhmm(d.minutes)}" for d in shutdown.rest_of_week
)
self._text( self._text(
f"Rest of week: {rest_line}", " ".join(hhmm(d.minutes) for d in days),
role="caption", role="caption",
color=self._colors.palette.muted, color=self._colors.palette.muted,
) )
next_line = ", ".join(
f"{d.label} {hhmm(d.minutes)}" for d in shutdown.next_week_preview
)
self._text(
f"Next week (speculative): {next_line}",
role="caption",
color=self._colors.palette.muted,
)
self._text(
shutdown.explanation, role="caption", color=self._colors.palette.muted
)

View File

@ -11,10 +11,12 @@ from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date from datetime import date
import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import earned_time import earned_time
from screen_locker import _glyphs as g
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import extra_minutes, span from screen_locker._earned import extra_minutes, span
from screen_locker._status_data import gather_status from screen_locker._status_data import gather_status
@ -29,6 +31,9 @@ if TYPE_CHECKING:
from screen_locker._workout_credit import WorkoutCreditResult from screen_locker._workout_credit import WorkoutCreditResult
_logger = logging.getLogger(__name__)
@dataclass(frozen=True) @dataclass(frozen=True)
class PhoneCheckOutcome: class PhoneCheckOutcome:
"""Result of the "Check Phone" button's verify-then-backfill chain. """Result of the "Check Phone" button's verify-then-backfill chain.
@ -73,7 +78,9 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
workout above the weekly minimum); it is a separate source with its own workout above the weekly minimum); it is a separate source with its own
dedup and is out of scope for the RunnerUp credit fix. dedup and is out of scope for the RunnerUp credit fix.
Returns a human-readable summary if anything was filled, else ``None``. Returns a glyph summary if anything was filled, else ``None``:
``↻●━━● +N`` and, with a bonus, `` ⏻ +1h`` (textgate; was "Auto-filled
N workouts from earlier this week. +1h shutdown time.").
""" """
prev_count = count_weekly_workouts(verifier.log_file) prev_count = count_weekly_workouts(verifier.log_file)
filled = verifier._scan_and_fill_week_runnerup( filled = verifier._scan_and_fill_week_runnerup(
@ -93,10 +100,9 @@ def _backfill_week_and_apply_bonus(verifier: ScreenLocker) -> str | None:
filled += sl_filled filled += sl_filled
if not filled: if not filled:
return None return None
plural = "workout" if filled == 1 else "workouts" message = f"{g.RETRY}{g.LIFT} +{filled}"
message = f"Auto-filled {filled} {plural} from earlier this week."
if bonus > 0: if bonus > 0:
message += f" +{span(bonus)} shutdown time." message += f" {g.SHUTDOWN} +{span(bonus)}"
return message return message
@ -184,10 +190,8 @@ class PhoneCheckMixin:
if outcome.credited_type == "runnerup_verified" if outcome.credited_type == "runnerup_verified"
else outcome.phone_message else outcome.phone_message
) )
source_label = ( source_glyph = (
"RunnerUp" g.RUN if outcome.credited_type == "runnerup_verified" else g.LIFT
if outcome.credited_type == "runnerup_verified"
else "StrongLifts"
) )
verifier = self.verifier_factory(self.log_file) verifier = self.verifier_factory(self.log_file)
verifier.workout_data = { verifier.workout_data = {
@ -196,24 +200,27 @@ class PhoneCheckMixin:
} }
credit = verifier._apply_workout_credit() credit = verifier._apply_workout_credit()
self._credit_message = "\n".join( self._credit_message = "\n".join(
self._credit_result_lines(f"{source_label} verified: {message}", credit) self._credit_result_lines(f"{source_glyph} {g.OK}", credit)
) )
elif outcome.week_fill_message is not None: elif outcome.week_fill_message is not None:
self._credit_message = outcome.week_fill_message self._credit_message = outcome.week_fill_message
else: else:
# The reasons are logged; the window shows the failure glyphs.
_logger.warning(
"Check Phone found nothing: StrongLifts: %s · RunnerUp: %s",
outcome.phone_message,
outcome.runnerup_message,
)
self._phone_check_result = ( self._phone_check_result = (
outcome.status, outcome.status,
( f"{g.LIFT}{g.FAIL} {g.RUN}{g.FAIL}",
f"StrongLifts: {outcome.phone_message} · "
f"RunnerUp: {outcome.runnerup_message}"
),
) )
self.render(gather_status()) self.render(gather_status())
def _credit_result_lines( def _credit_result_lines(
self, header: str, credit: WorkoutCreditResult self, header: str, credit: WorkoutCreditResult
) -> list[str]: ) -> list[str]:
"""Human-readable outcome lines for an applied workout credit. """Glyph outcome lines for an applied workout credit (no words).
Shared by the "Check Phone" verify path and the "Log Manual Workout" Shared by the "Check Phone" verify path and the "Log Manual Workout"
path so both report the reward identically: the base +2h shutdown push path so both report the reward identically: the base +2h shutdown push
@ -223,12 +230,11 @@ class PhoneCheckMixin:
""" """
lines = [header] lines = [header]
if credit.already_counted_today: if credit.already_counted_today:
lines.append("(Already recorded today — no additional credit.)") # Was "(Already recorded today — no additional credit.)".
lines.append(f"{g.OK}{g.OK} {g.GIFT}0")
return lines return lines
if credit.shutdown_adjusted: if credit.shutdown_adjusted:
lines.append("Shutdown time +2h later!") lines.append(f"{g.SHUTDOWN} {g.GIFT}{span(120)}")
if credit.extra_bonus_delta > 0: if credit.extra_bonus_delta > 0:
lines.append( lines.append(f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}")
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight"
)
return lines return lines

View File

@ -15,8 +15,10 @@ writes to ``log.json``. Host class must provide:
from __future__ import annotations from __future__ import annotations
import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD from screen_locker._constants import HEAT_SKIP_CITY, HEAT_SKIP_TEMP_THRESHOLD
from screen_locker._temperature import HARD_TIMEOUT_SECONDS, submit_background from screen_locker._temperature import HARD_TIMEOUT_SECONDS, submit_background
@ -25,53 +27,44 @@ if TYPE_CHECKING:
from screen_locker._temperature import TemperatureCheck from screen_locker._temperature import TemperatureCheck
_logger = logging.getLogger(__name__)
class TemperatureStatusMixin: class TemperatureStatusMixin:
"""Provides the background Warsaw-temperature fetch/poll/render.""" """Provides the background Warsaw-temperature fetch/poll/render."""
def _section_temperature(self, parent: tk.Widget) -> None: def _section_temperature(self, parent: tk.Widget) -> None:
"""Render the live Warsaw temperature. """Render the live temperature against the heat-skip threshold.
The same reading the real locker's heat-skip check would see, The same reading the real locker's heat-skip check would see,
fetched in the background. fetched in the background. textgate: was "Warsaw Temperature" and a
sentence per state; now ``▲`` with the reading (or wait / clock-fail /
fail glyphs), danger-coloured with ``↷`` when it would heat-skip.
""" """
del parent del parent
self._label("Warsaw Temperature", role="body", pad="sm")
result = self._temp_result result = self._temp_result
palette = self._colors.palette
if result is None: if result is None:
self._text( self._text(f"{g.HEAT} {g.WAIT}", role="body", color=palette.muted)
"Checking Warsaw temperature…",
role="caption",
color=self._colors.palette.muted,
)
return return
if result.timed_out: if result.timed_out:
_logger.warning(
"Temperature check timed out after ~%ds", int(HARD_TIMEOUT_SECONDS)
)
self._text( self._text(
f"Warsaw temperature check timed out after ~" f"{g.HEAT} {g.CLOCK}{g.FAIL}", role="body", color=palette.warning
f"{int(HARD_TIMEOUT_SECONDS)}s — network may be down.",
role="caption",
color=self._colors.palette.warning,
) )
return return
if result.temp_celsius is None: if result.temp_celsius is None:
self._text( self._text(f"{g.HEAT} {g.FAIL}", role="body", color=palette.warning)
"Warsaw temperature check failed (network/API error).",
role="caption",
color=self._colors.palette.warning,
)
return return
hot = result.temp_celsius >= HEAT_SKIP_TEMP_THRESHOLD hot = result.temp_celsius >= HEAT_SKIP_TEMP_THRESHOLD
relation = "≥" if hot else "<"
self._text( self._text(
f"Warsaw: {result.temp_celsius:.0f}°C (heat-skip threshold " f"{g.HEAT} {result.temp_celsius:.0f}°C {relation} "
f"{HEAT_SKIP_TEMP_THRESHOLD}°C)", f"{HEAT_SKIP_TEMP_THRESHOLD}°C" + (f" {g.SKIP}" if hot else ""),
role="caption", role="body",
color=self._colors.palette.warning if hot else self._colors.palette.muted, color=palette.danger if hot else palette.muted,
)
if hot:
self._text(
"Would trigger heat-skip today.",
role="caption",
color=self._colors.palette.danger,
) )
def _start_temperature_check(self) -> None: def _start_temperature_check(self) -> None:

47
screen_locker/_tooltip.py Normal file
View File

@ -0,0 +1,47 @@
"""One-word hover tooltips for glyph-only Tk buttons (textgate tooltip exception).
kuhy allows ONE word naming what an icon means, shown only on hover. The tip
is a Label placed inside the button's own window on <Enter> and destroyed on
<Leave> or a click, so no screen paints it until the pointer is on the button.
Not a Toplevel: on a lock surface gatelock's recovery tick disowns any popup
window within a second (see tests/test_no_popup_widgets.py), so the tip has
to live in the same window as the button it names.
"""
from __future__ import annotations
import tkinter as tk
from screen_locker import _glyphs as g
_OFFSET = 16 # px below-right of the pointer, so the tip never covers it
def tooltip_word(glyph_text: str) -> str | None:
"""Return the hover word for a button's glyph text, or None to skip it."""
return g.TOOLTIP.get(glyph_text)
def attach_tooltip(widget: tk.Widget, word: str) -> None:
"""Show ``word`` beside the pointer while it hovers ``widget``."""
tip: list[tk.Label] = []
def show(event: tk.Event) -> None:
hide(event)
window = widget.winfo_toplevel()
label = tk.Label(window, text=word)
label.place(
x=event.x_root - window.winfo_rootx() + _OFFSET,
y=event.y_root - window.winfo_rooty() + _OFFSET,
)
label.lift()
tip.append(label)
def hide(_event: tk.Event) -> None:
while tip:
tip.pop().destroy()
widget.bind("<Enter>", show, add="+")
widget.bind("<Leave>", hide, add="+")
widget.bind("<ButtonPress>", hide, add="+")

View File

@ -1,11 +1,20 @@
"""UI flow methods mixin for the screen locker.""" """UI flow methods mixin for the screen locker.
textgate: every screen here is glyphs (``_glyphs``) plus numbers, with the
palette colour as the second channel. The sentences these screens used to
paint ("No Workout Found", the verifier's reason, the sync diagnosis) go to
the log at warning instead, so the reason is never lost, only unpainted.
"""
from __future__ import annotations from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker import _manual_workout from screen_locker import _manual_workout
from screen_locker._credit_watch import CreditStandDownMixin
from screen_locker._source_health import collect_source_findings, explain_findings from screen_locker._source_health import collect_source_findings, explain_findings
from screen_locker._ui_flows_lockout import LockoutFlowMixin from screen_locker._ui_flows_lockout import LockoutFlowMixin
from screen_locker._ui_flows_sick import SickDayFlowMixin from screen_locker._ui_flows_sick import SickDayFlowMixin
@ -14,8 +23,12 @@ from screen_locker._ui_flows_sick_panel import SickPanelFlowMixin
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
_logger = logging.getLogger(__name__)
class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
class UIFlowsMixin(
SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin, CreditStandDownMixin
):
"""Mixin providing UI flow logic for the screen locker. """Mixin providing UI flow logic for the screen locker.
The sick-day and lockout/penalty flows live in sibling modules and are The sick-day and lockout/penalty flows live in sibling modules and are
@ -28,18 +41,28 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
Split from :meth:`_start_phone_check` so the fit check Split from :meth:`_start_phone_check` so the fit check
(``scripts/verify_screen_fits.py``) can measure this screen without (``scripts/verify_screen_fits.py``) can measure this screen without
starting a background thread that talks to a phone over adb. starting a background thread that talks to a phone over adb.
Was "Checking phone..." / "Looking for today's workout in StrongLifts".
""" """
self.clear_container() self.clear_container()
self._label( self._label(
"Checking phone...", f"{g.PHONE} {g.LIFT}",
role="display", role="display",
color=self._colors.palette.warning, color=self._colors.palette.warning,
pad="lg", pad="lg",
) )
self._text("Looking for today's workout in StrongLifts...", role="body") self._text(g.WAIT, role="display", color=self._colors.palette.muted)
def _start_phone_check(self) -> None: def _start_phone_check(self) -> None:
"""Check phone for today's workout immediately at startup.""" """Check phone for today's workout immediately at startup.
Also the TRY AGAIN path. Another process (the stream daemon, a manual
log) may have credited today since the window opened; the log is
authoritative, so that closes the window instead of asking the phone
-- a StrongLifts "stale" verdict must never outrank a logged workout.
"""
if self.has_logged_today():
self._stand_down_for_credit()
return
self.paint_phone_check() self.paint_phone_check()
executor = ThreadPoolExecutor(max_workers=1) executor = ThreadPoolExecutor(max_workers=1)
self._phone_future = executor.submit(self._verify_phone_workout) self._phone_future = executor.submit(self._verify_phone_workout)
@ -54,23 +77,39 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
else: else:
self.root.after(500, self._poll_phone_check) self.root.after(500, self._poll_phone_check)
def _show_retry_and_sick(self, message: str) -> None: def _show_retry_and_sick(self, message: str, *, status: str = "") -> None:
"""Show TRY AGAIN, I'm sick and (budget allowing) the manual log.""" """Show retry, I'm sick and (budget allowing) the manual log.
Was "No Workout Found" over *message*. The screen now shows the
failure glyph for *status*; *message* goes to the log.
"""
_logger.warning("No workout accepted (%s): %s", status or "?", message)
self.clear_container() self.clear_container()
self._label( self._label(
"No Workout Found", f"{g.LIFT} {g.FAIL}",
role="display", role="display",
color=self._colors.palette.danger, color=self._colors.palette.danger,
pad="md", pad="md",
) )
self._text(message, color=self._colors.palette.warning) if status:
self._text(
g.status_glyph(status),
role="display",
color=self._colors.palette.warning,
)
# Never accuse the user of skipping a workout the machine simply could # Never accuse the user of skipping a workout the machine simply could
# not see. On 2026-08-24 this screen said "No Workout Found" after a # not see. On 2026-08-24 this screen said "No Workout Found" after a
# 1h57m session, because Firebase was unreadable and the GitHub mirror # 1h57m session, because Firebase was unreadable and the GitHub mirror
# had been stale for nine days -- neither of which was shown here. # had been stale for nine days -- neither of which was shown here.
diagnosis = explain_findings(collect_source_findings()) # Now a sync-fault glyph, one per finding; the prose is logged.
if diagnosis: findings = collect_source_findings()
self._text(diagnosis, color=self._colors.palette.muted) if findings:
_logger.warning("%s", explain_findings(findings))
self._text(
f"{g.SYNC}{g.FAIL} " * len(findings),
role="title",
color=self._colors.palette.warning,
)
self._text( self._text(
_manual_workout.budget_summary(self.log_file), _manual_workout.budget_summary(self.log_file),
color=self._colors.palette.muted, color=self._colors.palette.muted,
@ -78,44 +117,47 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
frame = self._button_row() frame = self._button_row()
self._button( self._button(
frame, frame,
"TRY AGAIN", g.RETRY,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._start_phone_check, command=self._start_phone_check,
width=12, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
self._sick_button(frame) self._sick_button(frame)
if self._mw_budget_closed(): if self._mw_budget_closed():
self._text( # Was "Manual-workout budget exhausted. No manual-log option".
"Manual-workout budget exhausted. No manual-log option available.", self._text(f"{g.FORM} {g.CLOSE}", color=self._colors.palette.danger)
color=self._colors.palette.danger,
)
else: else:
self._button( self._button(
frame, frame,
"Log Manual Workout", g.FORM,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._show_manual_workout_form, command=self._show_manual_workout_form,
width=16, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
def _on_manual_workout_saved(self, entry: dict) -> None: def _paint_accepted(self, glyph: str) -> None:
"""Show confirmation and unlock after a manual-workout entry is built.""" """Paint "accepted, unlocking" and schedule the unlock.
self.workout_data = entry
Was "✓ Workout Verified!" / "✓ Run Verified!" / "✓ Manual Workout
Logged!" over the source line and "Unlocking...".
"""
self.clear_container() self.clear_container()
self._label( self._label(
"✓ Manual Workout Logged!", f"{glyph} {g.OK}",
role="display", role="display",
scale=1.3, scale=1.3,
color=self._colors.palette.success, color=self._colors.palette.success,
pad="lg", pad="lg",
) )
self._text( self._text(g.WAIT, role="display", color=self._colors.palette.muted)
entry.get("source", ""), role="subtitle", color=self._colors.palette.success
)
self._text("Unlocking...", role="body", color=self._colors.palette.muted)
unlock_delay = 1500 if self.demo_mode else 2000 unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen) self.root.after(unlock_delay, self.unlock_screen)
def _on_manual_workout_saved(self, entry: dict) -> None:
"""Show confirmation and unlock after a manual-workout entry is built."""
self.workout_data = entry
self._paint_accepted(g.FORM)
def _on_manual_workout_cancelled(self) -> None: def _on_manual_workout_cancelled(self) -> None:
"""Return to the retry screen when the manual-workout form is cancelled.""" """Return to the retry screen when the manual-workout form is cancelled."""
self._start_phone_check() self._start_phone_check()
@ -125,39 +167,13 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
if status == "verified": if status == "verified":
self.workout_data["type"] = "phone_verified" self.workout_data["type"] = "phone_verified"
self.workout_data["source"] = message self.workout_data["source"] = message
self.clear_container() self._paint_accepted(g.LIFT)
self._label( elif status in ("too_short", "clock_tampered"):
"✓ Workout Verified!", self._show_retry_and_sick(message, status=status)
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(message, role="subtitle", color=self._colors.palette.success)
self._text("Unlocking...", role="body", color=self._colors.palette.muted)
unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen)
elif status == "too_short":
self._show_retry_and_sick(
f"❌ {message}\n\n"
"Your workout was too short!\n"
"Actually do the full workout, don't just\n"
"spam through the exercises.",
)
elif status == "clock_tampered":
self._show_retry_and_sick(
f"❌ {message}\n\n"
"System clock appears to be manipulated.\n"
"Fix your system time and try again.",
)
elif status in ("stale", "no_exercises", "not_verified"): elif status in ("stale", "no_exercises", "not_verified"):
# Try RunnerUp before showing failure — user may have run instead of lifted. # Try RunnerUp before showing failure — user may have run instead of lifted.
self._start_runnerup_fallback( self._start_runnerup_fallback(
lambda: self._show_retry_and_sick( lambda: self._show_retry_and_sick(message, status=status)
f"❌ {message}\n\n"
"Neither StrongLifts nor RunnerUp found a workout today.\n"
"Go do your workout first!",
)
) )
else: else:
# no_phone or error — try RunnerUp first, then penalty timer. # no_phone or error — try RunnerUp first, then penalty timer.
@ -168,15 +184,16 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
Shows a waiting screen, runs the check in a background thread, then Shows a waiting screen, runs the check in a background thread, then
either unlocks (run verified) or calls ``on_failure``. either unlocks (run verified) or calls ``on_failure``.
Was "Checking RunnerUp..." / "Looking for today's run in RunnerUp".
""" """
self.clear_container() self.clear_container()
self._label( self._label(
"Checking RunnerUp...", f"{g.PHONE} {g.RUN}",
role="display", role="display",
color=self._colors.palette.warning, color=self._colors.palette.warning,
pad="lg", pad="lg",
) )
self._text("Looking for today's run in RunnerUp...", role="body") self._text(g.WAIT, role="display", color=self._colors.palette.muted)
executor = ThreadPoolExecutor(max_workers=1) executor = ThreadPoolExecutor(max_workers=1)
self._runnerup_future = executor.submit(self._verify_runnerup_workout) self._runnerup_future = executor.submit(self._verify_runnerup_workout)
executor.shutdown(wait=False) executor.shutdown(wait=False)
@ -190,20 +207,7 @@ class UIFlowsMixin(SickDayFlowMixin, SickPanelFlowMixin, LockoutFlowMixin):
if status == "verified": if status == "verified":
self.workout_data["type"] = "runnerup_verified" self.workout_data["type"] = "runnerup_verified"
self.workout_data["source"] = message self.workout_data["source"] = message
self.clear_container() self._paint_accepted(g.RUN)
self._label(
"✓ Run Verified!",
role="display",
scale=1.3,
color=self._colors.palette.success,
pad="lg",
)
self._text(message, role="subtitle", color=self._colors.palette.success)
self._text(
"Unlocking...", role="body", color=self._colors.palette.muted
)
unlock_delay = 1500 if self.demo_mode else 2000
self.root.after(unlock_delay, self.unlock_screen)
else: else:
self._runnerup_on_failure() self._runnerup_on_failure()
else: else:

View File

@ -7,8 +7,10 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
from __future__ import annotations from __future__ import annotations
import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import ( from screen_locker._constants import (
NO_PHONE_EXTRA_LOCKOUT_SECONDS, NO_PHONE_EXTRA_LOCKOUT_SECONDS,
PHONE_PENALTY_DELAY_DEMO, PHONE_PENALTY_DELAY_DEMO,
@ -18,6 +20,8 @@ from screen_locker._constants import (
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
_logger = logging.getLogger(__name__)
class LockoutFlowMixin: class LockoutFlowMixin:
"""Lockout countdown and the no-phone penalty timer.""" """Lockout countdown and the no-phone penalty timer."""
@ -27,10 +31,14 @@ class LockoutFlowMixin:
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def lockout(self) -> None: def lockout(self) -> None:
"""Display lockout screen with countdown timer.""" """Display lockout screen with countdown timer.
Was "Go work out! Locked for N seconds": the barbell in the danger
colour over the seconds counting down.
"""
self.clear_container() self.clear_container()
self.lockout_label = self._label( self.lockout_label = self._label(
f"Go work out!\nLocked for {self.lockout_time} seconds", g.LIFT,
role="display", role="display",
scale=1.5, scale=1.5,
color=self._colors.palette.danger, color=self._colors.palette.danger,
@ -61,7 +69,13 @@ class LockoutFlowMixin:
def _show_phone_penalty( def _show_phone_penalty(
self, message: str, *, on_done: Callable[[], None] | None = None self, message: str, *, on_done: Callable[[], None] | None = None
) -> None: ) -> None:
"""Show penalty countdown when phone verification is unavailable.""" """Show penalty countdown when phone verification is unavailable.
Was "Cannot Verify Workout", the reason, and "Connect phone via ADB
to skip this wait, or wait for the penalty timer". Now the phone glyph
crossed out over the seconds left; the reason goes to the log.
"""
_logger.warning("Phone check unavailable, penalty wait: %s", message)
self.clear_container() self.clear_container()
self._phone_penalty_done_fn: Callable[[], None] = ( self._phone_penalty_done_fn: Callable[[], None] = (
on_done on_done
@ -80,18 +94,11 @@ class LockoutFlowMixin:
else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS else base_delay + NO_PHONE_EXTRA_LOCKOUT_SECONDS
) )
self._label( self._label(
"Cannot Verify Workout", f"{g.PHONE}{g.FAIL}",
role="display", role="display",
color=self._colors.palette.warning, color=self._colors.palette.warning,
pad="md", pad="md",
) )
self._text(message, color=self._colors.palette.warning)
self._text(
"Connect phone via ADB to skip this wait,\n"
"or wait for the penalty timer.\n\n"
"Note: Phone must be rooted and StrongLifts installed.",
role="body",
)
self.phone_penalty_remaining = delay self.phone_penalty_remaining = delay
self.phone_penalty_label = self._label( self.phone_penalty_label = self._label(
str(delay), str(delay),

View File

@ -1,15 +1,23 @@
"""Relaxed-day (Tue/Wed/Thu) UI flow methods mixin.""" """Relaxed-day (Tue/Wed/Thu) UI flow methods mixin.
textgate: glyphs and numbers only (``_glyphs``); the verifier's reason goes
to the log, not the screen.
"""
from __future__ import annotations from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import logging
from screen_locker import _glyphs as g
from screen_locker._weekly_check import ( from screen_locker._weekly_check import (
RELAXED_DAY_SKIP_TYPE, RELAXED_DAY_SKIP_TYPE,
WEEKLY_WORKOUT_MINIMUM, WEEKLY_WORKOUT_MINIMUM,
count_weekly_workouts, count_weekly_workouts,
) )
_logger = logging.getLogger(__name__)
class UIFlowsRelaxedMixin: class UIFlowsRelaxedMixin:
"""Mixin providing the relaxed-day UI flow logic.""" """Mixin providing the relaxed-day UI flow logic."""
@ -23,36 +31,39 @@ class UIFlowsRelaxedMixin:
The screen is not locked — the user can skip freely or voluntarily The screen is not locked — the user can skip freely or voluntarily
import a Stronglift workout that counts toward the weekly minimum. import a Stronglift workout that counts toward the weekly minimum.
Was "Optional Day (Tue / Wed / Thu)" / "Weekly workouts: N / M. No
penalty for skipping today." / "Skip — No Penalty" / "Log Stronglift
Workout": now the optional-day diamond, the week as dots + numbers,
skip (green) and the barbell (go).
""" """
count = count_weekly_workouts(self.log_file) count = count_weekly_workouts(self.log_file)
self.clear_container() self.clear_container()
self._label( self._label(
"Optional Day (Tue / Wed / Thu)", g.OPTIONAL,
role="title", role="display",
color=self._colors.palette.warning, color=self._colors.palette.warning,
pad="md", pad="md",
) )
self._text( self._text(
f"Weekly workouts: {count} / {WEEKLY_WORKOUT_MINIMUM}\n" g.dots(count, WEEKLY_WORKOUT_MINIMUM),
"No penalty for skipping today.", role="title",
role="subtitle",
color=self._colors.palette.muted, color=self._colors.palette.muted,
pad="sm", pad="sm",
) )
frame = self._button_row() frame = self._button_row()
self._button( self._button(
frame, frame,
"Skip — No Penalty", g.SKIP,
bg=self._colors.palette.success, bg=self._colors.palette.success,
command=self._skip_relaxed_day, command=self._skip_relaxed_day,
width=18, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
self._button( self._button(
frame, frame,
"Log Stronglift Workout", f"{g.GO} {g.LIFT}",
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._start_relaxed_phone_check, command=self._start_relaxed_phone_check,
width=20, width=8,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
# Skipping is free here, but a sick day is more than a skip: it # Skipping is free here, but a sick day is more than a skip: it
# stands every gate down and lifts tonight's shutdown to 20:00. # stands every gate down and lifts tonight's shutdown to 20:00.
@ -74,12 +85,12 @@ class UIFlowsRelaxedMixin:
"""Run Stronglift check in relaxed mode (no screen grab).""" """Run Stronglift check in relaxed mode (no screen grab)."""
self.clear_container() self.clear_container()
self._label( self._label(
"Checking phone...", f"{g.PHONE} {g.LIFT}",
role="display", role="display",
color=self._colors.palette.warning, color=self._colors.palette.warning,
pad="lg", pad="lg",
) )
self._text("Looking for today's workout in StrongLifts...", role="body") self._text(g.WAIT, role="display", color=self._colors.palette.muted)
executor = ThreadPoolExecutor(max_workers=1) executor = ThreadPoolExecutor(max_workers=1)
self._phone_future = executor.submit(self._verify_phone_workout) self._phone_future = executor.submit(self._verify_phone_workout)
executor.shutdown(wait=False) executor.shutdown(wait=False)
@ -108,30 +119,34 @@ class UIFlowsRelaxedMixin:
self._show_relaxed_retry(message, status) self._show_relaxed_retry(message, status)
def _show_relaxed_retry(self, message: str, status: str) -> None: def _show_relaxed_retry(self, message: str, status: str) -> None:
"""Show retry and skip-close when workout not found in relaxed mode.""" """Show retry and skip-close when workout not found in relaxed mode.
Was "No Workout Found" / the reason / "TRY AGAIN" / "Close (Skip)".
"""
_logger.warning("Relaxed-day check found no workout (%s): %s", status, message)
self.clear_container() self.clear_container()
self._label( self._label(
"No Workout Found", f"{g.LIFT} {g.FAIL}",
role="display", role="display",
color=self._colors.palette.danger, color=self._colors.palette.danger,
pad="md", pad="md",
) )
self._text( self._text(
f"❌ {message}\n\nReason: {status}", color=self._colors.palette.warning g.status_glyph(status), role="display", color=self._colors.palette.warning
) )
frame = self._button_row() frame = self._button_row()
self._button( self._button(
frame, frame,
"TRY AGAIN", g.RETRY,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._start_relaxed_phone_check, command=self._start_relaxed_phone_check,
width=12, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
self._sick_button(frame) self._sick_button(frame)
self._button( self._button(
frame, frame,
"Close (Skip)", g.SKIP,
bg=self._colors.palette.success, bg=self._colors.palette.success,
command=self.close, command=self.close,
width=14, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))

View File

@ -23,8 +23,10 @@ Split out of :mod:`screen_locker._ui_flows` to keep every file under the
from __future__ import annotations from __future__ import annotations
import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from screen_locker import _glyphs as g
from screen_locker._constants import SHUTDOWN_BASE_FILE from screen_locker._constants import SHUTDOWN_BASE_FILE
from screen_locker._credit_slot import locked_shutdown_state from screen_locker._credit_slot import locked_shutdown_state
from screen_locker._sick import mark_today_sick, push_in_background from screen_locker._sick import mark_today_sick, push_in_background
@ -32,18 +34,20 @@ from screen_locker._sick import mark_today_sick, push_in_background
if TYPE_CHECKING: if TYPE_CHECKING:
import tkinter as tk import tkinter as tk
_logger = logging.getLogger(__name__)
class SickDayFlowMixin: class SickDayFlowMixin:
"""The one-tap sick-day button and what follows it.""" """The one-tap sick-day button and what follows it."""
def _sick_button(self, frame: tk.Widget) -> None: def _sick_button(self, frame: tk.Widget) -> None:
"""Pack the "I'm sick" button into ``frame``.""" """Pack the sick-day button (was "I'm sick") into ``frame``."""
self._button( self._button(
frame, frame,
"I'm sick", g.SICK,
bg=self._colors.palette.warning, bg=self._colors.palette.warning,
command=self.mark_sick_and_unlock, command=self.mark_sick_and_unlock,
width=12, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))
# The keep-aware alternative (``_ui_flows_sick_panel``), next to it. # The keep-aware alternative (``_ui_flows_sick_panel``), next to it.
self._choose_lockers_link(frame) self._choose_lockers_link(frame)
@ -78,15 +82,19 @@ class SickDayFlowMixin:
self.close() self.close()
def _show_sick_refused(self, message: str) -> None: def _show_sick_refused(self, message: str) -> None:
"""Say why today could not be marked sick; the lock stays up.""" """Show that today could not be marked sick; the lock stays up.
Was "Could not mark today as sick" over sickdays' reason; the reason
(a free day, an unreadable pool) now goes to the log.
"""
_logger.warning("Could not mark today sick: %s", message)
self.clear_container() self.clear_container()
self._label( self._label(
"Could not mark today as sick", f"{g.SICK} {g.FAIL}",
role="display", role="display",
color=self._colors.palette.danger, color=self._colors.palette.danger,
pad="md", pad="md",
) )
self._text(message, color=self._colors.palette.warning)
frame = self._button_row() frame = self._button_row()
back = ( back = (
self._start_relaxed_day_flow self._start_relaxed_day_flow
@ -95,8 +103,8 @@ class SickDayFlowMixin:
) )
self._button( self._button(
frame, frame,
"Back", g.BACK,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=back, command=back,
width=12, width=4,
).pack(side="left", padx=self._colors.space("sm")) ).pack(side="left", padx=self._colors.space("sm"))

View File

@ -29,6 +29,7 @@ from gatelock import bind_activate
import sickdays import sickdays
from sickdays.gui import KeepPanel from sickdays.gui import KeepPanel
from screen_locker import _glyphs as g
from screen_locker._sick import stands_down_workout from screen_locker._sick import stands_down_workout
from screen_locker._surface_group import FrameGroup from screen_locker._surface_group import FrameGroup
@ -39,8 +40,10 @@ if TYPE_CHECKING:
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
LINK_TEXT = "choose lockers…" # textgate: was "choose lockers…" (sick, then pick) and "Workout lock kept —
KEPT_NOTE = "Workout lock kept — finish the workout to unlock." # finish the workout to unlock." (sick, but the barbell lock stays).
LINK_TEXT = f"{g.SICK}▾"
KEPT_NOTE = f"{g.SICK} {g.LIFT} {g.LOCK}"
def build_sick_panel( def build_sick_panel(
@ -162,10 +165,10 @@ class SickPanelFlowMixin:
).pack(pady=self._colors.space("md")) ).pack(pady=self._colors.space("md"))
back = self._button( back = self._button(
box, box,
"Back", g.BACK,
bg=self._colors.palette.accent, bg=self._colors.palette.accent,
command=self._close_sick_panel, command=self._close_sick_panel,
width=12, width=4,
) )
back.pack(pady=self._colors.space("sm")) back.pack(pady=self._colors.space("sm"))
back.first.focus_set() back.first.focus_set()

View File

@ -7,6 +7,7 @@ from typing import TYPE_CHECKING
from gatelock import bind_activate from gatelock import bind_activate
from screen_locker._tooltip import attach_tooltip, tooltip_word
from screen_locker._ui_form_fields import UIFormFieldsMixin, disable_paste from screen_locker._ui_form_fields import UIFormFieldsMixin, disable_paste
if TYPE_CHECKING: if TYPE_CHECKING:
@ -163,8 +164,11 @@ class UIWidgetsMixin(UIFormFieldsMixin):
) )
# Every per-monitor copy, not just `.first` -- one flow paints N screens # Every per-monitor copy, not just `.first` -- one flow paints N screens
# and the user may be looking at any of them. # and the user may be looking at any of them.
word = tooltip_word(text)
for button in buttons: for button in buttons:
bind_activate(button) bind_activate(button)
if word is not None:
attach_tooltip(button, word)
return buttons return buttons
def _button_row(self) -> FrameGroup: def _button_row(self) -> FrameGroup:

View File

@ -3,10 +3,16 @@
Split out of ``screen_lock`` so that module stays inside the repo's 400-line Split out of ``screen_lock`` so that module stays inside the repo's 400-line
cap; this is pure view code (paint the credit, then close), which is exactly cap; this is pure view code (paint the credit, then close), which is exactly
the kind of thing the other ``_ui_*`` mixins already own. the kind of thing the other ``_ui_*`` mixins already own.
textgate: was "Great job! 💪" / "Shutdown time +2h later! 🎁" / "Extra
workout today! +1h tonight" / "🔥 N-week streak (5+ workouts each)" /
"Screen Unlocked!". Now: the open lock in green, then each reward as its
glyph and amount, then the streak as week bars and their count.
""" """
from __future__ import annotations from __future__ import annotations
from screen_locker import _glyphs as g
from screen_locker._constants import EXTRA_BENEFITS_FILE from screen_locker._constants import EXTRA_BENEFITS_FILE
from screen_locker._earned import span from screen_locker._earned import span
from screen_locker._extra_benefits import current_streak from screen_locker._extra_benefits import current_streak
@ -18,12 +24,12 @@ class UnlockViewMixin:
"""Paints the unlock screen, then closes it.""" """Paints the unlock screen, then closes it."""
def unlock_screen(self) -> None: def unlock_screen(self) -> None:
"""Apply workout credit and display the success message.""" """Apply workout credit and display the success glyphs."""
credit = self._apply_workout_credit() credit = self._apply_workout_credit()
self.clear_container() self.clear_container()
self._label( self._label(
"Great job! 💪", f"{g.UNLOCK} {g.OK}",
role="display", role="display",
scale=1.5, scale=1.5,
color=self._colors.palette.success, color=self._colors.palette.success,
@ -31,22 +37,21 @@ class UnlockViewMixin:
) )
if credit.shutdown_adjusted: if credit.shutdown_adjusted:
self._text( self._text(
"Shutdown time +2h later! 🎁", f"{g.SHUTDOWN} {g.GIFT}{span(120)}",
role="title", role="title",
color=self._colors.palette.warning, color=self._colors.palette.warning,
) )
if credit.extra_bonus_delta > 0: if credit.extra_bonus_delta > 0:
self._text( self._text(
f"Extra workout today! +{span(credit.extra_bonus_delta)} tonight", f"{g.LIFT} {g.GIFT}{span(credit.extra_bonus_delta)}",
role="subtitle", role="subtitle",
color=self._colors.palette.warning, color=self._colors.palette.warning,
) )
streak = current_streak(EXTRA_BENEFITS_FILE) streak = current_streak(EXTRA_BENEFITS_FILE)
if streak >= 1: if streak >= 1:
self._text( self._text(
f"🔥 {streak}-week streak (5+ workouts each)", f"{g.STREAK * min(streak, 10)} {streak}",
role="label", role="label",
color=self._colors.palette.muted, color=self._colors.palette.muted,
) )
self._text("Screen Unlocked!", role="display", pad="md")
self.root.after(_UNLOCK_DELAY_MS, self.close) self.root.after(_UNLOCK_DELAY_MS, self.close)

View File

@ -1,42 +1,64 @@
"""Walking in RunnerUp TCX exports: which files are walks, and their moving time. """One crediting rule for every GPS activity, from its RunnerUp-style TCX export.
A day's walking counts as the workout once its walks -- usually separate A day's activities -- runs and walks, RunnerUp's files and the workout app's
commute legs, one file each -- add up to the shared workout duration bar alike -- are summed, and the day counts as the workout once EITHER
(``WORKOUT_DURATION_ACCEPT_MINUTES``) of *moving* time.
**Which files are walks.** RunnerUp's WebDAV and File synchronisers both * their distance reaches ``MIN_RUN_DISTANCE_KM`` (within the GPS tolerance), OR
export with ``ExportOptions.getDefault()``, whose TCX writer knows only * their *moving* time reaches the shared duration bar
Running/Biking and writes ``Sport="Other"`` for a walk. The sport survives (``WORKOUT_DURATION_ACCEPT_MINUTES``).
only in the file name (``Sport.TapiriikType()``): ``..._Walking.tcx``. The
Strava export variant writes ``Sport="Walking"``, so that counts too. The TCX sport and the ``_Walking`` file-name suffix never change the outcome;
``Other`` alone is not a walk: it is every sport RunnerUp cannot name. they only decide the label a message and the log's ``activity`` field carry
(the phone's history shows it).
**Which files are walks (label only).** RunnerUp's WebDAV and File
synchronisers both export with ``ExportOptions.getDefault()``, whose TCX writer
knows only Running/Biking and writes ``Sport="Other"`` for a walk. The sport
survives only in the file name (``Sport.TapiriikType()``): ``..._Walking.tcx``.
The Strava export variant writes ``Sport="Walking"``, so that counts too.
**Moving time, not elapsed.** A lap's ``TotalTimeSeconds`` is wall-clock: one **Moving time, not elapsed.** A lap's ``TotalTimeSeconds`` is wall-clock: one
real lap reads 101 min for 1 km of standing about. Moving time is summed over real lap reads 101 min for 1 km of standing about. The track is cut into
consecutive trackpoint pairs whose speed is walking speed windows of at least ``TRACK_WINDOW_SECONDS`` (a fix every second jitters, so
(``WALK_SPEED_MPS``): standing still is too slow, a tram or a bus too fast. one raw pair can read 15 m/s inside a 3 m/s run) and each window is judged by
A pair further apart than ``WALK_MAX_GAP_SECONDS`` is a GPS dropout whose its average speed. Faster than ``MAX_MOVING_SPEED_MPS`` (25 km/h) is a vehicle
motion is unknown and earns nothing -- the walk is never credited for time or a GPS jump: neither time nor distance counts, so a bus ride earns nothing.
nobody saw. Otherwise its metres count, and its seconds count as moving time at
``MIN_MOVING_SPEED_MPS`` or faster; standing still is too slow. A window longer
than ``WALK_MAX_GAP_SECONDS`` is a signal dropout (real exports have 2 minute
ones): the runner may have kept running unseen, so it counts as moving only at
``MIN_DROPOUT_SPEED_MPS`` or faster, while a pause (no distance across the
gap) earns nothing -- a pause cannot buy a run its duration.
The day's distance is the sum of the windows (``track_distance_m``), never the
lap's ``DistanceMeters`` total, and an export with no trackpoints cannot be
speed-checked, so it credits nothing. Only the root-DB fallback, which has no
trackpoints at all, is judged by its recorded distance and duration.
""" """
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime from datetime import datetime
import itertools
import logging import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from screen_locker._activity_day import (
SPORT_NAMES,
ActivityDay,
activity_day,
activity_shortfall,
distance_qualifies,
moving_qualifies,
)
from screen_locker._constants import ( from screen_locker._constants import (
MIN_WORKOUT_DURATION_MINUTES, MAX_MOVING_SPEED_MPS,
MIN_DROPOUT_SPEED_MPS,
MIN_MOVING_SPEED_MPS,
TRACK_WINDOW_SECONDS,
WALK_MAX_GAP_SECONDS, WALK_MAX_GAP_SECONDS,
WALK_SPEED_MPS,
WORKOUT_DURATION_ACCEPT_MINUTES,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable from collections.abc import Iterator
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -73,73 +95,78 @@ def _trackpoints(activity: ET.Element) -> list[tuple[float, float]]:
return points return points
def _segments(
points: list[tuple[float, float]],
) -> Iterator[tuple[float, float]]:
"""``(seconds, metres)`` of the track cut into windows of >= TRACK_WINDOW_SECONDS.
A fix every second jitters (one pair can read 15 m/s inside a 3 m/s run),
so speed is judged over a window, never over a raw 1 s pair. Fixes that
are already further apart than the window are their own segment.
"""
if not points:
return
anchor = points[0]
for point in points[1:]:
if point[0] - anchor[0] >= TRACK_WINDOW_SECONDS:
yield point[0] - anchor[0], point[1] - anchor[1]
anchor = point
if points[-1] is not anchor:
yield points[-1][0] - anchor[0], points[-1][1] - anchor[1]
def track_summary(activity: ET.Element) -> dict[str, Any]: def track_summary(activity: ET.Element) -> dict[str, Any]:
"""Moving seconds and end time of one activity, from its trackpoints.""" """Moving seconds, credited distance and end time, from the trackpoints.
A segment (see :func:`_segments`) counts unless it was travelled faster
than ``MAX_MOVING_SPEED_MPS``: it then adds its metres to
``track_distance_m``, and its seconds to ``moving_seconds`` too when it was
travelled at least at ``MIN_MOVING_SPEED_MPS``. A segment longer than
``WALK_MAX_GAP_SECONDS`` is a signal dropout whose motion is unknown; it
only counts as moving time at ``MIN_DROPOUT_SPEED_MPS``, so a pause (no
distance across the gap) earns no time while a runner whose GPS went away
for two minutes keeps the time and metres the far side proves.
"""
points = _trackpoints(activity) points = _trackpoints(activity)
slow, fast = WALK_SPEED_MPS
moving = 0.0 moving = 0.0
for (t0, d0), (t1, d1) in itertools.pairwise(points): metres = 0.0
gap = t1 - t0 for seconds, travelled in _segments(points):
if 0 < gap <= WALK_MAX_GAP_SECONDS and slow <= (d1 - d0) / gap <= fast: if seconds <= 0:
moving += gap continue
speed = travelled / seconds
if speed > MAX_MOVING_SPEED_MPS:
continue
metres += max(travelled, 0.0)
floor = (
MIN_MOVING_SPEED_MPS
if seconds <= WALK_MAX_GAP_SECONDS
else MIN_DROPOUT_SPEED_MPS
)
if speed >= floor:
moving += seconds
return { return {
"activity_id": activity.findtext(f"{_TCX_NS}Id") or "", "activity_id": activity.findtext(f"{_TCX_NS}Id") or "",
"moving_seconds": moving, "moving_seconds": moving,
"track_distance_m": metres,
"ended_at": points[-1][0] if points else None, "ended_at": points[-1][0] if points else None,
} }
@dataclass(frozen=True) # The day aggregate lives in ``_activity_day``; these names stay importable here,
class WalkDay: # along with the walk-only names they replaced.
"""A day's walks, summed. WalkDay = ActivityDay
walk_day = activity_day
Attributes: walk_shortfall = activity_shortfall
legs: Distinct walks (deduplicated by the activity's ``Id``: the __all__ = [
WebDAV copy and the phone's copy are the same walk). "SPORT_NAMES",
moving_minutes: Their summed moving time. "ActivityDay",
distance_km: Their summed distance. "WalkDay",
completed_at: Unix time the walk that crossed the bar ended -- when "activity_day",
the workout was actually done -- or ``None`` if it never did. "activity_shortfall",
""" "distance_qualifies",
"is_walking_export",
legs: int "moving_qualifies",
moving_minutes: float "track_summary",
distance_km: float "walk_day",
completed_at: float | None "walk_shortfall",
]
@property
def qualifies(self) -> bool:
"""Whether the day's walking counts as its workout."""
return self.moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
def message(self) -> str:
"""The verification line, in the RunnerUp verifier's own style."""
return (
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
f"{self.moving_minutes:.0f} min moving"
)
def walk_shortfall(day: WalkDay) -> str:
"""Why a day's walking did not count yet."""
return f"{day.message()} -- need {MIN_WORKOUT_DURATION_MINUTES}+ min moving"
def walk_day(walks: Iterable[dict[str, Any]]) -> WalkDay:
"""Sum parsed walk exports (``_parse_tcx`` dicts) into one :class:`WalkDay`."""
unique: dict[str, dict[str, Any]] = {}
for walk in walks:
unique.setdefault(str(walk.get("activity_id") or id(walk)), walk)
ordered = sorted(unique.values(), key=lambda w: w.get("ended_at") or 0.0)
moving = 0.0
completed_at: float | None = None
for walk in ordered:
moving += float(walk.get("moving_seconds", 0.0))
if completed_at is None and moving / 60 >= WORKOUT_DURATION_ACCEPT_MINUTES:
completed_at = walk.get("ended_at")
return WalkDay(
legs=len(ordered),
moving_minutes=moving / 60,
distance_km=sum(float(w.get("distance_m", 0.0)) for w in ordered) / 1000,
completed_at=completed_at,
)

View File

@ -1,9 +1,11 @@
"""Read-only localhost HTTP server for the status web UI. """Read-only localhost HTTP server for the status web UI.
Serves the status/decision/health payloads at ``/api/*`` and the built React Serves the status/decision/health payloads at ``/api/*``, the built Astro
bundle (``web/dist``) as static files. Binds to loopback only and never exposes bundle (``web/dist``) as static files, and ``/version``: the short git hash the
a secret: every payload comes from :mod:`screen_locker._web_payload`, which bundle was stamped with at build time (``web/stamp-version.mjs``), or 404 when
reads state files but never the sync token or the HMAC key. the build carries no stamp. Binds to loopback only and never exposes a secret:
every payload comes from :mod:`screen_locker._web_payload`, which reads state
files but never the sync token or the HMAC key.
Read-only by construction, like the MCP server it sits beside: there is no Read-only by construction, like the MCP server it sits beside: there is no
route that logs a workout, clears a lock, or writes anything at all. A local route that logs a workout, clears a lock, or writes anything at all. A local
@ -51,6 +53,9 @@ DEFAULT_PORT = 8770
_API_STATUS = "/api/status" _API_STATUS = "/api/status"
_API_DECISIONS = "/api/decisions" _API_DECISIONS = "/api/decisions"
_API_HEALTH = "/api/health" _API_HEALTH = "/api/health"
_VERSION = "/version"
# Written by web/stamp-version.mjs after `astro build`.
_VERSION_FILE = "version.txt"
# Content types that are text but not under the ``text/`` prefix. # Content types that are text but not under the ``text/`` prefix.
_EXTRA_TEXT_TYPES = frozenset( _EXTRA_TEXT_TYPES = frozenset(
@ -108,6 +113,8 @@ class _Handler(BaseHTTPRequestHandler):
self._serve_json("decisions", lambda: build_decisions_payload(limit=limit)) self._serve_json("decisions", lambda: build_decisions_payload(limit=limit))
elif split.path == _API_HEALTH: elif split.path == _API_HEALTH:
self._serve_json("health", build_health_payload) self._serve_json("health", build_health_payload)
elif split.path == _VERSION:
self._serve_version()
else: else:
self._serve_static(split.path) self._serve_static(split.path)
@ -132,6 +139,23 @@ class _Handler(BaseHTTPRequestHandler):
return return
self._send(HTTPStatus.OK, body, "application/json") self._send(HTTPStatus.OK, body, "application/json")
def _serve_version(self) -> None:
"""Send the bundle's build stamp, or a 404 when it has none.
Never the SPA fallback: a dashboard page at ``/version`` would make an
unstamped build look like a live one to a deploy check.
"""
stamp = WEB_DIST / _VERSION_FILE
if not stamp.is_file():
logger.warning("No build stamp at %s; /version answers 404", stamp)
self._send(
HTTPStatus.NOT_FOUND,
b"Build not stamped. Run: pnpm --dir web build",
"text/plain",
)
return
self._send(HTTPStatus.OK, stamp.read_bytes().strip(), "text/plain")
def _serve_static(self, path: str) -> None: def _serve_static(self, path: str) -> None:
"""Serve a file from ``WEB_DIST`` with SPA fallback and traversal guard. """Serve a file from ``WEB_DIST`` with SPA fallback and traversal guard.

View File

@ -18,6 +18,7 @@ from gatelock import (
ScrollableSurface, ScrollableSurface,
) )
from screen_locker._credit import place_credit
from screen_locker._queue_wait import wait_for_screen from screen_locker._queue_wait import wait_for_screen
from screen_locker._surface_group import FrameGroup from screen_locker._surface_group import FrameGroup
@ -116,6 +117,7 @@ class WindowSetupMixin:
scroller.container.pack(fill="both", expand=True) scroller.container.pack(fill="both", expand=True)
self._scrollers["__aux__"] = scroller self._scrollers["__aux__"] = scroller
self.container = FrameGroup([scroller.content]) self.container = FrameGroup([scroller.content])
place_credit(self.root, self._colors)
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None: def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
"""Add one scrollable, keyboard-reachable container for a live output. """Add one scrollable, keyboard-reachable container for a live output.
@ -141,6 +143,9 @@ class WindowSetupMixin:
scroller.container.place(relx=0, rely=0, relwidth=1, relheight=1) scroller.container.place(relx=0, rely=0, relwidth=1, relheight=1)
self._scrollers[surface.output_name] = scroller self._scrollers[surface.output_name] = scroller
self.container.add(scroller.content, surface.output_name) self.container.add(scroller.content, surface.output_name)
# On the surface toplevel, not scroller.content: flows clear and
# repaint the content frame, which would wipe the logo.
place_credit(parent, self._colors)
def teardown_surface(self, surface: SurfaceInfo) -> None: def teardown_surface(self, surface: SurfaceInfo) -> None:
"""Forget the container and viewport for an output that went dark.""" """Forget the container and viewport for an output that went dark."""
@ -201,9 +206,10 @@ class WindowSetupMixin:
def _setup_demo_close_button(self) -> None: def _setup_demo_close_button(self) -> None:
"""Add close button for demo mode.""" """Add close button for demo mode."""
# Was "✕ Close Demo": the cross on the danger fill says it alone.
close_btn = tk.Button( close_btn = tk.Button(
self.root, self.root,
text="✕ Close Demo", text="✕",
font=self._colors.font("caption"), font=self._colors.font("caption"),
bg=self._colors.palette.danger, bg=self._colors.palette.danger,
fg=self._colors.palette.on_fill, fg=self._colors.palette.on_fill,

View File

@ -20,10 +20,9 @@ from screen_locker import _credit_notify
from screen_locker._constants import SHUTDOWN_BASE_FILE from screen_locker._constants import SHUTDOWN_BASE_FILE
from screen_locker._credit_slot import CreditSlot, credit_slot, locked_shutdown_state from screen_locker._credit_slot import CreditSlot, credit_slot, locked_shutdown_state
from screen_locker._day import today_str from screen_locker._day import today_str
from screen_locker._earned import extra_minutes from screen_locker._earned import extra_minutes, first_minutes
from screen_locker._rest_day import is_rest_day from screen_locker._rest_day import is_rest_day
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES, count_weekly_workouts from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES, count_weekly_workouts
from screen_locker._workout_ledger import entry_done_at
if TYPE_CHECKING: if TYPE_CHECKING:
from pathlib import Path from pathlib import Path
@ -67,22 +66,12 @@ class WorkoutCreditMixin:
workout_data: dict[str, str] workout_data: dict[str, str]
log_file: Path log_file: Path
def _done_at(self, day: date) -> float | None:
"""When this workout ended; ``None`` (now) when it records no end.
``workout_data`` is the entry's inner dict, so it is wrapped as the
log entry ``entry_done_at`` reads. The run's own end anchors a late
workout, never the moment a sync applied it.
"""
return entry_done_at({"workout_data": self.workout_data}, day)
def _try_adjust_shutdown_for_workout(self) -> bool: def _try_adjust_shutdown_for_workout(self) -> bool:
"""Try to adjust shutdown time later for actual workouts.""" """Try to adjust shutdown time later for actual workouts."""
workout_type = self.workout_data.get("type", "") workout_type = self.workout_data.get("type", "")
if workout_type not in COUNTED_WORKOUT_TYPES: if workout_type not in COUNTED_WORKOUT_TYPES:
return False return False
day = date.fromisoformat(today_str()) adjusted = self._adjust_shutdown_time_later()
adjusted = self._adjust_shutdown_time_later(at=self._done_at(day))
if adjusted: if adjusted:
_logger.info("Shutdown time moved later as workout reward") _logger.info("Shutdown time moved later as workout reward")
return adjusted return adjusted
@ -152,7 +141,7 @@ class WorkoutCreditMixin:
slot is CreditSlot.FURTHER slot is CreditSlot.FURTHER
and extra and extra
and before and before
and self._adjust_shutdown_time_by(extra, at=self._done_at(day)) and self._adjust_shutdown_time_by(extra)
): ):
new_cfg = self._read_shutdown_config() new_cfg = self._read_shutdown_config()
if new_cfg: if new_cfg:
@ -160,7 +149,12 @@ class WorkoutCreditMixin:
after = self._read_shutdown_config() after = self._read_shutdown_config()
if slot is not CreditSlot.NONE: if slot is not CreditSlot.NONE:
self._notify_credit(before, after) reward = (
first_minutes(earned_time.WORKOUT, day)
if first_counted_today
else extra
)
self._notify_credit(before, after, reward)
return WorkoutCreditResult( return WorkoutCreditResult(
shutdown_adjusted=shutdown_adjusted, shutdown_adjusted=shutdown_adjusted,
@ -173,6 +167,7 @@ class WorkoutCreditMixin:
self, self,
before: tuple[int, int, int] | None, before: tuple[int, int, int] | None,
after: tuple[int, int, int] | None, after: tuple[int, int, int] | None,
reward: int | None,
) -> None: ) -> None:
"""Pop the "Workout credited" notification; never fails the credit. """Pop the "Workout credited" notification; never fails the credit.
@ -182,7 +177,7 @@ class WorkoutCreditMixin:
batch uncredited, so every exception is logged and dropped here. batch uncredited, so every exception is logged and dropped here.
""" """
try: try:
_credit_notify.notify_workout_credit(before, after, self.log_file) _credit_notify.notify_workout_credit(before, after, reward)
except Exception: # pylint: disable=broad-exception-caught # notification must never fail the credit except Exception: # pylint: disable=broad-exception-caught # notification must never fail the credit
_logger.exception( _logger.exception(
"Workout credit notification failed — the credit itself is " "Workout credit notification failed — the credit itself is "

View File

@ -4,8 +4,8 @@ Every other earner publishes its credits as HMAC-signed rows in a ledger that
``earned_time`` reads (``first_credit_at``, ``credit_units``). This is the ``earned_time`` reads (``first_credit_at``, ``credit_units``). This is the
workout's: ``~/.local/share/workout_locker/ledger.json``, one row per workout's: ``~/.local/share/workout_locker/ledger.json``, one row per
* workout credit slot in ``log.json`` -- RunnerUp (a run, or the day's walks * workout credit slot in ``log.json`` -- RunnerUp (the day's runs and walks,
summed), StrongLifts (phone or PC session), manual, any lock-screen or summed by one rule), StrongLifts (phone or PC session), manual, any lock-screen or
verify path -- appended by the one log write chokepoint verify path -- appended by the one log write chokepoint
(``_log_mixin.write_signed_entry``), so no path can credit without it; and (``_log_mixin.write_signed_entry``), so no path can credit without it; and
* declared rest day -- appended when it is declared. * declared rest day -- appended when it is declared.

View File

@ -87,10 +87,8 @@ def main(argv: list[str] | None = None) -> int:
except (OSError, ValueError) as exc: except (OSError, ValueError) as exc:
_logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT) _logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT)
return 1 return 1
# Warm the budget sum (registry, ledgers) and the conf read once, so the # Warm the conf read once, so the first poke costs what every later one does.
# first poke costs what every later one does.
_poke_credit.current_shutdown() _poke_credit.current_shutdown()
_poke_credit.current_gaming_minutes(_poke_credit.fresh_locker().log_file)
try: try:
server = PokeServer((args.bind, args.port), key) server = PokeServer((args.bind, args.port), key)
except OSError as exc: except OSError as exc:

View File

@ -0,0 +1,99 @@
"""``python3 -m screen_locker.runnerup_retire``: uninstall RunnerUp, a week on.
What ``runnerup-retire.service`` runs. ``--status`` prints anchor, due date,
marker validity and (with ``--query-phone``) whether RunnerUp is installed;
it never writes and never talks to the phone unless asked. ``--dry-run`` runs
every check, including the read-only adb queries, but writes nothing, pulls
nothing and uninstalls nothing. The exit code is non-zero only for outcomes
that need a human (bad marker, adb missing, failed backup or uninstall).
"""
from __future__ import annotations
import argparse
from datetime import UTC, datetime
import logging
import sys
from typing import TYPE_CHECKING
from screen_locker._runnerup_retire import (
GRACE,
Paths,
derive_anchor,
run_retire,
)
from screen_locker._runnerup_retire_adb import PHONE_SERIAL, AdbError, Phone
from screen_locker._runnerup_retire_state import load_state
from screen_locker._runnerup_retire_tcx import check_marker
if TYPE_CHECKING:
from screen_locker._runnerup_retire_adb import PhoneLike
__all__ = ["main", "status_lines"]
_logger = logging.getLogger(__name__)
def _installed_line(phone: PhoneLike, *, query: bool) -> str:
if not query:
return "installed: not queried (add --query-phone)"
try:
device = phone.find_device()
if device.serial is None:
return f"installed: unknown ({device.reason})"
return f"installed: {'yes' if phone.installed(device.serial) else 'no'}"
except AdbError as exc:
_logger.warning("--status could not ask the phone: %s", exc)
return f"installed: unknown ({exc})"
def status_lines(
paths: Paths, phone: PhoneLike, now: datetime, *, query_phone: bool = False
) -> list[str]:
"""The ``--status`` report. Read-only: nothing is created or saved."""
state = load_state(paths.state_file)
anchor = derive_anchor(paths, state)
if anchor is None:
anchor_line, due_line = "anchor: none (no app run credited yet)", "due: never"
else:
origin = "stored" if state.anchor_at else "derived, not yet stored"
due = anchor + GRACE
days = (due - now).total_seconds() / 86400
anchor_line = f"anchor: {anchor.isoformat()} ({origin})"
due_line = f"due: {due:%Y-%m-%d %H:%M} ({days:+.1f} days)"
marker = check_marker(paths.marker, paths.processed)
return [
anchor_line,
due_line,
f"marker: {'valid' if marker.ok else 'INVALID'} ({marker.reason})",
f"done: {state.done_at or 'no'}",
_installed_line(phone, query=query_phone),
]
def main(argv: list[str] | None = None) -> int:
"""CLI entry; returns the process exit code."""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n", maxsplit=1)[0])
parser.add_argument(
"--status", action="store_true", help="print state, change nothing"
)
parser.add_argument(
"--dry-run", action="store_true", help="check everything, change nothing"
)
parser.add_argument(
"--query-phone", action="store_true", help="with --status: ask adb"
)
parser.add_argument("--serial", default=PHONE_SERIAL, help="phone adb serial")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
paths, phone = Paths.default(), Phone(args.serial)
if args.status:
now = datetime.now(UTC)
lines = status_lines(paths, phone, now, query_phone=args.query_phone)
sys.stdout.write("\n".join(lines) + "\n")
return 0
return 0 if run_retire(paths, phone, dry_run=args.dry_run).ok else 1
if __name__ == "__main__":
sys.exit(main())

View File

@ -19,9 +19,11 @@ from gatelock import (
LockConfig, LockConfig,
LockWindow, LockWindow,
) )
from gatelock.error_report import watch_stalls
from screen_locker import _instance from screen_locker import _errors, _instance
from screen_locker._auto_upgrade import AutoUpgradeMixin from screen_locker._auto_upgrade import AutoUpgradeMixin
from screen_locker._carrot_watch import watch_for_carrot
from screen_locker._constants import ( from screen_locker._constants import (
EARLY_BIRD_END_HOUR, EARLY_BIRD_END_HOUR,
EARLY_BIRD_END_MINUTE, EARLY_BIRD_END_MINUTE,
@ -34,9 +36,11 @@ from screen_locker._constants import (
PHONE_PENALTY_DELAY_PRODUCTION, PHONE_PENALTY_DELAY_PRODUCTION,
SCHEDULED_SKIPS_FILE, SCHEDULED_SKIPS_FILE,
) )
from screen_locker._credit_watch import watch_for_credit
from screen_locker._decision_log import record_run_aborted from screen_locker._decision_log import record_run_aborted
from screen_locker._early_bird import EarlyBirdMixin from screen_locker._early_bird import EarlyBirdMixin
from screen_locker._heat_skip import HeatSkipMixin from screen_locker._heat_skip import HeatSkipMixin
from screen_locker._hold import watch_for_hold
from screen_locker._log_mixin import LogMixin from screen_locker._log_mixin import LogMixin
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._phone_verification import PhoneVerificationMixin from screen_locker._phone_verification import PhoneVerificationMixin
@ -166,7 +170,9 @@ class ScreenLocker(
self._instance_lock.release() self._instance_lock.release()
sys.exit(0) sys.exit(0)
self.root.on_callback_error = self.on_callback_error self.root.on_callback_error = self.on_callback_error
self.root.title("Workout Locker" + (" [DEMO MODE]" if demo_mode else "")) # textgate: the window is fullscreen, so its title is never painted;
# was "Workout Locker" (+ " [DEMO MODE]"). Nothing matches on it.
self.root.title("")
self.demo_mode = demo_mode self.demo_mode = demo_mode
self.lockout_time = 10 if demo_mode else 1800 self.lockout_time = 10 if demo_mode else 1800
self._lock: LockWindow | None = None self._lock: LockWindow | None = None
@ -208,6 +214,11 @@ class ScreenLocker(
# across two separate if/elif/else statements). # across two separate if/elif/else statements).
if self._lock is not None: # pragma: no branch if self._lock is not None: # pragma: no branch
self._lock.grab_input() self._lock.grab_input()
watch_for_hold(self.root, self.close)
watch_for_carrot(self.root, self._stand_down_for_carrot)
watch_for_credit(
self.root, self.log_file, self.has_logged_today, self._stand_down_for_credit
)
def close(self) -> None: def close(self) -> None:
"""Close the application and exit.""" """Close the application and exit."""
@ -224,6 +235,9 @@ class ScreenLocker(
def run(self) -> None: def run(self) -> None:
"""Start the Tkinter main event loop.""" """Start the Tkinter main event loop."""
if (reporter := _errors.SLOT.reporter) is not None:
# Armed here, not in __init__: the build is no freeze (c890f31a21).
self.root.after_idle(lambda: watch_stalls(self.root, reporter))
if self._lock is not None: if self._lock is not None:
self._lock.run() self._lock.run()
else: else:

View File

@ -30,6 +30,8 @@ from typing import TYPE_CHECKING
from gatelock import LockConfig from gatelock import LockConfig
from screen_locker import _glyphs as g
from screen_locker._credit import place_credit
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._status_data import ( from screen_locker._status_data import (
StatusSnapshot, StatusSnapshot,
@ -112,7 +114,7 @@ class StatusWindow(
"""Redraw the whole window from *snapshot*.""" """Redraw the whole window from *snapshot*."""
self._last_snapshot = snapshot self._last_snapshot = snapshot
self.clear_container() self.clear_container()
self._label("Workout Status", role="title", pad="md") # textgate: the "Workout Status" heading is gone; see the sections.
self._section_today(self.container, snapshot.today) self._section_today(self.container, snapshot.today)
self._section_week(self.container, snapshot.week) self._section_week(self.container, snapshot.week)
self._section_streak(self.container, snapshot.streak, snapshot.week_rewards) self._section_streak(self.container, snapshot.streak, snapshot.week_rewards)
@ -130,44 +132,29 @@ class StatusWindow(
if status == "verified" if status == "verified"
else self._colors.palette.warning else self._colors.palette.warning
) )
self._text(f"Phone check ({status}): {message}", role="body", color=color) self._text(message, role="title", color=color)
if self._credit_message is not None: if self._credit_message is not None:
self._text( self._text(
self._credit_message, role="body", color=self._colors.palette.success self._credit_message, role="body", color=self._colors.palette.success
) )
# "Check Phone"/"Log Manual Workout" are the primary write actions # Check phone / manual log are the primary write actions (accent,
# (accent, high contrast per rule 3); "Refresh"/"Close" are secondary # high contrast per rule 3); refresh / close are secondary utility
# utility actions (muted) -- two tiers instead of four arbitrary hues. # actions (muted) -- two tiers instead of four arbitrary hues. Was
# "Check Phone" / "Log Manual Workout" / "Refresh" / "Close".
frame = self._button_row() frame = self._button_row()
self._button( buttons = [(g.PHONE, self._colors.palette.accent, self._on_check_phone_clicked)]
frame,
"Check Phone",
bg=self._colors.palette.accent,
command=self._on_check_phone_clicked,
width=14,
).pack(side="left", padx=self._colors.space("sm"))
if not self._mw_budget_closed(): if not self._mw_budget_closed():
self._button( buttons.append(
frame, (g.FORM, self._colors.palette.accent, self._show_manual_workout_form)
"Log Manual Workout", )
bg=self._colors.palette.accent, buttons += [
command=self._show_manual_workout_form, (g.RETRY, self._colors.palette.field_bg, self._on_refresh_clicked),
width=16, (g.CLOSE, self._colors.palette.field_bg, self.root.destroy),
).pack(side="left", padx=self._colors.space("sm")) ]
self._button( for glyph, bg, command in buttons:
frame, self._button(frame, glyph, bg=bg, command=command, width=4).pack(
"Refresh", side="left", padx=self._colors.space("sm")
bg=self._colors.palette.field_bg, )
command=self._on_refresh_clicked,
width=10,
).pack(side="left", padx=self._colors.space("sm"))
self._button(
frame,
"Close",
bg=self._colors.palette.field_bg,
command=self.root.destroy,
width=8,
).pack(side="left", padx=self._colors.space("sm"))
def _on_refresh_clicked(self) -> None: def _on_refresh_clicked(self) -> None:
"""Clear any stale phone-check/credit/temperature results, re-check both.""" """Clear any stale phone-check/credit/temperature results, re-check both."""
@ -192,9 +179,7 @@ class StatusWindow(
verifier.workout_data = entry verifier.workout_data = entry
credit = verifier._apply_workout_credit() credit = verifier._apply_workout_credit()
self._credit_message = "\n".join( self._credit_message = "\n".join(
self._credit_result_lines( self._credit_result_lines(f"{g.FORM} {g.OK}", credit)
f"Manual workout logged: {entry.get('source', '')}", credit
)
) )
self.render(gather_status()) self.render(gather_status())
@ -221,7 +206,7 @@ def main(argv: list[str] | None = None) -> None:
return return
root = tk.Tk() root = tk.Tk()
root.title("Workout Status") root.title("")
root.configure(bg=_STATUS_COLORS.palette.bg) root.configure(bg=_STATUS_COLORS.palette.bg)
root.minsize(560, 200) root.minsize(560, 200)
@ -229,6 +214,7 @@ def main(argv: list[str] | None = None) -> None:
window.render(gather_status()) window.render(gather_status())
window = StatusWindow(root, gather_status(), on_refresh=refresh) window = StatusWindow(root, gather_status(), on_refresh=refresh)
place_credit(root, _STATUS_COLORS)
root.mainloop() root.mainloop()

View File

@ -0,0 +1,96 @@
"""Helpers for the unified-activity tests: TCX builder and a phone-less verifier."""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
if TYPE_CHECKING:
from pathlib import Path
_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
DAY = "2026-10-10"
def tcx(
sport: str,
start: str,
*,
moving_min: float,
metres: float,
pause_min: float = 0.0,
) -> str:
"""A RunnerUp-shaped export: ``moving_min`` of steady motion covering ``metres``.
A ``pause_min`` pause sits in the middle of the track as ONE gap between
two trackpoints (the clock runs, the distance does not), so the lap's
wall-clock time is ``moving_min + pause_min``.
"""
begin = datetime.fromisoformat(f"{DAY}T{start}:00+00:00")
speed = metres / (moving_min * 60)
total = int(moving_min * 60)
half = total // 2 // 5 * 5
pause = int(pause_min * 60)
points = ""
for s in range(0, total + 1, 5):
offset = s + (pause if s > half else 0)
points += (
f"<Trackpoint><Time>{(begin + timedelta(seconds=offset)).isoformat()}"
f"</Time><DistanceMeters>{s * speed:.1f}</DistanceMeters></Trackpoint>"
)
return (
f'<TrainingCenterDatabase xmlns="{_NS}"><Activities>'
f'<Activity Sport="{sport}"><Id>{DAY}T{start}</Id><Lap>'
f"<TotalTimeSeconds>{total + pause}</TotalTimeSeconds>"
f"<DistanceMeters>{metres}</DistanceMeters>"
f"<Track>{points}</Track></Lap></Activity></Activities>"
"</TrainingCenterDatabase>"
)
class Verifier(RunnerUpVerificationMixin):
"""The real mixin reading one temporary drop directory and no phone."""
def __init__(self, folder: Path) -> None:
self.folder = folder
def _has_adb_device(self) -> bool:
return False
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
return False, ""
def _find_runnerup_exports_for_date(self, date_str: str) -> list[str]:
return sorted(str(p) for p in self.folder.glob(f"*{date_str}*.tcx"))
def drop(folder: Path, stamp: str, suffix: str, body: str) -> None:
"""Write a RunnerUp-named export for the test day."""
(folder / f"RunnerUp_Pixel_6a_{DAY}-{stamp}{suffix}.tcx").write_text(body)
def verify(verifier: Verifier) -> tuple[str, str] | None:
"""The file-based verdict for the test day."""
with patch("screen_locker._runnerup_verification.today_str", return_value=DAY):
return verifier._verify_runnerup_via_files()
def tcx_points(sport: str, start: str, points: list[tuple[int, float]]) -> str:
"""An export whose track is exactly ``(seconds after start, cumulative metres)``."""
begin = datetime.fromisoformat(f"{DAY}T{start}:00+00:00")
body = "".join(
f"<Trackpoint><Time>{(begin + timedelta(seconds=s)).isoformat()}</Time>"
f"<DistanceMeters>{m:.1f}</DistanceMeters></Trackpoint>"
for s, m in points
)
return (
f'<TrainingCenterDatabase xmlns="{_NS}"><Activities>'
f'<Activity Sport="{sport}"><Id>{DAY}T{start}</Id><Lap>'
f"<TotalTimeSeconds>{points[-1][0]}</TotalTimeSeconds>"
f"<DistanceMeters>{points[-1][1]}</DistanceMeters>"
f"<Track>{body}</Track></Lap></Activity></Activities>"
"</TrainingCenterDatabase>"
)

View File

@ -54,8 +54,13 @@ def _hermetic_gatelock(
The runtime dir is redirected as well, so a test cannot reach the real The runtime dir is redirected as well, so a test cannot reach the real
``$XDG_RUNTIME_DIR`` and stand a *production* locker down through the ``$XDG_RUNTIME_DIR`` and stand a *production* locker down through the
arbiter. arbiter.
The queue's startup grace is zeroed too: ``wait_for_turn`` sleeps it for
real before its first look, which put 1.5 s on every test that builds a
locker and the suite far past the 60 s action cap.
""" """
monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "gatelock-runtime")) monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "gatelock-runtime"))
monkeypatch.setattr("gatelock._queue.STARTUP_GRACE_SECONDS", 0.0)
with ( with (
patch("gatelock._surfaces.tk.Toplevel", side_effect=_make_toplevel), patch("gatelock._surfaces.tk.Toplevel", side_effect=_make_toplevel),
patch("gatelock._outputs.RandrBackend.create", return_value=None), patch("gatelock._outputs.RandrBackend.create", return_value=None),

View File

@ -0,0 +1,28 @@
"""A ``holds`` stand-in for tests: ``covers`` returns a value or raises it."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from datetime import datetime
class FakeHolds:
"""A ``holds`` stand-in: ``covers`` returns the value, or raises it."""
def __init__(self, covers: object) -> None:
self._covers = covers
self.calls: list[tuple[str, datetime | None]] = []
def covers(self, gate: str, now: datetime | None = None) -> bool:
"""Record the call, then answer like ``holds.covers``."""
self.calls.append((gate, now))
if isinstance(self._covers, BaseException):
raise self._covers
return bool(self._covers)
def fake_holds_module(*, covers: object) -> FakeHolds:
"""A ``holds`` stand-in to install with ``monkeypatch.setitem(sys.modules, ...)``."""
return FakeHolds(covers)

View File

@ -105,4 +105,20 @@ ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
"workday_penalty.json", "workday_penalty.json",
("_constants.WORKDAY_PENALTY_FILE", "_workday_penalty.WORKDAY_PENALTY_FILE"), ("_constants.WORKDAY_PENALTY_FILE", "_workday_penalty.WORKDAY_PENALTY_FILE"),
), ),
# RunnerUp retirement: the anchor/done stamp, the dufs drop directory it
# reads the marker and TCX files from (and writes the phone backup into),
# and the credit log the anchor is derived from. A test must never see, or
# create files under, the user's real RunnerUp folder.
(
"runnerup_retire.json",
("_runnerup_retire.STATE_FILE",),
),
(
"RunnerUp",
("_runnerup_retire.WATCH_DIR",),
),
(
"retire_log.json",
("_runnerup_retire.LOG_FILE",),
),
) )

View File

@ -1,32 +0,0 @@
"""Pinning the clock an untimed credit is stamped with.
Re-exported from ``conftest`` rather than defined there so neither file
exceeds the repo's line limit.
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from screen_locker import _late_credit
if TYPE_CHECKING:
from collections.abc import Iterator
@pytest.fixture(autouse=True)
def _untimed_credits_land_at_noon() -> Iterator[None]:
"""A credit with no time of its own (``at=None``) lands at today's noon.
``at=None`` means "now", and a suite run after a test's configured
shutdown (18:00, say) made every such credit late: the same tests went red
at 18:01. Noon is before any shutdown, so only tests that pass ``at=``
(or re-patch ``_late_credit._now``) take the late path.
"""
noon = datetime.now(tz=UTC).astimezone().replace(hour=12, minute=0, second=0)
with patch.object(_late_credit, "_now", return_value=noon.timestamp()):
yield

View File

@ -0,0 +1,67 @@
"""Signed progress rows and a state file for the partial-bonus tests.
A progress row is the fact a gate signs, "done N of M for day D"
(``earned_time`` 0.24.0, DOCS-progress.md), written to the gate's own ledger
next to its credits. Like every ledger helper here it signs with
``_earned_fixtures.KEY`` and lands where screen-locker reads it, so the
tests read real signed ledgers, never a mock of the reader.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Final
import earned_time
from screen_locker._day import today_str
from screen_locker.tests._earned_fixtures import _any_credit, signed, write_ledger
if TYPE_CHECKING:
from unittest.mock import MagicMock
# A flat earner whose rung does not divide by 3 or 2, so a share rounds down.
ODD: Final = earned_time.Earner(
name="odd",
label="Odd",
gaming_minutes=50,
shutdown_minutes=50,
ledger=".local/share/odd_guard/ledger.json",
match=_any_credit,
progress_source="odd",
)
def progress_row(
earner: earned_time.Earner,
done: int,
target: int,
day: str | None = None,
) -> dict[str, Any]:
"""A signed progress row for ``earner``'s source (default today)."""
for_day = day or today_str()
return signed(
{
"kind": "progress",
"entry_id": f"progress:{for_day}:{done}:{target}",
"day": for_day,
"amount": 0,
"device": "test",
"created_at": f"{for_day}T12:00:00+00:00",
"detail": {
"source": earner.progress_source,
"for_day": for_day,
"done": str(done),
"target": str(target),
},
}
)
def put_progress(earner: earned_time.Earner, rows: list[tuple[int, int]]) -> None:
"""Replace ``earner``'s ledger with one progress row per (done, target)."""
write_ledger(earner, [progress_row(earner, d, t) for d, t in rows])
def paid(mixin: MagicMock) -> list[int]:
"""The minutes each ``_adjust_shutdown_time_by`` call pushed, in order."""
return [c.args[0] for c in mixin._adjust_shutdown_time_by.call_args_list]

View File

@ -29,12 +29,27 @@ import pytest
import sickdays import sickdays
import sickdays.gui import sickdays.gui
from screen_locker import _errors
import screen_locker._night_lockdown import screen_locker._night_lockdown
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
@pytest.fixture(autouse=True)
def _no_error_hooks(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep the CLI from hooking this process's errors into the real spool.
gatelock installs its hooks once per process: a reporter already in place
makes ``install`` return it untouched, so every report lands in tmp_path.
"""
reporter = _errors.error_report.Reporter(
app=_errors.APP, repo=_errors.REPO, spool=tmp_path / "app-errors-spool"
)
monkeypatch.setattr(_errors.error_report.INSTALLED, "reporter", reporter)
monkeypatch.setattr(_errors.SLOT, "reporter", None)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _no_free_days_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def _no_free_days_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Never let the lock chain read the developer's real free-day pool. """Never let the lock chain read the developer's real free-day pool.
@ -221,3 +236,13 @@ def _no_real_ntp() -> Iterator[None]:
def _no_live_focus_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def _no_live_focus_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""No live focus project reshapes the registry (earned_time >= 0.19).""" """No live focus project reshapes the registry (earned_time >= 0.19)."""
monkeypatch.setenv("FOCUS_PROJECT_DATA", str(tmp_path / "focus_project")) monkeypatch.setenv("FOCUS_PROJECT_DATA", str(tmp_path / "focus_project"))
@pytest.fixture(autouse=True)
def _no_real_holds(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Point ``holds`` at an empty file: a real hold must not mute the ladder.
Without this the suite would read ``~/.local/share/holds/holds.json`` and
every ladder test would start failing inside a declared test hold.
"""
monkeypatch.setenv("HOLDS_DATA", str(tmp_path / "holds-none.json"))

View File

@ -0,0 +1,137 @@
"""Builders for the RunnerUp retirement tests: TCX files, marker, credit log."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
import json
from typing import TYPE_CHECKING, Any
from screen_locker._runnerup_retire import Paths
from screen_locker._runnerup_retire_adb import AdbError, Device
if TYPE_CHECKING:
from pathlib import Path
_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
APP = "kuhy workout_app"
# 2026-11-01T10:30:00Z, the end of every TCX built by default.
END_UNIX = 1793529000.0
def tcx_text(
*, author: str = "RunnerUp", creator: str = "", end: str = "2026-11-01T10:30:00Z"
) -> str:
"""A tiny TCX: two trackpoints (the last is the run's end) and an author."""
creator_xml = f"<Creator><Name>{creator}</Name></Creator>" if creator else ""
return (
f'<?xml version="1.0"?><TrainingCenterDatabase xmlns="{_NS}"><Activities>'
'<Activity Sport="Running"><Id>2026-11-01T10:00:00Z</Id>'
"<Lap><TotalTimeSeconds>1800</TotalTimeSeconds>"
"<DistanceMeters>5000</DistanceMeters><Track>"
"<Trackpoint><Time>2026-11-01T10:00:00Z</Time>"
"<DistanceMeters>0</DistanceMeters></Trackpoint>"
f"<Trackpoint><Time>{end}</Time><DistanceMeters>5000</DistanceMeters>"
f"</Trackpoint></Track></Lap>{creator_xml}</Activity></Activities>"
f'<Author xsi:type="Application_t" xmlns:xsi="x"><Name>{author}</Name>'
"</Author></TrainingCenterDatabase>"
)
def put_tcx(folder: Path, name: str, **kwargs: str) -> Path:
"""Write a TCX named ``name`` into ``folder`` (created if needed)."""
folder.mkdir(parents=True, exist_ok=True)
path = folder / name
path.write_text(tcx_text(**kwargs), encoding="utf-8")
return path
def put_marker(watch: Path, names: list[str], count: int | None = None) -> Path:
"""Write the app's import marker into the drop folder."""
watch.mkdir(parents=True, exist_ok=True)
marker = watch / ".workout_app_import.json"
body = {
"completed_at": "2026-11-02T08:00:00Z",
"count": len(names) if count is None else count,
"tcx_names": names,
}
marker.write_text(json.dumps(body), encoding="utf-8")
return marker
def put_log(log_file: Path, entries: dict[str, list[dict[str, Any]]]) -> None:
"""Write a day-keyed credit log."""
log_file.write_text(json.dumps(entries), encoding="utf-8")
def credit(
timestamp: str, completed_at: object = None, kind: str = "runnerup_verified"
) -> dict[str, Any]:
"""One log entry as the credit chokepoint writes it."""
data: dict[str, Any] = {"type": kind}
if completed_at is not None:
data["completed_at"] = completed_at
return {"timestamp": timestamp, "workout_data": data}
ANCHOR = datetime(2026, 11, 1, 10, 45, tzinfo=UTC)
DUE = ANCHOR + timedelta(days=7)
RUN = "RunnerUp_2026-08-12-17-42-11_Running.tcx"
@dataclass
class FakePhone:
"""Records what the retirement asked of the phone."""
adb: bool = True
device: Device = field(default_factory=lambda: Device("S", "attached"))
present: bool = True
ask_error: AdbError | None = None
backup_error: Exception | None = None
uninstall_error: AdbError | None = None
calls: list[str] = field(default_factory=list)
def available(self) -> bool:
"""Available."""
return self.adb
def find_device(self) -> Device:
"""Find device."""
if self.ask_error:
raise self.ask_error
return self.device
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Installed."""
self.calls.append(f"installed {dev}")
return self.present
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Backup."""
self.calls.append("backup")
if self.backup_error:
raise self.backup_error
final.mkdir(parents=True)
return final, 3
def uninstall(self, dev: str) -> None:
"""Uninstall."""
self.calls.append("uninstall")
if self.uninstall_error:
raise self.uninstall_error
def world(tmp_path: Path, *, anchored: bool = True, marker: bool = True) -> Paths:
"""A drop folder with one RunnerUp run, one app run, and the credit log."""
paths = Paths(
tmp_path / "state" / "s.json", tmp_path / "drop", tmp_path / "log.json"
)
put_tcx(paths.processed, RUN)
put_tcx(paths.processed, "app.tcx", author=APP)
put_log(
paths.log_file,
{"d": [credit(ANCHOR.isoformat(), END_UNIX)]} if anchored else {},
)
if marker:
put_marker(paths.watch_dir, [RUN])
return paths

View File

@ -0,0 +1,28 @@
"""Hold only whole-suite runs to pyproject's ``fail_under = 100``.
A ``-k`` run selects a handful of tests, so its total coverage is always far
below 100% and pytest-cov turned every green ``pytest -q -k <name>`` (the
board's done_check form) into exit 1. The commit gate, the nightly
``full_gate.sh`` and CI select no keyword, so they keep the bar. Path-selected
partial runs (``test_changed.sh``, ``push_gate.sh``) pass ``--no-cov``
themselves and are untouched.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import pytest
def pytest_sessionstart(session: pytest.Session) -> None:
"""Drop the coverage bar for a ``-k`` keyword-selected run.
pytest-cov copies ``fail_under`` into its options when coverage starts
(before this hook) and checks it at the end; ``None`` skips the check.
"""
config = session.config
cov = config.pluginmanager.getplugin("_cov")
if cov is not None and config.option.keyword:
cov.options.cov_fail_under = None

View File

@ -37,7 +37,7 @@ def setup_unlock(
if seed_today_type is None: if seed_today_type is None:
log_file.write_text("{}") log_file.write_text("{}")
else: else:
today = datetime.now(tz=UTC).strftime("%Y-%m-%d") today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
log_file.write_text( log_file.write_text(
json.dumps( json.dumps(
{ {

View File

@ -29,7 +29,6 @@ from screen_locker.tests._gatelock_fixtures import (
dual_output, dual_output,
) )
from screen_locker.tests._isolated_state import ISOLATED_STATE from screen_locker.tests._isolated_state import ISOLATED_STATE
from screen_locker.tests._late_credit_fixtures import _untimed_credits_land_at_noon
from screen_locker.tests._locker_factories import ( from screen_locker.tests._locker_factories import (
_make_locker, _make_locker,
create_locker, create_locker,
@ -57,7 +56,6 @@ __all__ = [
"_hermetic_gatelock", "_hermetic_gatelock",
"_make_locker", "_make_locker",
"_mock_sys_exit", "_mock_sys_exit",
"_untimed_credits_land_at_noon",
"create_locker", "create_locker",
"create_locker_early_bird", "create_locker_early_bird",
"create_locker_relaxed_day", "create_locker_relaxed_day",
@ -98,6 +96,8 @@ def _block_real_tk_and_exit() -> Iterator[None]:
# The startup early-exit checks moved to _startup_checks; sys.exit is # The startup early-exit checks moved to _startup_checks; sys.exit is
# bound there now, so it needs blocking separately. # bound there now, so it needs blocking separately.
stack.enter_context(patch("screen_locker._startup_checks.sys.exit")) stack.enter_context(patch("screen_locker._startup_checks.sys.exit"))
# kuhy_credit's logo is a real tk.Canvas: swap it too.
stack.enter_context(patch("screen_locker._credit.KuhyCredit"))
yield yield
@ -199,7 +199,8 @@ def _isolate_shutdown_base(tmp_path: Path) -> Iterator[None]:
refresh sees an empty unit dir, never the real one. refresh sees an empty unit dir, never the real one.
""" """
target = tmp_path / "shutdown_base.json" target = tmp_path / "shutdown_base.json"
today = datetime.now(tz=UTC).strftime("%Y-%m-%d") # Local day, as the code compares it (_day.today_str), not the UTC one.
today = datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
target.write_text(json.dumps(dict.fromkeys(["last_reset_date", *_BONUS], today))) target.write_text(json.dumps(dict.fromkeys(["last_reset_date", *_BONUS], today)))
with ( with (
patch("screen_locker._constants.SHUTDOWN_BASE_FILE", target), patch("screen_locker._constants.SHUTDOWN_BASE_FILE", target),

View File

@ -0,0 +1,190 @@
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns3="http://www.garmin.com/xmlschemas/ActivityExtension/v2" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Running">
<Id>2026-08-12T15:42:11Z</Id>
<Lap StartTime="2026-08-12T15:42:11Z">
<TotalTimeSeconds>624</TotalTimeSeconds>
<DistanceMeters>983.6306355595589</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-08-12T15:42:12Z</Time>
<Position>
<LatitudeDegrees>48.858438076</LatitudeDegrees>
<LongitudeDegrees>2.294584871</LongitudeDegrees>
</Position>
<AltitudeMeters>110.06611511572041</AltitudeMeters>
<DistanceMeters>2.142966628074646</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>54</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:13Z</Time>
<Position>
<LatitudeDegrees>48.858442867</LatitudeDegrees>
<LongitudeDegrees>2.294574705</LongitudeDegrees>
</Position>
<AltitudeMeters>109.65041623678366</AltitudeMeters>
<DistanceMeters>3.0187163949012756</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>53</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:37Z</Time>
<Position>
<LatitudeDegrees>48.858578090</LatitudeDegrees>
<LongitudeDegrees>2.294260282</LongitudeDegrees>
</Position>
<AltitudeMeters>102.71014718222068</AltitudeMeters>
<DistanceMeters>31.116633534431458</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>65</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:48Z</Time>
<Position>
<LatitudeDegrees>48.858744365</LatitudeDegrees>
<LongitudeDegrees>2.294188828</LongitudeDegrees>
</Position>
<AltitudeMeters>101.26072111921606</AltitudeMeters>
<DistanceMeters>50.64840912818909</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>61</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:56Z</Time>
<Position>
<LatitudeDegrees>48.858792955</LatitudeDegrees>
<LongitudeDegrees>2.294100028</LongitudeDegrees>
</Position>
<AltitudeMeters>100.58585072961351</AltitudeMeters>
<DistanceMeters>58.97427588701248</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>58</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:43:42Z</Time>
<Position>
<LatitudeDegrees>48.858859857</LatitudeDegrees>
<LongitudeDegrees>2.292925949</LongitudeDegrees>
</Position>
<AltitudeMeters>99.60869064520372</AltitudeMeters>
<DistanceMeters>140.32738709449768</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>57</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
</Track>
</Lap>
<Lap StartTime="2026-08-12T15:52:36Z">
<TotalTimeSeconds>626</TotalTimeSeconds>
<DistanceMeters>980.7304027080536</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-08-12T15:52:36Z</Time>
<Position>
<LatitudeDegrees>48.859968549</LatitudeDegrees>
<LongitudeDegrees>2.282023519</LongitudeDegrees>
</Position>
<AltitudeMeters>99.76934097304894</AltitudeMeters>
<DistanceMeters>1003.5486820391379</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>59</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:52:37Z</Time>
<Position>
<LatitudeDegrees>48.859990492</LatitudeDegrees>
<LongitudeDegrees>2.282025531</LongitudeDegrees>
</Position>
<AltitudeMeters>100.06562741186055</AltitudeMeters>
<DistanceMeters>1005.9941445044242</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>57</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:54:28Z</Time>
<Position>
<LatitudeDegrees>48.861645306</LatitudeDegrees>
<LongitudeDegrees>2.281974721</LongitudeDegrees>
</Position>
<AltitudeMeters>99.66943152941295</AltitudeMeters>
<DistanceMeters>1190.9687945595942</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>55</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:54:46Z</Time>
<Position>
<LatitudeDegrees>48.861872213</LatitudeDegrees>
<LongitudeDegrees>2.282046494</LongitudeDegrees>
</Position>
<AltitudeMeters>99.35286804810477</AltitudeMeters>
<DistanceMeters>1217.0878333947621</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>58</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
</Track>
</Lap>
<Notes></Notes>
<Creator xsi:type="Device_t">
<Name>RunnerUp Pixel 6a with barometer</Name>
<UnitId>0</UnitId>
<ProductID>0</ProductID>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<BuildMajor>0</BuildMajor>
<BuildMinor>0</BuildMinor>
</Version>
</Creator>
</Activity>
</Activities>
<Author xsi:type="Application_t">
<Name>org.runnerup - 2.11.0.1 - 23000372</Name>
<Build>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Build>
<LangID>en</LangID>
<PartNumber>000-00000-00</PartNumber>
</Author>
</TrainingCenterDatabase>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,748 @@
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Running">
<Id>2026-11-09T16:30:00Z</Id>
<Lap StartTime="2026-11-09T16:30:00Z">
<TotalTimeSeconds>1560</TotalTimeSeconds>
<DistanceMeters>4212.014</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-11-09T16:30:00Z</Time>
<Position>
<LatitudeDegrees>48.8584000</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>0.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:30:20Z</Time>
<Position>
<LatitudeDegrees>48.8587720</LatitudeDegrees>
<LongitudeDegrees>2.2949745</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>54.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:30:40Z</Time>
<Position>
<LatitudeDegrees>48.8591285</LatitudeDegrees>
<LongitudeDegrees>2.2954757</LongitudeDegrees>
</Position>
<AltitudeMeters>35.3</AltitudeMeters>
<DistanceMeters>107.999</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:00Z</Time>
<Position>
<LatitudeDegrees>48.8594688</LatitudeDegrees>
<LongitudeDegrees>2.2960023</LongitudeDegrees>
</Position>
<AltitudeMeters>35.5</AltitudeMeters>
<DistanceMeters>161.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:20Z</Time>
<Position>
<LatitudeDegrees>48.8597926</LatitudeDegrees>
<LongitudeDegrees>2.2965524</LongitudeDegrees>
</Position>
<AltitudeMeters>35.8</AltitudeMeters>
<DistanceMeters>215.997</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:40Z</Time>
<Position>
<LatitudeDegrees>48.8600999</LatitudeDegrees>
<LongitudeDegrees>2.2971240</LongitudeDegrees>
</Position>
<AltitudeMeters>36.1</AltitudeMeters>
<DistanceMeters>269.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:00Z</Time>
<Position>
<LatitudeDegrees>48.8603909</LatitudeDegrees>
<LongitudeDegrees>2.2977150</LongitudeDegrees>
</Position>
<AltitudeMeters>36.3</AltitudeMeters>
<DistanceMeters>324.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:20Z</Time>
<Position>
<LatitudeDegrees>48.8606663</LatitudeDegrees>
<LongitudeDegrees>2.2983230</LongitudeDegrees>
</Position>
<AltitudeMeters>36.6</AltitudeMeters>
<DistanceMeters>378.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:40Z</Time>
<Position>
<LatitudeDegrees>48.8609269</LatitudeDegrees>
<LongitudeDegrees>2.2989459</LongitudeDegrees>
</Position>
<AltitudeMeters>36.8</AltitudeMeters>
<DistanceMeters>432.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:00Z</Time>
<Position>
<LatitudeDegrees>48.8611740</LatitudeDegrees>
<LongitudeDegrees>2.2995813</LongitudeDegrees>
</Position>
<AltitudeMeters>37.0</AltitudeMeters>
<DistanceMeters>485.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:20Z</Time>
<Position>
<LatitudeDegrees>48.8614092</LatitudeDegrees>
<LongitudeDegrees>2.3002272</LongitudeDegrees>
</Position>
<AltitudeMeters>37.2</AltitudeMeters>
<DistanceMeters>540.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:40Z</Time>
<Position>
<LatitudeDegrees>48.8616342</LatitudeDegrees>
<LongitudeDegrees>2.3008814</LongitudeDegrees>
</Position>
<AltitudeMeters>37.4</AltitudeMeters>
<DistanceMeters>594.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:00Z</Time>
<Position>
<LatitudeDegrees>48.8618509</LatitudeDegrees>
<LongitudeDegrees>2.3015420</LongitudeDegrees>
</Position>
<AltitudeMeters>37.5</AltitudeMeters>
<DistanceMeters>648.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:20Z</Time>
<Position>
<LatitudeDegrees>48.8620615</LatitudeDegrees>
<LongitudeDegrees>2.3022071</LongitudeDegrees>
</Position>
<AltitudeMeters>37.7</AltitudeMeters>
<DistanceMeters>702.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:40Z</Time>
<Position>
<LatitudeDegrees>48.8622683</LatitudeDegrees>
<LongitudeDegrees>2.3028751</LongitudeDegrees>
</Position>
<AltitudeMeters>37.8</AltitudeMeters>
<DistanceMeters>756.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:00Z</Time>
<Position>
<LatitudeDegrees>48.8624735</LatitudeDegrees>
<LongitudeDegrees>2.3035441</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>810.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:20Z</Time>
<Position>
<LatitudeDegrees>48.8626796</LatitudeDegrees>
<LongitudeDegrees>2.3042125</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>864.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:40Z</Time>
<Position>
<LatitudeDegrees>48.8628890</LatitudeDegrees>
<LongitudeDegrees>2.3048786</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>918.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:00Z</Time>
<Position>
<LatitudeDegrees>48.8631038</LatitudeDegrees>
<LongitudeDegrees>2.3055406</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>972.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:20Z</Time>
<Position>
<LatitudeDegrees>48.8633263</LatitudeDegrees>
<LongitudeDegrees>2.3061968</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>1026.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:40Z</Time>
<Position>
<LatitudeDegrees>48.8635585</LatitudeDegrees>
<LongitudeDegrees>2.3068452</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>1080.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:00Z</Time>
<Position>
<LatitudeDegrees>48.8638022</LatitudeDegrees>
<LongitudeDegrees>2.3074837</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>1134.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:20Z</Time>
<Position>
<LatitudeDegrees>48.8640589</LatitudeDegrees>
<LongitudeDegrees>2.3081103</LongitudeDegrees>
</Position>
<AltitudeMeters>37.8</AltitudeMeters>
<DistanceMeters>1188.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:40Z</Time>
<Position>
<LatitudeDegrees>48.8643301</LatitudeDegrees>
<LongitudeDegrees>2.3087227</LongitudeDegrees>
</Position>
<AltitudeMeters>37.7</AltitudeMeters>
<DistanceMeters>1242.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:00Z</Time>
<Position>
<LatitudeDegrees>48.8646168</LatitudeDegrees>
<LongitudeDegrees>2.3093186</LongitudeDegrees>
</Position>
<AltitudeMeters>37.6</AltitudeMeters>
<DistanceMeters>1296.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:20Z</Time>
<Position>
<LatitudeDegrees>48.8649196</LatitudeDegrees>
<LongitudeDegrees>2.3098958</LongitudeDegrees>
</Position>
<AltitudeMeters>37.5</AltitudeMeters>
<DistanceMeters>1350.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:40Z</Time>
<Position>
<LatitudeDegrees>48.8652388</LatitudeDegrees>
<LongitudeDegrees>2.3104521</LongitudeDegrees>
</Position>
<AltitudeMeters>37.3</AltitudeMeters>
<DistanceMeters>1404.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:00Z</Time>
<Position>
<LatitudeDegrees>48.8655746</LatitudeDegrees>
<LongitudeDegrees>2.3109853</LongitudeDegrees>
</Position>
<AltitudeMeters>37.1</AltitudeMeters>
<DistanceMeters>1457.999</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:20Z</Time>
<Position>
<LatitudeDegrees>48.8659267</LatitudeDegrees>
<LongitudeDegrees>2.3114938</LongitudeDegrees>
</Position>
<AltitudeMeters>36.9</AltitudeMeters>
<DistanceMeters>1512.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:40Z</Time>
<Position>
<LatitudeDegrees>48.8662946</LatitudeDegrees>
<LongitudeDegrees>2.3119758</LongitudeDegrees>
</Position>
<AltitudeMeters>36.7</AltitudeMeters>
<DistanceMeters>1566.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:00Z</Time>
<Position>
<LatitudeDegrees>48.8666773</LatitudeDegrees>
<LongitudeDegrees>2.3124302</LongitudeDegrees>
</Position>
<AltitudeMeters>36.5</AltitudeMeters>
<DistanceMeters>1620.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:20Z</Time>
<Position>
<LatitudeDegrees>48.8670740</LatitudeDegrees>
<LongitudeDegrees>2.3128561</LongitudeDegrees>
</Position>
<AltitudeMeters>36.2</AltitudeMeters>
<DistanceMeters>1674.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:40Z</Time>
<Position>
<LatitudeDegrees>48.8674834</LatitudeDegrees>
<LongitudeDegrees>2.3132533</LongitudeDegrees>
</Position>
<AltitudeMeters>36.0</AltitudeMeters>
<DistanceMeters>1728.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:00Z</Time>
<Position>
<LatitudeDegrees>48.8679042</LatitudeDegrees>
<LongitudeDegrees>2.3136218</LongitudeDegrees>
</Position>
<AltitudeMeters>35.7</AltitudeMeters>
<DistanceMeters>1782.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:20Z</Time>
<Position>
<LatitudeDegrees>48.8683351</LatitudeDegrees>
<LongitudeDegrees>2.3139623</LongitudeDegrees>
</Position>
<AltitudeMeters>35.4</AltitudeMeters>
<DistanceMeters>1836.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:40Z</Time>
<Position>
<LatitudeDegrees>48.8687747</LatitudeDegrees>
<LongitudeDegrees>2.3142760</LongitudeDegrees>
</Position>
<AltitudeMeters>35.2</AltitudeMeters>
<DistanceMeters>1890.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:00Z</Time>
<Position>
<LatitudeDegrees>48.8692217</LatitudeDegrees>
<LongitudeDegrees>2.3145646</LongitudeDegrees>
</Position>
<AltitudeMeters>34.9</AltitudeMeters>
<DistanceMeters>1944.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:20Z</Time>
<Position>
<LatitudeDegrees>48.8696748</LatitudeDegrees>
<LongitudeDegrees>2.3148301</LongitudeDegrees>
</Position>
<AltitudeMeters>34.6</AltitudeMeters>
<DistanceMeters>1998.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:40Z</Time>
<Position>
<LatitudeDegrees>48.8701329</LatitudeDegrees>
<LongitudeDegrees>2.3150752</LongitudeDegrees>
</Position>
<AltitudeMeters>34.3</AltitudeMeters>
<DistanceMeters>2052.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:00Z</Time>
<Position>
<LatitudeDegrees>48.8705949</LatitudeDegrees>
<LongitudeDegrees>2.3153027</LongitudeDegrees>
</Position>
<AltitudeMeters>34.1</AltitudeMeters>
<DistanceMeters>2106.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:20Z</Time>
<Position>
<LatitudeDegrees>48.8710599</LatitudeDegrees>
<LongitudeDegrees>2.3155157</LongitudeDegrees>
</Position>
<AltitudeMeters>33.8</AltitudeMeters>
<DistanceMeters>2160.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:40Z</Time>
<Position>
<LatitudeDegrees>48.8715270</LatitudeDegrees>
<LongitudeDegrees>2.3157179</LongitudeDegrees>
</Position>
<AltitudeMeters>33.6</AltitudeMeters>
<DistanceMeters>2214.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:00Z</Time>
<Position>
<LatitudeDegrees>48.8719954</LatitudeDegrees>
<LongitudeDegrees>2.3159128</LongitudeDegrees>
</Position>
<AltitudeMeters>33.3</AltitudeMeters>
<DistanceMeters>2268.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:20Z</Time>
<Position>
<LatitudeDegrees>48.8724644</LatitudeDegrees>
<LongitudeDegrees>2.3161042</LongitudeDegrees>
</Position>
<AltitudeMeters>33.1</AltitudeMeters>
<DistanceMeters>2322.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:40Z</Time>
<Position>
<LatitudeDegrees>48.8729334</LatitudeDegrees>
<LongitudeDegrees>2.3162960</LongitudeDegrees>
</Position>
<AltitudeMeters>32.9</AltitudeMeters>
<DistanceMeters>2376.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:00Z</Time>
<Position>
<LatitudeDegrees>48.8734016</LatitudeDegrees>
<LongitudeDegrees>2.3164919</LongitudeDegrees>
</Position>
<AltitudeMeters>32.7</AltitudeMeters>
<DistanceMeters>2430.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:20Z</Time>
<Position>
<LatitudeDegrees>48.8738683</LatitudeDegrees>
<LongitudeDegrees>2.3166958</LongitudeDegrees>
</Position>
<AltitudeMeters>32.6</AltitudeMeters>
<DistanceMeters>2484.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:40Z</Time>
<Position>
<LatitudeDegrees>48.8743329</LatitudeDegrees>
<LongitudeDegrees>2.3169112</LongitudeDegrees>
</Position>
<AltitudeMeters>32.4</AltitudeMeters>
<DistanceMeters>2538.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:00Z</Time>
<Position>
<LatitudeDegrees>48.8747943</LatitudeDegrees>
<LongitudeDegrees>2.3171416</LongitudeDegrees>
</Position>
<AltitudeMeters>32.3</AltitudeMeters>
<DistanceMeters>2592.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:20Z</Time>
<Position>
<LatitudeDegrees>48.8752516</LatitudeDegrees>
<LongitudeDegrees>2.3173901</LongitudeDegrees>
</Position>
<AltitudeMeters>32.2</AltitudeMeters>
<DistanceMeters>2646.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:40Z</Time>
<Position>
<LatitudeDegrees>48.8757037</LatitudeDegrees>
<LongitudeDegrees>2.3176595</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>2700.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:00Z</Time>
<Position>
<LatitudeDegrees>48.8761495</LatitudeDegrees>
<LongitudeDegrees>2.3179525</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2754.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:20Z</Time>
<Position>
<LatitudeDegrees>48.8765876</LatitudeDegrees>
<LongitudeDegrees>2.3182709</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2808.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:40Z</Time>
<Position>
<LatitudeDegrees>48.8770168</LatitudeDegrees>
<LongitudeDegrees>2.3186164</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2862.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:00Z</Time>
<Position>
<LatitudeDegrees>48.8774357</LatitudeDegrees>
<LongitudeDegrees>2.3189900</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2916.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:20Z</Time>
<Position>
<LatitudeDegrees>48.8778429</LatitudeDegrees>
<LongitudeDegrees>2.3193923</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>2970.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:40Z</Time>
<Position>
<LatitudeDegrees>48.8782372</LatitudeDegrees>
<LongitudeDegrees>2.3198234</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>3024.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:00Z</Time>
<Position>
<LatitudeDegrees>48.8786174</LatitudeDegrees>
<LongitudeDegrees>2.3202829</LongitudeDegrees>
</Position>
<AltitudeMeters>32.2</AltitudeMeters>
<DistanceMeters>3078.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:20Z</Time>
<Position>
<LatitudeDegrees>48.8789825</LatitudeDegrees>
<LongitudeDegrees>2.3207698</LongitudeDegrees>
</Position>
<AltitudeMeters>32.3</AltitudeMeters>
<DistanceMeters>3132.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:40Z</Time>
<Position>
<LatitudeDegrees>48.8793318</LatitudeDegrees>
<LongitudeDegrees>2.3212829</LongitudeDegrees>
</Position>
<AltitudeMeters>32.5</AltitudeMeters>
<DistanceMeters>3186.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:00Z</Time>
<Position>
<LatitudeDegrees>48.8796647</LatitudeDegrees>
<LongitudeDegrees>2.3218205</LongitudeDegrees>
</Position>
<AltitudeMeters>32.6</AltitudeMeters>
<DistanceMeters>3240.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:20Z</Time>
<Position>
<LatitudeDegrees>48.8799810</LatitudeDegrees>
<LongitudeDegrees>2.3223808</LongitudeDegrees>
</Position>
<AltitudeMeters>32.8</AltitudeMeters>
<DistanceMeters>3294.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:40Z</Time>
<Position>
<LatitudeDegrees>48.8802809</LatitudeDegrees>
<LongitudeDegrees>2.3229617</LongitudeDegrees>
</Position>
<AltitudeMeters>33.0</AltitudeMeters>
<DistanceMeters>3348.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:00Z</Time>
<Position>
<LatitudeDegrees>48.8805647</LatitudeDegrees>
<LongitudeDegrees>2.3235609</LongitudeDegrees>
</Position>
<AltitudeMeters>33.2</AltitudeMeters>
<DistanceMeters>3402.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:20Z</Time>
<Position>
<LatitudeDegrees>48.8808333</LatitudeDegrees>
<LongitudeDegrees>2.3241761</LongitudeDegrees>
</Position>
<AltitudeMeters>33.4</AltitudeMeters>
<DistanceMeters>3456.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:40Z</Time>
<Position>
<LatitudeDegrees>48.8810877</LatitudeDegrees>
<LongitudeDegrees>2.3248052</LongitudeDegrees>
</Position>
<AltitudeMeters>33.7</AltitudeMeters>
<DistanceMeters>3510.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:00Z</Time>
<Position>
<LatitudeDegrees>48.8813292</LatitudeDegrees>
<LongitudeDegrees>2.3254458</LongitudeDegrees>
</Position>
<AltitudeMeters>33.9</AltitudeMeters>
<DistanceMeters>3564.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:20Z</Time>
<Position>
<LatitudeDegrees>48.8815595</LatitudeDegrees>
<LongitudeDegrees>2.3260960</LongitudeDegrees>
</Position>
<AltitudeMeters>34.2</AltitudeMeters>
<DistanceMeters>3618.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:40Z</Time>
<Position>
<LatitudeDegrees>48.8817805</LatitudeDegrees>
<LongitudeDegrees>2.3267536</LongitudeDegrees>
</Position>
<AltitudeMeters>34.4</AltitudeMeters>
<DistanceMeters>3672.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:00Z</Time>
<Position>
<LatitudeDegrees>48.8819942</LatitudeDegrees>
<LongitudeDegrees>2.3274167</LongitudeDegrees>
</Position>
<AltitudeMeters>34.7</AltitudeMeters>
<DistanceMeters>3726.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:20Z</Time>
<Position>
<LatitudeDegrees>48.8822028</LatitudeDegrees>
<LongitudeDegrees>2.3280836</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>3780.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:40Z</Time>
<Position>
<LatitudeDegrees>48.8824086</LatitudeDegrees>
<LongitudeDegrees>2.3287525</LongitudeDegrees>
</Position>
<AltitudeMeters>35.2</AltitudeMeters>
<DistanceMeters>3834.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:00Z</Time>
<Position>
<LatitudeDegrees>48.8826139</LatitudeDegrees>
<LongitudeDegrees>2.3294217</LongitudeDegrees>
</Position>
<AltitudeMeters>35.5</AltitudeMeters>
<DistanceMeters>3888.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:20Z</Time>
<Position>
<LatitudeDegrees>48.8828212</LatitudeDegrees>
<LongitudeDegrees>2.3300896</LongitudeDegrees>
</Position>
<AltitudeMeters>35.8</AltitudeMeters>
<DistanceMeters>3942.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:40Z</Time>
<Position>
<LatitudeDegrees>48.8830327</LatitudeDegrees>
<LongitudeDegrees>2.3307543</LongitudeDegrees>
</Position>
<AltitudeMeters>36.0</AltitudeMeters>
<DistanceMeters>3996.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:00Z</Time>
<Position>
<LatitudeDegrees>48.8832508</LatitudeDegrees>
<LongitudeDegrees>2.3314142</LongitudeDegrees>
</Position>
<AltitudeMeters>36.3</AltitudeMeters>
<DistanceMeters>4050.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:20Z</Time>
<Position>
<LatitudeDegrees>48.8834774</LatitudeDegrees>
<LongitudeDegrees>2.3320674</LongitudeDegrees>
</Position>
<AltitudeMeters>36.5</AltitudeMeters>
<DistanceMeters>4104.014</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:40Z</Time>
<Position>
<LatitudeDegrees>48.8837145</LatitudeDegrees>
<LongitudeDegrees>2.3327118</LongitudeDegrees>
</Position>
<AltitudeMeters>36.8</AltitudeMeters>
<DistanceMeters>4158.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:56:00Z</Time>
<Position>
<LatitudeDegrees>48.8839640</LatitudeDegrees>
<LongitudeDegrees>2.3333455</LongitudeDegrees>
</Position>
<AltitudeMeters>37.0</AltitudeMeters>
<DistanceMeters>4212.014</DistanceMeters>
</Trackpoint>
</Track>
</Lap>
<Creator xsi:type="Device_t">
<Name>kuhy workout_app</Name>
<UnitId>0</UnitId>
<ProductID>0</ProductID>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Creator>
</Activity>
</Activities>
<Author xsi:type="Application_t">
<Name>kuhy workout_app</Name>
<Build>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Build>
<LangID>en</LangID>
<PartNumber>000-00000-00</PartNumber>
</Author>
</TrainingCenterDatabase>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,193 @@
"""An armed lock takes itself down when wake-alarm's signed carrot lands late.
2026-11-07: the lock armed at 07:49 because today's morning_session.json had
not landed; it landed at 07:50 and nothing re-read it, so the morning session
ran under a fullscreen lock.
"""
from __future__ import annotations
from datetime import datetime, timedelta
import json
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from gatelock.log_integrity import compute_entry_hmac
import pytest
from screen_locker import _carrot_watch, _morning_session
from screen_locker._carrot_watch import POLL_MS, watch_for_carrot
from screen_locker._morning_session import MorningSkip
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
_EIGHT = datetime(2026, 11, 7, 8, 0).astimezone()
@pytest.fixture(autouse=True)
def _signing_key(tmp_path: Path) -> Iterator[None]:
key = tmp_path / "hmac.key"
key.write_bytes(b"1" * 32)
with patch("gatelock.log_integrity.DEFAULT_HMAC_KEY_FILE", key):
yield
def _sign(date: str, until: datetime) -> None:
"""Write a signed session file into the conftest-redirected path."""
entry: dict[str, object] = {
"date": date,
"outcome": "in_progress",
"exempt_until": until.isoformat(),
}
entry["hmac"] = compute_entry_hmac(entry)
_morning_session.MORNING_SESSION_FILE.write_text(json.dumps(entry))
def _tick(now: datetime) -> tuple[MagicMock, MagicMock]:
"""Arm the watch, run its first poll at ``now``; return (root, on_carrot)."""
root, on_carrot = MagicMock(), MagicMock()
watch_for_carrot(root, on_carrot)
with patch.object(_carrot_watch, "_local_now", return_value=now):
root.after.call_args.args[1]()
return root, on_carrot
class TestWatchForCarrot:
"""The poll on the Tk loop."""
def test_local_now_is_timezone_aware_local_time(self) -> None:
"""The poll's clock is the real, aware local time."""
assert abs(_carrot_watch._local_now() - datetime.now().astimezone()) < (
timedelta(seconds=5)
)
def test_arms_a_fifteen_second_poll(self) -> None:
"""Arming schedules the first check 15 s out and releases nothing."""
root, on_carrot = MagicMock(), MagicMock()
watch_for_carrot(root, on_carrot)
assert POLL_MS == 15_000
assert root.after.call_args.args[0] == POLL_MS
on_carrot.assert_not_called()
def test_signed_todays_skip_releases_once_and_stops_polling(self) -> None:
"""A skip that landed after arming is handed over; no re-arm."""
until = _EIGHT + timedelta(hours=1, minutes=13)
_sign("2026-11-07", until)
root, on_carrot = _tick(_EIGHT)
on_carrot.assert_called_once_with(MorningSkip("in_progress", until))
assert root.after.call_count == 1
def test_no_file_keeps_the_lock_and_reschedules(self) -> None:
"""No file: the lock stays and the next poll is scheduled."""
root, on_carrot = _tick(_EIGHT)
on_carrot.assert_not_called()
assert root.after.call_count == 2
assert root.after.call_args.args[0] == POLL_MS
def test_expired_skip_keeps_the_lock(self) -> None:
"""A carrot whose exempt_until has passed is no skip."""
_sign("2026-11-07", _EIGHT - timedelta(minutes=1))
root, on_carrot = _tick(_EIGHT)
on_carrot.assert_not_called()
assert root.after.call_count == 2
def test_yesterdays_file_keeps_the_lock(self) -> None:
"""A file dated another day is no skip."""
_sign("2026-11-06", _EIGHT + timedelta(hours=3))
_root, on_carrot = _tick(_EIGHT)
on_carrot.assert_not_called()
@pytest.mark.parametrize(("hour", "minute"), [(4, 59), (11, 0), (23, 30)])
def test_outside_05_to_11_never_reads_or_releases(
self, hour: int, minute: int
) -> None:
"""Outside 05:00-11:00 local the poll neither reads nor releases."""
now = _EIGHT.replace(hour=hour, minute=minute)
_sign("2026-11-07", now + timedelta(hours=1))
with patch.object(_carrot_watch._morning_session, "morning_skip_today") as read:
root, on_carrot = _tick(now)
read.assert_not_called()
on_carrot.assert_not_called()
assert root.after.call_count == 2
def test_inside_window_reads_without_waiting(self) -> None:
"""The poll never waits: it must not block the Tk loop."""
with patch.object(
_carrot_watch._morning_session, "morning_skip_today", return_value=None
) as read:
_tick(_EIGHT)
read.assert_called_once_with(_EIGHT, wait=False)
def test_reader_failure_is_logged_and_the_poll_survives(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A read error warns and re-arms; one bad read must not end the watch."""
with (
patch.object(
_carrot_watch._morning_session,
"morning_skip_today",
side_effect=OSError("disk gone"),
),
caplog.at_level(logging.WARNING, logger="screen_locker._carrot_watch"),
):
root, on_carrot = _tick(_EIGHT)
on_carrot.assert_not_called()
assert root.after.call_count == 2
assert "disk gone" in caplog.text
class TestLockerStandsDown:
"""The locker side: marker, decision, warning, then the real close."""
def test_construction_arms_the_watch(
self, mock_tk: MagicMock, tmp_path: Path
) -> None:
"""A built locker watches on its own root and its own stand-down."""
with patch("screen_locker.screen_lock.watch_for_carrot") as watch:
locker = create_locker(mock_tk, tmp_path)
watch.assert_called_once_with(locker.root, locker._stand_down_for_carrot)
def test_stand_down_banks_marker_records_decision_then_closes(
self,
mock_tk: MagicMock,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Marker first, decision lock=no, warning, and only then close()."""
locker = create_locker(mock_tk, tmp_path)
until = _EIGHT + timedelta(hours=1)
order = MagicMock()
with (
patch.object(locker, "_save_early_bird_pending", order.save),
patch("screen_locker._auto_upgrade.record_decision", order.record),
patch.object(locker, "close", order.close),
caplog.at_level(logging.WARNING, logger="screen_locker._auto_upgrade"),
):
locker._stand_down_for_carrot(MorningSkip("in_progress", until))
assert [c[0] for c in order.mock_calls] == ["save", "record", "close"]
decision = order.record.call_args.args[0]
assert decision.locked is False
assert decision.reason == "wake_alarm_skip_late"
assert decision.extra["exempt_until"] == until.isoformat()
assert decision.extra["outcome"] == "in_progress"
assert "carrot" in caplog.text.lower()
def test_stand_down_goes_through_the_real_close_and_exits_zero(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""The real ``close``: lock window released, instance lock dropped, exit 0."""
locker = create_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_save_early_bird_pending"),
patch("screen_locker._auto_upgrade.record_decision"),
patch.object(locker, "_lock") as lock,
patch.object(locker._instance_lock, "release") as release,
):
locker._stand_down_for_carrot(MorningSkip("completed", _EIGHT))
lock.close.assert_called_once_with()
release.assert_called_once_with()
mock_sys_exit.assert_called_once_with(0)

View File

@ -22,7 +22,7 @@ if TYPE_CHECKING:
def _today() -> str: def _today() -> str:
return datetime.now(tz=UTC).strftime("%Y-%m-%d") return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
class TestIsScheduledSkipToday: class TestIsScheduledSkipToday:

View File

@ -19,7 +19,7 @@ if TYPE_CHECKING:
def _today() -> str: def _today() -> str:
return datetime.now(tz=UTC).strftime("%Y-%m-%d") return datetime.now(tz=UTC).astimezone().strftime("%Y-%m-%d")
class TestExplainLockDecision: class TestExplainLockDecision:

View File

@ -0,0 +1,122 @@
"""A credit after tonight's shutdown adds its reward to that shutdown.
kuhy, 2026-11-18: shutdown 18:00, a run ending 19:58 must make 20:00 and the
book's +1h 21:00 -- the same sum the daily reset derives. The late-credit rule
(2026-10-17) made it 21:58 (the run's end + 2h) and then 22:58. Unpaid gates
keep the PC up behind the evening chain until 23:00 instead.
"""
from __future__ import annotations
from datetime import date, datetime
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import earned_time
import pytest
from screen_locker import _sick_floor
from screen_locker._ceiling import ceiling
from screen_locker._day import today_str
from screen_locker._earned import first_minutes
from screen_locker._shutdown import ShutdownMixin
from screen_locker.tests._sick_helpers import mark_sick
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
from screen_locker.screen_lock import ScreenLocker
def _today_at(hhmm: str) -> str:
"""Unix time of ``hhmm`` local today, as a ledger ``completed_at``."""
day = date.fromisoformat(today_str())
hour, minute = (int(p) for p in hhmm.split(":"))
moment = datetime(day.year, day.month, day.day, hour, minute).astimezone()
return str(moment.timestamp())
def _locker(mock_tk: MagicMock, tmp_path: Path, start: int) -> ScreenLocker:
"""A locker over an in-memory shutdown config starting at ``start``."""
locker = create_locker(mock_tk, tmp_path)
config = {"value": (start, start, 300)}
def write(mw: int, ts: int, morning: int, *, restore: bool) -> bool:
assert restore
config["value"] = (mw, ts, morning)
return True
object.__setattr__(
locker, "_read_shutdown_config", MagicMock(side_effect=lambda: config["value"])
)
object.__setattr__(locker, "_write_shutdown_config", MagicMock(side_effect=write))
return locker
@pytest.mark.usefixtures("pre_ladder")
def test_a_run_after_the_shutdown_adds_to_the_shutdown(
mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
"""18:00 shutdown, run ends 19:58: 18:00 + the workout reward, not 19:58 + it."""
locker = _locker(mock_tk, tmp_path, 18 * 60)
locker.workout_data = {
"type": "runnerup_verified",
"completed_at": _today_at("19:58"),
}
with (
patch("screen_locker._shutdown.plan_absorb", side_effect=lambda m: (m, 0)),
patch("screen_locker._shutdown.save_lift"),
patch("screen_locker._workout_credit.is_rest_day", return_value=False),
patch("screen_locker._workout_credit.count_weekly_workouts", return_value=3),
patch("screen_locker._workout_credit._credit_notify.notify_workout_credit"),
):
result = locker._apply_credit_for_written_entry([])
reward = first_minutes(earned_time.WORKOUT, date.fromisoformat(today_str()))
assert result.shutdown_adjusted is True
assert locker._read_shutdown_config() == (18 * 60 + reward, 18 * 60 + reward, 300)
class _Host(ShutdownMixin):
"""The real add paths over an in-memory config."""
def __init__(self, tonight: int) -> None:
self.config: tuple[int, int, int] = (tonight, tonight, 300)
def _read_shutdown_config(self) -> tuple[int, int, int] | None:
return self.config
def _write_shutdown_config(
self, mon_wed: int, thu_sun: int, morning_end: int, *, restore: bool = False
) -> bool:
assert restore
self.config = (mon_wed, thu_sun, morning_end)
return True
@pytest.mark.usefixtures("pre_ladder")
def test_the_book_after_the_run_adds_its_hour() -> None:
"""18:00 + 2h run + 1h book = 21:00, whatever the clock says (2026-11-18)."""
host = _Host(18 * 60)
assert host._adjust_shutdown_time_later() is True
assert host._adjust_shutdown_time_by(60) is True
reward = first_minutes(earned_time.WORKOUT, date.fromisoformat(today_str()))
assert host.config == (18 * 60 + reward + 60, 18 * 60 + reward + 60, 300)
def test_the_ceiling_still_caps_the_sum() -> None:
"""An add never pushes tonight past the day's ceiling."""
host = _Host(22 * 60 + 30)
host._adjust_shutdown_time_by(120)
assert host.config[1] == ceiling(date.fromisoformat(today_str()))
def test_a_sick_day_credit_only_raises_to_the_sick_target() -> None:
"""On a sick day the credit is already in the target: raise, never add."""
day = date.fromisoformat(today_str())
mark_sick(day)
host = _Host(21 * 60)
with patch.object(_sick_floor, "sick_target", return_value=22 * 60):
assert host._adjust_shutdown_time_by(60) is True
assert host._adjust_shutdown_time_later() is True
assert host.config[1] == 22 * 60

View File

@ -9,7 +9,6 @@ from __future__ import annotations
import logging import logging
import subprocess import subprocess
from types import SimpleNamespace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@ -18,6 +17,9 @@ import pytest
from screen_locker import _credit_notify from screen_locker import _credit_notify
from screen_locker.tests.conftest import create_locker from screen_locker.tests.conftest import create_locker
# The toast's glyphs (textgate): the module's own constants, not words.
_SHUTDOWN = _credit_notify._SHUTDOWN
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
from pathlib import Path from pathlib import Path
@ -40,52 +42,44 @@ def _warned(caplog: pytest.LogCaptureFixture, needle: str) -> bool:
) )
class TestGamingMinutes:
"""The budget figure, or None when its inputs cannot be read."""
def test_returns_the_registry_figure(self) -> None:
"""gather's resolution is shown as whole minutes."""
target = SimpleNamespace(resolution=SimpleNamespace(gaming_minutes=420.0))
with patch(f"{_MOD}.gather", return_value=target):
assert _credit_notify.gaming_minutes_today(None) == 420
def test_unreadable_inputs_warn_and_return_none(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A broken ledger costs the figure, not the notification."""
with patch(f"{_MOD}.gather", side_effect=OSError("ledger gone")):
assert _credit_notify.gaming_minutes_today(None) is None
assert _warned(caplog, "ledger gone")
class TestCreditBody: class TestCreditBody:
"""Whichever parts are known end up in the body.""" """Whichever parts are known end up in the body."""
def test_full_body(self) -> None: def test_full_body(self) -> None:
"""Shutdown time, tonight's move and the gaming budget.""" """Shutdown time and tonight's move; no gaming figure any more."""
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420) body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0))
assert body == "Shutdown 22:00 (+2h) \N{MIDDLE DOT} gaming 7.0h" assert body == f"{_SHUTDOWN} 22:00 (+2h)"
def test_a_capped_credit_shows_plus_zero(self) -> None: def test_a_capped_credit_shows_plus_zero(self) -> None:
"""No backwards move is ever shown: the delta floors at zero.""" """No backwards move is ever shown: the delta floors at zero."""
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None) body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0))
assert body == "Shutdown 22:00 (+0h)" assert body == f"{_SHUTDOWN} 22:00 (+0h)"
def test_a_late_credit_shows_the_reward_not_the_jump(self) -> None:
"""18:00 -> 21:58 after a run ending 19:58: the toast says +2h, not +3h58m."""
body = _credit_notify.credit_body((0, 1080, 0), (0, 1318, 0), reward=120)
assert body == f"{_SHUTDOWN} 21:58 (+2h)"
def test_a_ceiling_cut_reward_shows_what_was_left(self) -> None:
"""A 2h reward that met the 23:00 ceiling after 1h shows +1h."""
body = _credit_notify.credit_body((0, 1320, 0), (0, 1380, 0), reward=120)
assert body == f"{_SHUTDOWN} 23:00 (+1h)"
def test_unknown_before_drops_the_delta(self) -> None: def test_unknown_before_drops_the_delta(self) -> None:
"""Without the old config there is no move to show.""" """Without the old config there is no move to show."""
assert _credit_notify.credit_body(None, (0, 1320, 0), None) == "Shutdown 22:00" assert _credit_notify.credit_body(None, (0, 1320, 0)) == f"{_SHUTDOWN} 22:00"
def test_unreadable_after_warns_and_shows_gaming_only( def test_unreadable_after_warns_and_shows_the_check_mark(
self, caplog: pytest.LogCaptureFixture self, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""An unreadable config is said out loud, not silently omitted.""" """An unreadable config is said out loud, not silently omitted."""
assert _credit_notify.credit_body(None, None, 90) == "gaming 1.5h" assert _credit_notify.credit_body(None, None) == "\N{CHECK MARK}"
assert _warned(caplog, "unreadable") assert _warned(caplog, "unreadable")
def test_nothing_known_still_says_something(self) -> None: def test_the_gaming_figure_is_gone(self) -> None:
"""An empty body would read as a glitch; say the credit happened.""" """No budget exists any more: the body never mentions gaming."""
body = _credit_notify.credit_body(None, None, None) assert not hasattr(_credit_notify, "gaming_minutes_today")
assert body == "Credit applied (details unavailable)" assert not hasattr(_credit_notify, "_GAMING")
class TestSendNotification: class TestSendNotification:
@ -146,13 +140,10 @@ class TestSendNotification:
def test_notify_workout_credit_sends_the_composed_body() -> None: def test_notify_workout_credit_sends_the_composed_body() -> None:
"""The real entry point composes the body and sends it once.""" """The real entry point composes the body and sends it once."""
with ( with (
patch(f"{_MOD}.gaming_minutes_today", return_value=60),
patch(f"{_MOD}.send_notification", return_value=True) as send, patch(f"{_MOD}.send_notification", return_value=True) as send,
): ):
assert _real_notify((0, 1200, 0), (0, 1260, 0), None) assert _real_notify((0, 1080, 0), (0, 1318, 0), 120)
send.assert_called_once_with( send.assert_called_once_with(_credit_notify.TITLE, f"{_SHUTDOWN} 21:58 (+2h)")
_credit_notify.TITLE, "Shutdown 21:00 (+1h) \N{MIDDLE DOT} gaming 1.0h"
)
class TestCreditSideOfTheNotifier: class TestCreditSideOfTheNotifier:
@ -168,7 +159,7 @@ class TestCreditSideOfTheNotifier:
"""Anything the notifier raises is logged at ERROR and dropped.""" """Anything the notifier raises is logged at ERROR and dropped."""
locker = create_locker(mock_tk, tmp_path) locker = create_locker(mock_tk, tmp_path)
with patch(f"{_MOD}.notify_workout_credit", side_effect=KeyError("x")): with patch(f"{_MOD}.notify_workout_credit", side_effect=KeyError("x")):
locker._notify_credit(None, None) locker._notify_credit(None, None, None)
assert any( assert any(
r.levelno == logging.ERROR and "notification failed" in r.getMessage() r.levelno == logging.ERROR and "notification failed" in r.getMessage()
for r in caplog.records for r in caplog.records

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