mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-24 15:46:26 +01:00
Compare commits
No commits in common. "main" and "v1.0.0" have entirely different histories.
38
.github/workflows/md-naming.yml
vendored
38
.github/workflows/md-naming.yml
vendored
@ -1,38 +0,0 @@
|
||||
name: md-naming
|
||||
|
||||
# The four markdown namespaces, enforced on push as well as at commit time.
|
||||
# The local pre-commit hook can be skipped (a fresh clone that never ran
|
||||
# `pre-commit install` has no hooks at all), so the convention needs a second
|
||||
# gate that no one can forget to install.
|
||||
#
|
||||
# Deliberately a SEPARATE workflow from any release job: a badly named doc
|
||||
# should fail lint, not block publishing an artifact.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
md-naming:
|
||||
name: markdown naming convention
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The gate and its exemption list live in the shared utils repo so every
|
||||
# repo enforces the same namespaces. Checking it out beats vendoring a
|
||||
# copy here, which is exactly how a gate and a survey start disagreeing.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
- name: Enforce the naming convention
|
||||
run: bash .utils/scripts/check_md_naming.sh --all
|
||||
|
||||
# Warns only: no machine can prove a task is finished, so an old TODO
|
||||
# gets a nudge, never a failure.
|
||||
- name: Warn about stale TODOs
|
||||
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py
|
||||
108
.github/workflows/pre-commit.yml
vendored
108
.github/workflows/pre-commit.yml
vendored
@ -7,116 +7,26 @@ on:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
# One ~120 s job used to install Flutter, Node and all of requirements.txt
|
||||
# and then run every hook in series; mypy (~20 s), flutter analyze (~13 s
|
||||
# plus the SDK) and pylint (~12 s) dominated it. Each now gets its own runner
|
||||
# with only the toolchain it needs, and the other hooks share `rest`; the
|
||||
# workflow takes as long as the slowest group rather than the sum.
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- group: mypy
|
||||
hooks: mypy
|
||||
skip: ""
|
||||
# Both pylint hooks (source and tests) share the id `pylint`.
|
||||
- group: pylint
|
||||
hooks: pylint
|
||||
skip: ""
|
||||
- group: flutter
|
||||
hooks: flutter-analyze
|
||||
skip: ""
|
||||
# dependency-freshness is local only (pre-commit hook), never in CI.
|
||||
- group: rest
|
||||
hooks: ""
|
||||
skip: mypy,pylint,flutter-analyze,dependency-freshness
|
||||
name: pre-commit (${{ matrix.group }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Hooks here delegate to the shared gates in kuhyx/utils. Without this
|
||||
# checkout they exit 1 with "shared gate not found at
|
||||
# /home/runner/utils/..." -- which is what this workflow was doing on
|
||||
# every run since those hooks were added.
|
||||
- name: Check out the shared gates
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
- name: Point the delegates at that checkout
|
||||
run: echo "UTILS_ROOT=$GITHUB_WORKSPACE/.utils" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
- uses: astral-sh/setup-uv@v10.2.0
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: requirements.txt
|
||||
|
||||
# The flutter-analyze hook shells out to `flutter analyze` in
|
||||
python-version: "3.12"
|
||||
# The flutter-analyze pre-commit hook shells out to `flutter analyze` in
|
||||
# stronglift_replacement/workout_app. Pin to the version the app is
|
||||
# developed against (Dart SDK ^3.12.2) so CI's analyzer matches local.
|
||||
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1
|
||||
if: matrix.group == 'flutter'
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: 3.50.1
|
||||
working-directory: stronglift_replacement/workout_app
|
||||
flutter-version: "3.44.6"
|
||||
channel: stable
|
||||
cache: true
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
# analyze needs resolved packages (.dart_tool); the hook runs analyze
|
||||
# only, so fetch deps here first.
|
||||
- name: Resolve Flutter packages
|
||||
if: matrix.group == 'flutter'
|
||||
run: flutter pub get
|
||||
working-directory: stronglift_replacement/workout_app
|
||||
|
||||
# The web-lint / web-typecheck hooks run pnpm inside web/. Without its
|
||||
# installed packages `tsc --build` cannot find the 'vite/client' and
|
||||
# 'node' type libraries and fails with TS2688 -- which is what this
|
||||
# workflow had been doing on every run since the status UI landed in
|
||||
# 8f91158.
|
||||
# No `version:` -- pnpm/action-setup reads `packageManager` from
|
||||
# web/package.json (it errors if both are given).
|
||||
- uses: pnpm/action-setup@v4
|
||||
if: matrix.group == 'rest'
|
||||
with:
|
||||
package_json_file: web/package.json
|
||||
- uses: actions/setup-node@v4
|
||||
if: matrix.group == 'rest'
|
||||
with:
|
||||
node-version: "26.13.1"
|
||||
cache: pnpm
|
||||
cache-dependency-path: web/pnpm-lock.yaml
|
||||
- name: Install status-UI packages
|
||||
if: matrix.group == 'rest'
|
||||
run: pnpm install --frozen-lockfile
|
||||
working-directory: web
|
||||
|
||||
# Every hook brings its own environment except the language: system
|
||||
# ones, and those all run in `rest`: screens-fit imports screen_locker
|
||||
# (and so its runtime deps). The other groups need pre-commit alone. uv with a cached
|
||||
# wheel store replaces a ~27 s pip install.
|
||||
- name: Install requirements for the system hooks
|
||||
if: matrix.group == 'rest'
|
||||
run: uv pip install --system -r requirements.txt
|
||||
- name: Install pre-commit
|
||||
if: matrix.group != 'rest'
|
||||
run: uv pip install --system pre-commit
|
||||
|
||||
# One cache per group: a shared key would hold whichever group saved
|
||||
# first, and the others would rebuild their hook envs on every run. The
|
||||
# restore key falls back to the old single pre-commit/action cache,
|
||||
# which already holds every hook env, so a group's first run does not
|
||||
# rebuild pylint's git dependencies from scratch.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: pre-commit-${{ matrix.group }}-${{ env.pythonLocation }}-${{ hashFiles('.pre-commit-config.yaml') }}
|
||||
restore-keys: |
|
||||
pre-commit-${{ matrix.group }}-${{ env.pythonLocation }}-
|
||||
pre-commit-3|${{ env.pythonLocation }}|
|
||||
|
||||
- name: pre-commit run (${{ matrix.group }})
|
||||
env:
|
||||
SKIP: ${{ matrix.skip }}
|
||||
run: pre-commit run ${{ matrix.hooks }} --all-files --show-diff-on-failure --color=always
|
||||
- uses: pre-commit/action@v3.0.1
|
||||
|
||||
121
.github/workflows/python-tests.yml
vendored
121
.github/workflows/python-tests.yml
vendored
@ -6,40 +6,26 @@ on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
# 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
|
||||
# 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.
|
||||
FLUTTER_SHARDS: 10
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
# uv with a cached wheel store installs requirements.txt in seconds;
|
||||
# plain pip took ~26 s of a ~70 s job.
|
||||
- uses: astral-sh/setup-uv@v10.2.0
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: requirements.txt
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv pip install --system -r requirements.txt
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
# -n auto spreads the suite over every runner core (pytest-xdist is in
|
||||
# requirements.txt); pytest-cov merges the workers' coverage, and every
|
||||
# worker loads conftest.py, so the state-file redirects hold in each.
|
||||
# -q cancels pyproject's -v: 1368 test names were most of the log.
|
||||
- name: Run tests with coverage
|
||||
run: python -m pytest -n auto -p no:sugar -q
|
||||
run: python -m pytest -v
|
||||
|
||||
# The pytest suite replaces the whole `tk` module so it can never reach a
|
||||
# display, which means the lock-screen widget behaviour it guards cannot be
|
||||
@ -52,95 +38,16 @@ jobs:
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
- uses: astral-sh/setup-uv@v10.2.0
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: requirements.txt
|
||||
python-version: "3.12"
|
||||
|
||||
# No apt step: the runner image already ships Xvfb, and
|
||||
# setup-python's interpreter has its own tkinter (python3-tk is for the
|
||||
# system python, which this job never runs). The apt-get update +
|
||||
# install cost ~35 s. If either ever goes missing the check does not
|
||||
# skip -- _xvfb_reexec returns 1 without Xvfb, and the import fails
|
||||
# without tkinter.
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
uv pip install --system -r requirements.txt
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb python3-tk
|
||||
pip install -r requirements.txt
|
||||
# The script imports screen_locker directly rather than through
|
||||
# pytest, which would put the rootdir on sys.path for it.
|
||||
uv pip install --system -e . --no-deps
|
||||
pip install -e . --no-deps
|
||||
|
||||
- name: Sport selector survives gatelock's recovery tick
|
||||
# Run as a module (like the screen-fits gate) so scripts/ resolves as a
|
||||
# package and the check can import the helpers it was split into.
|
||||
run: python3 -m scripts.verify_lock_popup_safety
|
||||
|
||||
# The two coverage bars below used to run only in the local pre-push hook,
|
||||
# which became a 1-second stamp check on 2026-09-20 (pre-commit's manual
|
||||
# stage holds them now). Nothing else in CI runs the Flutter or web suites,
|
||||
# so these jobs are the only place the 100% bars are enforced on every push.
|
||||
#
|
||||
# The Flutter suite took ~150 s on one runner, nearly all of it compiling 77
|
||||
# test files, so it runs as FLUTTER_SHARDS buckets of whole files in
|
||||
# parallel and flutter-coverage applies the unchanged 100% bar and
|
||||
# every-lib-file-present guard to their union.
|
||||
flutter-shard:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
name: flutter test (shard ${{ matrix.shard }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The slim cached SDK (utils/flutter-setup): subosito's full-SDK
|
||||
# cache cost ~38 s to restore even on a hit.
|
||||
- uses: kuhyx/utils/flutter-setup@flutter-setup-v1
|
||||
with:
|
||||
flutter-version: 3.50.1
|
||||
working-directory: stronglift_replacement/workout_app
|
||||
|
||||
- name: flutter test --coverage, bucket ${{ matrix.shard }}
|
||||
run: bash scripts/check_flutter_coverage.sh --shard "${{ matrix.shard }}/$FLUTTER_SHARDS"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: flutter-lcov-${{ matrix.shard }}
|
||||
path: stronglift_replacement/workout_app/coverage/lcov.info
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
flutter-coverage:
|
||||
needs: flutter-shard
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: flutter-lcov-*
|
||||
path: lcov-shards
|
||||
|
||||
- name: flutter test --coverage, 100% of lib/ (workout app)
|
||||
run: bash scripts/check_flutter_coverage.sh --merged "$FLUTTER_SHARDS" lcov-shards/*/lcov.info
|
||||
|
||||
web-coverage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
package_json_file: web/package.json
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 26.13.1
|
||||
cache: pnpm
|
||||
cache-dependency-path: web/pnpm-lock.yaml
|
||||
|
||||
- name: vitest --coverage, 100% (status web UI)
|
||||
run: |
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
pnpm --dir web run coverage
|
||||
run: python3 scripts/verify_lock_popup_safety.py
|
||||
|
||||
45
.github/workflows/release-apk.yml
vendored
45
.github/workflows/release-apk.yml
vendored
@ -3,14 +3,6 @@ name: release-apk
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# A publisher, not a gate: build only when something that ends up in
|
||||
# the APK changed. versionCode is the commit count, so skipped pushes
|
||||
# still leave it monotonic.
|
||||
paths:
|
||||
- 'stronglift_replacement/workout_app/**'
|
||||
- '.fvmrc'
|
||||
- '.versioncode-offset'
|
||||
- '.github/workflows/release-apk.yml'
|
||||
# Lets a release be rebuilt from the current main without a dummy commit.
|
||||
workflow_dispatch:
|
||||
|
||||
@ -23,13 +15,9 @@ concurrency:
|
||||
group: release-apk-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
# NOTE: versionCode is the commit count (`git rev-list --count HEAD`), which
|
||||
# only ever increases and tracks the code rather than the CI file. It replaced
|
||||
# github.run_number on 2026-08-09: run_number counts workflow RUNS, so it
|
||||
# resets to 1 if this file is renamed AND it can fall behind a build made
|
||||
# outside this workflow — which happened, leaving CI unable to install over a
|
||||
# manually sideloaded APK (INSTALL_FAILED_VERSION_DOWNGRADE). The checkout
|
||||
# below therefore needs fetch-depth: 0; a shallow clone counts 1 commit.
|
||||
# NOTE: versionCode is github.run_number, which is per-workflow-FILE. Never
|
||||
# rename or replace this file — the counter resets to 1, versionCode goes
|
||||
# backwards, and Android silently refuses every future update.
|
||||
#
|
||||
# This job is NOT gated on a test suite: this repo has no Flutter analyze/test
|
||||
# job to depend on, so a broken commit still publishes. The build failing is
|
||||
@ -43,24 +31,15 @@ jobs:
|
||||
working-directory: stronglift_replacement/workout_app
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# versionCode is the commit count; a shallow clone would report 1.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Derive versionCode from the commit count
|
||||
id: vc
|
||||
run: echo "code=$(git rev-list --count HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "17"
|
||||
# ~/.gradle caches + wrapper, keyed on the Gradle files.
|
||||
cache: gradle
|
||||
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: 3.50.1
|
||||
flutter-version: 3.44.6
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
@ -106,9 +85,9 @@ jobs:
|
||||
|
||||
- name: Build signed APK
|
||||
run: |
|
||||
flutter build apk --release --flavor daily \
|
||||
flutter build apk --release \
|
||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||
--build-number="${{ steps.vc.outputs.code }}"
|
||||
--build-number="${{ github.run_number }}"
|
||||
|
||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||
# the debug key if key.properties is misplaced, producing a green build
|
||||
@ -116,7 +95,7 @@ jobs:
|
||||
- name: Verify the APK is release-signed
|
||||
run: |
|
||||
set -euo pipefail
|
||||
apk=build/app/outputs/flutter-apk/app-daily-release.apk
|
||||
apk=build/app/outputs/flutter-apk/app-release.apk
|
||||
signer=$(ls -d "$ANDROID_SDK_ROOT"/build-tools/* | sort -V | tail -1)/apksigner
|
||||
"$signer" verify --print-certs "$apk" | tee /tmp/certs.txt
|
||||
if grep -qi 'CN=Android Debug' /tmp/certs.txt; then
|
||||
@ -136,8 +115,8 @@ jobs:
|
||||
id: art
|
||||
run: |
|
||||
set -euo pipefail
|
||||
out="workout-app-${{ steps.ver.outputs.semver }}-build.${{ steps.vc.outputs.code }}.apk"
|
||||
cp build/app/outputs/flutter-apk/app-daily-release.apk "$out"
|
||||
out="workout-app-${{ steps.ver.outputs.semver }}-build.${{ github.run_number }}.apk"
|
||||
cp build/app/outputs/flutter-apk/app-release.apk "$out"
|
||||
echo "path=$out" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Publish the per-commit prerelease
|
||||
@ -145,12 +124,12 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="v${{ steps.ver.outputs.semver }}-build.${{ steps.vc.outputs.code }}"
|
||||
tag="v${{ steps.ver.outputs.semver }}-build.${{ github.run_number }}"
|
||||
gh release create "$tag" "${{ steps.art.outputs.path }}" \
|
||||
--prerelease \
|
||||
--target "${{ github.sha }}" \
|
||||
--title "$tag" \
|
||||
--notes "Automated build of ${{ github.sha }} (versionCode ${{ steps.vc.outputs.code }})."
|
||||
--notes "Automated build of ${{ github.sha }} (versionCode ${{ github.run_number }})."
|
||||
|
||||
# Cut a clean vX.Y.Z the first time a pubspec version is seen. A failing
|
||||
# `gh release view` is the "not published yet" signal, which also covers
|
||||
@ -170,4 +149,4 @@ jobs:
|
||||
gh release create "$tag" "${{ steps.art.outputs.path }}" \
|
||||
--target "${{ github.sha }}" \
|
||||
--title "$tag" \
|
||||
--notes "Release $tag (versionCode ${{ steps.vc.outputs.code }})."
|
||||
--notes "Release $tag (versionCode ${{ github.run_number }})."
|
||||
|
||||
25
.github/workflows/repo-contract.yml
vendored
25
.github/workflows/repo-contract.yml
vendored
@ -1,25 +0,0 @@
|
||||
name: repo-contract
|
||||
|
||||
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
|
||||
# contract is enforced on push too. Mirrors md-naming.yml.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
repo-contract:
|
||||
name: repo contract
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
- name: Enforce the repo contract
|
||||
run: bash .utils/scripts/check_repo_contract.sh
|
||||
21
.gitignore
vendored
21
.gitignore
vendored
@ -16,33 +16,14 @@ htmlcov/
|
||||
.DS_Store
|
||||
|
||||
# Runtime state files — personal workout/health data, never public.
|
||||
screen_locker/log.json
|
||||
# ...and the ledger naming which of its entries record the same workout.
|
||||
screen_locker/duplicate_credits.json
|
||||
# ...and the sync tombstones the PC re-pushes every tick (names a workout id).
|
||||
screen_locker/sync_tombstones.json
|
||||
screen_locker/workout_log.json
|
||||
# ...including the timestamped backups a correction script leaves behind.
|
||||
screen_locker/*.json.bak-*
|
||||
screen_locker/sick_history.json
|
||||
screen_locker/extra_benefits_state.json
|
||||
screen_locker/scheduled_skips.json
|
||||
screen_locker/shutdown_base.json
|
||||
screen_locker/shutdown_base.lock
|
||||
screen_locker/log.lock
|
||||
screen_locker/sick_day_state.json
|
||||
screen_locker/early_bird_pending.json
|
||||
|
||||
# ci_mirror.sh cached requirements.txt venv (rebuilt on demand)
|
||||
.ci-mirror-venv/
|
||||
|
||||
# Web status UI (web/) build and tooling output.
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
web/.astro/
|
||||
web/coverage/
|
||||
web/node_modules
|
||||
web/dist
|
||||
screen_locker/rest_days.json
|
||||
screen_locker/grace_floor.json
|
||||
screen_locker/grace_floor.lock
|
||||
screen_locker/rest_days.lock
|
||||
|
||||
@ -1 +0,0 @@
|
||||
daily
|
||||
@ -8,21 +8,14 @@ default_language_version:
|
||||
default_stages: [pre-commit]
|
||||
fail_fast: false
|
||||
|
||||
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
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
|
||||
args: [--markdown-linebreak-ext=md]
|
||||
exclude: ^screen_locker/tests/fixtures/run_tcx/
|
||||
- id: end-of-file-fixer
|
||||
exclude: ^screen_locker/tests/fixtures/run_tcx/
|
||||
- id: check-yaml
|
||||
# pnpm-lock.yaml is a two-document stream by design.
|
||||
exclude: ^web/pnpm-lock\.yaml$
|
||||
- id: check-json
|
||||
- id: check-toml
|
||||
- id: check-added-large-files
|
||||
@ -43,12 +36,6 @@ repos:
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: repo-contract
|
||||
name: repo contract (CLAUDE.md Commands + test_changed)
|
||||
entry: scripts/check_repo_contract.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
|
||||
- id: no-noqa
|
||||
name: Block noqa comments
|
||||
entry: '(?i)#\s*(noqa|type:\s*ignore)'
|
||||
@ -61,15 +48,13 @@ repos:
|
||||
types: [python]
|
||||
- id: requirements-sync
|
||||
name: requirements.txt covers all package imports
|
||||
# scripts/ became a real package (it now holds shared helpers), so
|
||||
# auto-detection sees two candidates -- name the one that ships.
|
||||
entry: python3 scripts/check_requirements_sync.py --package screen_locker
|
||||
entry: python3 scripts/check_requirements_sync.py
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^(screen_locker/.*\.py|requirements\.txt)$
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.17.1
|
||||
rev: v0.15.2
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||
@ -103,74 +88,19 @@ repos:
|
||||
- --disable-error-code=redundant-cast
|
||||
- --disable-error-code=empty-body
|
||||
- --disable-error-code=list-item
|
||||
# The hook runs in its own isolated venv, so stubs installed into the
|
||||
# project venv are invisible to it. Without this, the Firebase session
|
||||
# recovery's `import requests` fails as import-untyped here while
|
||||
# type-checking cleanly everywhere else.
|
||||
additional_dependencies:
|
||||
- types-requests>=2.31.0
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
# Same release as requirements.txt. No --jobs here: pyproject.toml holds
|
||||
# it at 1, because parallel pylint pickles through dill, which crashes on
|
||||
# Python 3.15 (see the comment on `jobs` there).
|
||||
rev: v4.1.4
|
||||
rev: v3.3.2
|
||||
hooks:
|
||||
# Two hooks, because the three checks below are not defects in a test
|
||||
# suite -- they are how pytest and unit-testing private mixins work --
|
||||
# while in SOURCE they are real findings that must still fail:
|
||||
# protected-access tests drive private mixin methods directly; those
|
||||
# methods ARE the unit under test (ruff already
|
||||
# exempts the same thing via SLF001 for tests).
|
||||
# unused-argument pytest fixtures must be REQUESTED in the signature
|
||||
# to take effect but are never referenced in the body.
|
||||
# duplicate-code near-identical `with patch(...)` preambles; a test
|
||||
# should read top-to-bottom without chasing a fixture.
|
||||
# Splitting also removes the old failure mode where the score depended on
|
||||
# what else happened to be staged alongside. Both are a hard 10.00.
|
||||
- id: pylint
|
||||
name: pylint (source, 10.00)
|
||||
alias: pylint-source
|
||||
exclude: ^screen_locker/tests/
|
||||
args:
|
||||
- --rcfile=pyproject.toml
|
||||
- --fail-under=10
|
||||
- --fail-under=8.0
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
# Kept in step with pyproject.toml: pip refuses two different
|
||||
# direct URLs for one distribution, so any pin that drifts from
|
||||
# the manifest becomes an unresolvable hook environment rather
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
|
||||
- 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.24.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
||||
- 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.
|
||||
- music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
- id: pylint
|
||||
name: pylint (tests, 10.00)
|
||||
alias: pylint-tests
|
||||
files: ^screen_locker/tests/
|
||||
args:
|
||||
- --rcfile=pyproject.toml
|
||||
- --fail-under=10
|
||||
- --disable=protected-access,unused-argument,duplicate-code
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
# Kept in step with pyproject.toml: pip refuses two different
|
||||
# direct URLs for one distribution, so any pin that drifts from
|
||||
# the manifest becomes an unresolvable hook environment rather
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
|
||||
- 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.24.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
||||
- 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
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.3.0#subdirectory=crdt-sync
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
|
||||
@ -189,110 +119,40 @@ repos:
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
# 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
|
||||
# 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
|
||||
name: CI mirror (clean requirements.txt venv)
|
||||
entry: bash scripts/ci_mirror.sh venv
|
||||
- id: ci-mirror
|
||||
name: CI mirror (clean-venv pytest + pre-commit --all-files)
|
||||
entry: bash scripts/ci_mirror.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-precommit-pylint-source
|
||||
name: "CI mirror (pre-commit --all-files: pylint source)"
|
||||
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
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-pytest
|
||||
name: CI mirror (clean-venv pytest, xdist)
|
||||
entry: bash scripts/ci_mirror.sh pytest
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
stages: [pre-push]
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
args:
|
||||
- --skip=*.json,*.lock,*pnpm-lock.yaml,.git,__pycache__,.venv
|
||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||
- --ignore-words-list=als,ans,ect,nd,som,sur,te,nam,numer,lew,sie,wil,postion,clen,ther,folow,derrive,ony,tje,noe,theses,crate,doubleclick,wile,tabel,pary,blok,bloc,proces,serwer,parametr,adres,hart,dout,metod,tekst,synonim,grup,mosty,lokal,skalar,milion,nowe,tre,hel,alph
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
# Fails a commit that still points crdt_sync at a local path. Local
|
||||
# tests would go green against a library CI has never seen, silently.
|
||||
- id: crdt-sync-override
|
||||
name: no local crdt_sync dependency_override
|
||||
entry: bash scripts/check_no_crdt_sync_override.sh stronglift_replacement/workout_app/pubspec.yaml
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
- id: shellcheck
|
||||
name: shellcheck
|
||||
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
||||
language: system
|
||||
types: [shell]
|
||||
- id: max-file-length
|
||||
name: Max file length (250 lines)
|
||||
name: Max file length (400 lines)
|
||||
entry: python3 scripts/check_file_length.py
|
||||
language: system
|
||||
# Dart was missing here until 2026-08-15, so the cap had never looked at
|
||||
# a single file in workout_app/ — the whole Flutter app was exempt from
|
||||
# the gate it was being refactored to satisfy. ts/tsx joined on
|
||||
# 2026-08-29 with web/, for exactly the same reason: a language absent
|
||||
# from this list is a directory the cap silently does not apply to.
|
||||
# c/c++ and markdown joined on 2026-11-01 (the Linux runner had grown
|
||||
# to 258; prose is under the same cap per the 250-line rule).
|
||||
types_or: [python, shell, dart, ts, tsx, c, c++, markdown]
|
||||
exclude: '^web/(node_modules|dist|coverage)/'
|
||||
types_or: [python, shell]
|
||||
- id: no-silent-failures
|
||||
name: Block silent failures (swallowed exceptions and silent sys.exit(0) must say why)
|
||||
entry: python3 -m scripts.check_silent_failures
|
||||
name: Block silent failures (swallowed exceptions must log why)
|
||||
entry: python3 scripts/check_silent_failures.py
|
||||
language: system
|
||||
types: [python]
|
||||
- id: no-silent-failures-dart
|
||||
# The Python hook above is types:[python] and so had never looked at a
|
||||
# single Dart file — in the app where a swallowed sync error costs the
|
||||
# user a workout with nothing anywhere saying so.
|
||||
name: Block silent failures in Dart (swallowed errors must log why)
|
||||
entry: python3 -m scripts.check_silent_failures_dart
|
||||
language: system
|
||||
types: [dart]
|
||||
- id: screens-fit
|
||||
name: Every lock screen fits 1366x768 (no scrolling required)
|
||||
entry: python3 -m scripts.verify_screen_fits
|
||||
@ -300,13 +160,6 @@ repos:
|
||||
files: '^screen_locker/.*\.py$'
|
||||
pass_filenames: false
|
||||
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
|
||||
name: flutter analyze (workout app)
|
||||
# env -u GIT_DIR: git exports it to hooks, and flutter shells out to
|
||||
@ -317,174 +170,11 @@ repos:
|
||||
language: system
|
||||
files: '^stronglift_replacement/workout_app/.*\.(dart|yaml)$'
|
||||
pass_filenames: false
|
||||
- id: flutter-test-coverage-shard-0
|
||||
name: flutter test bucket 0/8 (workout app, local gate)
|
||||
entry: bash scripts/check_flutter_coverage.sh --gate-shard 0
|
||||
- id: flutter-test-coverage
|
||||
name: flutter test --coverage 100% (workout app)
|
||||
entry: bash scripts/check_flutter_coverage.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: flutter-test-coverage-shard-1
|
||||
name: flutter test bucket 1/8 (workout app, local gate)
|
||||
entry: bash scripts/check_flutter_coverage.sh --gate-shard 1
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: flutter-test-coverage-shard-2
|
||||
name: flutter test bucket 2/8 (workout app, local gate)
|
||||
entry: bash scripts/check_flutter_coverage.sh --gate-shard 2
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: flutter-test-coverage-shard-3
|
||||
name: flutter test bucket 3/8 (workout app, local gate)
|
||||
entry: bash scripts/check_flutter_coverage.sh --gate-shard 3
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
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
|
||||
# unchanged 100% bar and every-lib-file guard to their union.
|
||||
- id: flutter-test-coverage-merge
|
||||
name: flutter coverage 100% (union of the 8 buckets)
|
||||
entry: bash scripts/check_flutter_coverage.sh --gate-merge
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
|
||||
# web/ gates. steam-backlog-enforcer, which this app was copied from, has
|
||||
# only a coverage hook -- its lint and typecheck are unenforced, so both
|
||||
# can rot without anything failing. All three run here.
|
||||
- id: web-lint
|
||||
name: eslint (status web UI)
|
||||
entry: pnpm --dir web run lint
|
||||
language: system
|
||||
files: '^web/(src/.*\.(ts|astro)|eslint\.config\.js|package\.json)$'
|
||||
files: '^stronglift_replacement/workout_app/.*\.dart$'
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
- id: web-typecheck
|
||||
name: astro check + build (status web UI)
|
||||
entry: pnpm --dir web run build
|
||||
language: system
|
||||
files: '^web/(src/.*\.(ts|astro)|tsconfig\.json|astro\.config\.mjs|vitest\.config\.ts)$'
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
- id: web-coverage
|
||||
name: vitest --coverage 100% (status web UI)
|
||||
entry: pnpm --dir web run coverage
|
||||
language: system
|
||||
files: '^web/src/'
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
|
||||
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
||||
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
||||
# Shared gate in ~/src/utils owns the namespaces and the exemption list, so
|
||||
# one repo's idea of a valid name cannot drift from every other repo's.
|
||||
- id: md-naming
|
||||
name: markdown naming convention
|
||||
entry: scripts/check_md_naming.sh
|
||||
language: system
|
||||
files: \.(md|markdown)$
|
||||
|
||||
- id: todo-closer
|
||||
name: close Todo trailer tasks
|
||||
entry: scripts/todo_hooks.sh closer
|
||||
language: system
|
||||
stages: [post-commit]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-merge
|
||||
name: import PR Todo sections (pull)
|
||||
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||
language: system
|
||||
stages: [post-merge]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-rewrite
|
||||
name: import PR Todo sections (pull --rebase)
|
||||
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||
language: system
|
||||
stages: [post-rewrite]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||
# so the question is mechanically answerable at all.
|
||||
#
|
||||
# `files:` is what keeps this cheap: a commit touching only source makes
|
||||
# ZERO network requests, and manifest commits mostly hit a 6h disk cache.
|
||||
#
|
||||
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
|
||||
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
||||
# a hook that hard-failed on a flaky connection would leave no way to
|
||||
# commit at all. The strict run is local only (CI does not check
|
||||
# freshness): scripts/check_dependency_freshness.sh --all --strict
|
||||
- id: dependency-freshness
|
||||
name: dependencies on newest stable
|
||||
entry: scripts/check_dependency_freshness.sh
|
||||
language: system
|
||||
pass_filenames: true
|
||||
files: >-
|
||||
(pubspec\.(yaml|lock)|pyproject\.toml|requirements.*\.txt|uv\.lock
|
||||
|package\.json|package-lock\.json|pnpm-lock\.yaml
|
||||
|Cargo\.(toml|lock)|go\.(mod|sum)
|
||||
|\.fvmrc|\.nvmrc|\.python-version
|
||||
|\.github/workflows/.*\.ya?ml)$
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
# The only pre-push hook. Everything that used to run here is now
|
||||
# `stages: [manual]` -- run on demand with `scripts/check_gate_stamp.sh
|
||||
# full`, and by CI on every push. finish_auto.sh stamps HEAD after its
|
||||
# gate; a tree without that receipt cannot leave the machine.
|
||||
- id: gate-stamp
|
||||
name: pushed tree passed the local gate (stamp check)
|
||||
entry: scripts/check_gate_stamp.sh check
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
stages: [pre-push]
|
||||
|
||||
143
AGENTS.md
143
AGENTS.md
@ -1,143 +0,0 @@
|
||||
do NOT run tests unless specifically instructed to do so or before committing
|
||||
If tests fail on the same issue twice in a row, STOP and ask the user how to proceed instead of continuing to fix and retry.
|
||||
ALWAYS confirm that the feature you add / bug you fixed behaves as it should by running the program after your changes (not tests!) and inspecting output comparing it with what user wanted, after confirming by yourself ask user if the program behaves as they intended
|
||||
After running tests fix all coverage gaps and issues, do not ignore unless specifically instructed to do so
|
||||
You are NOT done until you install the new version on the phone itself:
|
||||
`bash ~/.claude/scripts/phone_deploy.sh stronglift_replacement/workout_app`
|
||||
(it picks a safe versionCode and launches; never a bare `flutter install`).
|
||||
To drive a whole workout on the phone without touching real data, deploy the
|
||||
sandbox flavor instead: `... --flavor sandbox`. That is a separate package
|
||||
(`com.kuhy.workout_app.sandbox`) with its own data, no network, no LAN server,
|
||||
a red SANDBOX ribbon, and a SANDBOX section in Settings (wipe, "mark today not
|
||||
done", rest length in seconds). Its trace is `adb logcat -s WorkoutSandbox`.
|
||||
|
||||
## NEVER fail silently
|
||||
|
||||
A failure that says nothing is a bug. The PC's workout sync did nothing for
|
||||
weeks because a missing token `return`ed `[]` and real errors only logged at
|
||||
`INFO` — nobody could tell "nothing to do" from "it broke".
|
||||
|
||||
- **Swallowed exceptions must say why, loudly.** Every `except` must either
|
||||
re-`raise` or log at `warning`/`error`/`exception`/`critical` with the
|
||||
concrete reason. `debug`/`info` do NOT count — an invisible log is a silent
|
||||
failure with extra steps. Enforced by `scripts/check_silent_failures.py`
|
||||
(pre-commit hook `no-silent-failures`); ruff's `S110` only catches
|
||||
`except: pass`, which is the rare case.
|
||||
- **Guard clauses that abort work must log too.** `if token is None: return`
|
||||
is a silent no-op. Say what was missing and what it means.
|
||||
- **Return something meaningful.** Prefer a typed result (e.g.
|
||||
`_manual_push.PushResult(pushed, record_count, reason)`) over a bare
|
||||
`None`/`[]`/`False`, so the caller can react instead of guessing. `reason`
|
||||
should read like a sentence a human can act on.
|
||||
- **No escape hatch** — `# noqa` is banned repo-wide. If a failure really is
|
||||
benign, log it at `warning` and move on.
|
||||
|
||||
## The shutdown hour is derived, never incremented into
|
||||
|
||||
`/etc/shutdown-schedule.conf` is recomputed from scratch by
|
||||
`_shutdown_base.reset_to_base_if_new_day` on each new day: the base plus
|
||||
every earned term, capped at 23. The numbers are NOT in this repo: they live
|
||||
in the shared earner registry `earned_time` (kuhyx/utils, `earned_time/`),
|
||||
which steam-backlog-enforcer reads for gaming time too. Base = 20:00 minus
|
||||
each earner's cut once its `penalty_from` day arrives (reading, from
|
||||
2026-10-01 -> 19:00); terms = workout 2h + 1h per further session, LeetCode
|
||||
1h, reading 1h, plus whatever is registered later.
|
||||
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
|
||||
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
|
||||
(`apply_flat_bonuses_if_new`, stamped `<name>_bonus_minutes` in
|
||||
`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
|
||||
`_earner_units`, re-synced by every `--sync-only` pass) starts
|
||||
`earner-bonus.service` (`--apply-bonuses`). The 15-minute `workout-sync` is
|
||||
only the fallback. The reset and the pass hold `_bonus_lock`, since three
|
||||
processes can run them at once. The base is the registry
|
||||
constant, not the state file: the file once persisted `base_*_hour`, which
|
||||
made the code's default dead.
|
||||
|
||||
A sick day is a date in the shared `sickdays` pool, read only through
|
||||
`_sick.py`. It may keep lockers: the workout lock asks
|
||||
`_sick.stands_down_workout` (keep-aware), while everything that only computes
|
||||
shutdown (`_sick_floor`, `_shutdown_base`, `_shutdown_target`, the preview
|
||||
scripts) asks `is_sick` and ignores keep. A sick day's shutdown is absolute:
|
||||
20:00 plus the GAMING pay of everything credited that day, capped at 23:00
|
||||
(`earned_time.sick_shutdown_from`, 0.13). The reset writes it, `_sick_floor`
|
||||
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
|
||||
sum. No lift is saved on a sick day.
|
||||
|
||||
## Every credit adds to tonight's shutdown, whenever it lands
|
||||
|
||||
A credit adds its reward to tonight's config even after that shutdown passed:
|
||||
18:00, a run ending 19:58 -> 20:00, the book's +1h -> 21:00, exactly what the
|
||||
daily reset derives (`scripts/preview_shutdown.py` flags any MISMATCH). Unpaid
|
||||
gates do not shut the PC down: the evening chain (book, tutor, LeetCode) holds
|
||||
it behind their locks until 23:00, the only hard bound. The late-credit rule
|
||||
(`min(23:00, credit's own time + reward)`, 2026-10-17) is gone since
|
||||
2026-11-18 (kuhy): it turned that evening into 21:58 and 22:58. Trade-off kuhy
|
||||
accepted: with no gate pending, a workout ending after its earned shutdown
|
||||
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`
|
||||
via `_earned.py`: HMAC-verified `credit` rows matched by the earner's own
|
||||
rule (LeetCode's `submitted_at`, book-guard's `detail.bonus == "1"` +
|
||||
`ended_at`), and *fail closed* -- an unreadable ledger or key earns nothing,
|
||||
logged. The gates stay read-only; none writes the config.
|
||||
|
||||
The schedule is in minutes after midnight end to end. `/etc/shutdown-schedule.conf`
|
||||
holds authoritative `MON_WED_MINUTES` / `THU_SUN_MINUTES` / `MORNING_END_MINUTES`
|
||||
plus strict-rounded legacy `*_HOUR` copies (evening floor, morning ceil) for old
|
||||
readers; `read_shutdown_config` prefers `*_MINUTES` and falls back to `*_HOUR` x 60.
|
||||
`adjust_shutdown_schedule.sh` takes `HH:MM` (or a legacy bare hour) and the
|
||||
helpers `_earned.hhmm` / `_earned.span` render times and durations, so a
|
||||
30-minute earner is applied exactly.
|
||||
|
||||
## The morning session is the carrot — and the early-bird window is it
|
||||
|
||||
`EarlyBirdMixin._is_early_bird_time` no longer reads a clock: it is open
|
||||
exactly while wake-alarm's signed file grants an exemption (before the
|
||||
alarm, during the session, until 11:00 once it completed in time). The
|
||||
05:00–08:30 window and the extended-to-09:00 reward locked someone who got
|
||||
up at 07:00 and were a second mechanism next to the one that knows whether
|
||||
the user is up (2026-09-20). The pending marker is banked by the
|
||||
`wake_alarm_skip` rung; `early-bird-workout-check.timer` (09:30:30, 11:00:30)
|
||||
re-checks just after the carrot's two possible ends.
|
||||
|
||||
The `wake_alarm_skip` rung reads wake-alarm's HMAC-signed
|
||||
`~/.local/state/wake_alarm/morning_session.json` (`_morning_session.py`), not
|
||||
Firebase: wake-alarm is the only reader, and the previous channel here pointed
|
||||
at a path that stopped existing when the repos split and answered "no skip"
|
||||
for a year without an error. The whole decision is *signature ok, dated today,
|
||||
now < exempt_until*; the 09:30/11:00 cutoffs live in wake-alarm
|
||||
(`DOCS-morning-session-pc.md`) and must not be re-derived here. The enforce
|
||||
path waits up to 30 s for a freshly booted PC's refresher; status paths never
|
||||
wait, and tests pin the retry to 0.
|
||||
|
||||
## Commands
|
||||
|
||||
- run: `./run.sh` (locks the screen; never launch on the live display for checks)
|
||||
- test: `python -m pytest -n auto -p no:sugar -q`
|
||||
- test-changed: `scripts/test_changed.sh`
|
||||
- lint: `pre-commit run ruff --all-files`
|
||||
- coverage: `python -m pytest -n auto -p no:sugar -q`
|
||||
- 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).
|
||||
26
CLAUDE.md
Normal file
26
CLAUDE.md
Normal file
@ -0,0 +1,26 @@
|
||||
do NOT run tests unless specifically instructed to do so or before committing
|
||||
If tests fail on the same issue twice in a row, STOP and ask the user how to proceed instead of continuing to fix and retry.
|
||||
ALWAYS confirm that the feature you add / bug you fixed behaves as it should by running the program after your changes (not tests!) and inspecting output comparing it with what user wanted, after confirming by yourself ask user if the program behaves as they intended
|
||||
After running tests fix all coverage gaps and issues, do not ignore unless specifically instructed to do so
|
||||
You are NOT done until you install the new version on the phone itself (flutter install --debug from the workout_app directory, then adb shell monkey -p com.kuhy.workout_app to launch).
|
||||
|
||||
## NEVER fail silently
|
||||
|
||||
A failure that says nothing is a bug. The PC's workout sync did nothing for
|
||||
weeks because a missing token `return`ed `[]` and real errors only logged at
|
||||
`INFO` — nobody could tell "nothing to do" from "it broke".
|
||||
|
||||
- **Swallowed exceptions must say why, loudly.** Every `except` must either
|
||||
re-`raise` or log at `warning`/`error`/`exception`/`critical` with the
|
||||
concrete reason. `debug`/`info` do NOT count — an invisible log is a silent
|
||||
failure with extra steps. Enforced by `scripts/check_silent_failures.py`
|
||||
(pre-commit hook `no-silent-failures`); ruff's `S110` only catches
|
||||
`except: pass`, which is the rare case.
|
||||
- **Guard clauses that abort work must log too.** `if token is None: return`
|
||||
is a silent no-op. Say what was missing and what it means.
|
||||
- **Return something meaningful.** Prefer a typed result (e.g.
|
||||
`_manual_push.PushResult(pushed, record_count, reason)`) over a bare
|
||||
`None`/`[]`/`False`, so the caller can react instead of guessing. `reason`
|
||||
should read like a sentence a human can act on.
|
||||
- **No escape hatch** — `# noqa` is banned repo-wide. If a failure really is
|
||||
benign, log it at `warning` and move on.
|
||||
341
DESIGN_AUDIT_TODO.md
Normal file
341
DESIGN_AUDIT_TODO.md
Normal file
@ -0,0 +1,341 @@
|
||||
# Design audit — screen-locker
|
||||
|
||||
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
|
||||
Report only — nothing in this repo was changed by the audit itself.
|
||||
|
||||
This repo has two UI surfaces, audited separately below. `~/utils/gatelock`
|
||||
was checked with `git -C ~/utils/gatelock rev-parse --show-toplevel` → prints
|
||||
`/home/kuhy/utils`, i.e. gatelock is a subdirectory of the `~/utils` monorepo,
|
||||
**not its own git repo**. Per audit scope, no separate gatelock report was
|
||||
written; see the "Shared gatelock library" section at the end instead.
|
||||
|
||||
## Python/Tkinter lock UI (screen_locker/)
|
||||
|
||||
Design-token entry point check: **no `ttk.Style()` call anywhere in the
|
||||
package** (confirmed via repo-wide grep) and `_constants.py` holds only
|
||||
business-logic constants (budgets, timeouts, file paths) — zero color/font/
|
||||
spacing tokens. Every color, font, and padding value is a literal typed
|
||||
directly at each `tk.Label`/`tk.Button`/`tk.Frame`/`tk.Entry` call site,
|
||||
independently, in 9 files. Evidence:
|
||||
|
||||
- Hex color literals: **100 occurrences, 23 distinct values**, across
|
||||
`screen_lock.py` (6), `_ui_widgets.py` (6), `_window_setup.py` (3),
|
||||
`status_view.py` (21), `_heat_skip.py` (7 + 4 module-level constants),
|
||||
`_manual_workout_dialog.py` (15), `_manual_workout_widgets.py` (12),
|
||||
`_sick_dialog.py` (18), `_temperature_status_mixin.py` (5).
|
||||
`#1a1a1a` alone (the background) appears **31 times** — and it is *also*
|
||||
already defined once, correctly, as `LockConfig.bg = "#1a1a1a"` in
|
||||
`~/utils/gatelock/gatelock/_window.py:71`. None of the 31 in-repo literals
|
||||
import or reference it; `LockWindow.setup()` in gatelock applies
|
||||
`config.bg` to the root window (`_window.py:143`), and then every
|
||||
screen-locker dialog re-hardcodes the same string as if gatelock's value
|
||||
didn't exist.
|
||||
- `font=("Arial", N[, "bold"])` literals: **25 occurrences**, 6 distinct
|
||||
size/weight combos, e.g. `_ui_widgets.py:45,64`, `_sick_dialog.py:111,121`,
|
||||
`_manual_workout_widgets.py:70,89,97,116,126,137,145,164,174`.
|
||||
`_heat_skip.py:12-17` breaks pattern entirely with its own local
|
||||
`_FONT = "monospace"` constant (line 17) plus four color constants
|
||||
(`_BG`, `_FG_MAIN`, `_FG_SUB`, `_BTN_SKIP`, `_BTN_NO`) — the only file in
|
||||
the package that centralizes *anything*, and it does so locally/unshared
|
||||
rather than in a common module.
|
||||
- `padx=`/`pady=` literals: **59 occurrences**, 13 distinct values (1, 2, 5,
|
||||
6, 8, 10, 12, 14, 15, 20, 28, 30) spread across 7 of the 9 files.
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — No
|
||||
`ttk.Style()`, no shared colors/fonts/spacing module. Same visual decision
|
||||
(e.g. background `#1a1a1a`) is independently re-typed 31 times across 9
|
||||
files instead of imported once. `_heat_skip.py:12-17` even invents its own
|
||||
local token block, proving the pattern was known and simply not applied
|
||||
package-wide. Fixing any single visual value (e.g. rebranding the
|
||||
background) means editing up to 9 files by hand with no compiler/lint
|
||||
check that all sites were caught.
|
||||
- **Rule 1 (near-black/white, not pure)** — `bg="#1a1a1a"` (near-black,
|
||||
fine) is paired with pure white text: `_ui_widgets.py:38,57` default
|
||||
`color: str = "white"`, plus explicit `fg="white"` at `_window_setup.py:40`,
|
||||
`_sick_dialog.py:112,128,138` (X11 name `"white"` = `#FFFFFF`), and 6 more
|
||||
in `_manual_workout_widgets.py` (lines 90, 112→ label fg, 116, 137, 158,
|
||||
165). Pure-white-on-near-black is the harsh contrast this rule warns
|
||||
against; should be a near-white (e.g. `#f0f0f0`/`#eaeaea`).
|
||||
- **Rule 2 (saturate your neutrals)** — `#1a1a1a` and `#2a2a2a` have equal
|
||||
R=G=B (26,26,26 and 42,42,42): true zero-saturation gray, not tinted warm
|
||||
or cool. Generic gray per the rule's definition.
|
||||
- **Rule 9 (distinct brightness values in a palette)** — `#ffaa00` (warning/
|
||||
bonus amber, e.g. `screen_lock.py:319`, `status_view.py:181`) and
|
||||
`#ff8844` (network/temp-check failure, e.g. `status_view.py:121,243`,
|
||||
`_temperature_status_mixin.py:50,57,65`) are near-identical in hue and
|
||||
brightness despite signaling different states (bonus/pending vs.
|
||||
error/failure) — they will read as the same color at a glance.
|
||||
- **Rule 11 (mathematically related measurements)** — `padx`/`pady` values
|
||||
(1, 2, 5, 6, 8, 10, 12, 14, 15, 20, 28, 30) don't follow a consistent
|
||||
scale (not all multiples of 4 or 8); e.g. `pady=1` at `status_view.py:177`
|
||||
sits next to `pady=2` (`status_view.py:160`) and `pady=28`
|
||||
(`_heat_skip.py:74`) elsewhere — no discernible spacing system.
|
||||
- **Rule 20 (body text ≥16px)** — Multiple body-text sizes sit well under
|
||||
16px: `font_size=10` at `status_view.py:248,253,255` (the last one,
|
||||
line 255, also uses the lowest-contrast color in the file, `#666666`, for
|
||||
a 10px label — compounding readability), `font_size=11` at
|
||||
`status_view.py:199`, `_heat_skip.py:91,104` (`font=(_FONT, 11)`),
|
||||
`font_size=12` at `status_view.py:160,212,225,239,243`,
|
||||
`_temperature_status_mixin.py:43,50,57,65`, `_sick_dialog.py:135`
|
||||
(`font=("Arial", 12)` on the `tk.Text` justification box), `font_size=13`
|
||||
at `status_view.py:121,123,181`.
|
||||
- **Rule 21 (line length ~70 chars)** — No widget in the package sets
|
||||
`wraplength` (confirmed: zero matches for `wraplength` repo-wide), so long
|
||||
strings render as one unbroken line regardless of window width. Concrete
|
||||
case: `_sick_dialog.py:205-207`, the commitment-prompt text "If you say
|
||||
YES and skip via 'I'm sick' tomorrow, the sick day costs 2x normal." is
|
||||
~80 characters and will render as a single line at `font_size=16` with no
|
||||
wrap control.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — Only
|
||||
`_heat_skip.py:92,93,105,106` sets explicit button padding
|
||||
(`padx=14, pady=5`, ratio 2.8x — roughly compliant). Every other button in
|
||||
the package goes through `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`), which sets no `padx`/`pady` at all and relies on
|
||||
Tk's built-in default padding — a different, unspecified ratio. Button
|
||||
proportions are therefore inconsistent across dialogs, not a deliberate
|
||||
choice.
|
||||
- **Rule 27 (don't mix depth techniques)** — `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`) sets no `relief`, so every button in
|
||||
`status_view.py`, `_sick_dialog.py`, `_manual_workout_dialog.py`, and
|
||||
`_manual_workout_widgets.py` uses Tk's default `relief="raised"` (a faux
|
||||
3D bevel). `_heat_skip.py:94,107` explicitly overrides to
|
||||
`relief="flat"` for its two buttons only — one dialog in the app uses a
|
||||
flat depth style while every other dialog uses a raised/beveled one.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — no asymmetric icon/shape glyphs requiring
|
||||
eye-adjusted centering; text/emoji labels only.
|
||||
- Rule 6 (letter-spacing/line-height by size) — Tk's `font=` tuple has no
|
||||
letter-spacing or line-height controls; not expressible in this stack.
|
||||
- Rule 7 (border contrast) — no widget in the package sets `borderwidth`
|
||||
or a visible border color (only one incidental `highlightthickness=0` at
|
||||
`_manual_workout_dialog.py:72`, which removes a border, not adds one).
|
||||
- Rule 8 (align with something else) — pack/grid layouts are internally
|
||||
consistent per-dialog; no cross-dialog layout grid to check against.
|
||||
- Rule 12 (order by visual weight) — button rows use uniform-weight buttons
|
||||
(same size/style, only color differs); no weight hierarchy to evaluate.
|
||||
- Rule 13 (12-column grid) — fixed 2-column form grid
|
||||
(`_manual_workout_widgets.py:26-49`) is a bespoke field layout, not a page
|
||||
grid system this rule targets.
|
||||
- Rule 14 (space between contrast edges, not bounding box) — cannot be
|
||||
verified from source without rendering; Tk widgets' effective visual
|
||||
edges vs. bounding boxes aren't determinable statically.
|
||||
- Rule 15 (closer elements lighter) — single flat z-plane throughout; no
|
||||
layered/stacked surfaces.
|
||||
- Rule 16 (shadow blur ≈ 2x offset) — no shadows anywhere in the package.
|
||||
- Rule 17 (simple on complex) — flat solid backgrounds behind all text;
|
||||
trivially compliant, nothing to flag.
|
||||
- Rule 18 (container brightness limits) — the one adjacent pair found,
|
||||
`#1a1a1a` (bg, luma 10.2%) vs. `#2a2a2a` (entry/spinbox fields, luma
|
||||
16.5%), differs by ~6.3 percentage points — within the ~12% dark-mode
|
||||
limit. Pass.
|
||||
- Rule 19 (outer padding ≥ inner padding) — the lock window has no bounded
|
||||
"container" with edge padding (content is `place(relx=0.5, rely=0.5,
|
||||
anchor="center")` on a fullscreen root); the outer/inner relationship this
|
||||
rule assumes doesn't apply to a centered-content-on-fullscreen-canvas
|
||||
layout.
|
||||
- Rule 23 (two typefaces max) — only "Arial" and "monospace"
|
||||
(`_heat_skip.py:17`) appear; 2 total, within the limit (the inconsistency
|
||||
of *where* each is used is captured under Rule 4 above, not this rule).
|
||||
- Rule 24 (nest corners) — no widget sets a corner radius (stock Tk widgets
|
||||
are rectangular); nothing to nest.
|
||||
- Rule 25 (avoid adjacent hard divides) — no borders/dividers used anywhere;
|
||||
nothing to conflict.
|
||||
- Rule 26 (no shadows in dark interfaces) — Pass by omission: no shadows
|
||||
exist in this dark-background UI.
|
||||
- Rule 28 (lower icon contrast next to text) — emoji glyphs (💪, 😷, ✓, ☀,
|
||||
⚠, 🔥) share the same `fg=` color as their surrounding text; Tk offers no
|
||||
per-glyph opacity control within one Label's text, so this can't be
|
||||
addressed without moving emoji into separate, independently-colored
|
||||
widgets.
|
||||
|
||||
### Notes
|
||||
|
||||
- The absence of any shared theme/constants module means every rule above
|
||||
that *did* pass (18, 26) did so incidentally, not by design — there's no
|
||||
guard rail keeping it that way as new dialogs get added.
|
||||
- `_heat_skip.py`'s local `_BG`/`_FG_MAIN`/`_FG_SUB`/`_BTN_SKIP`/`_BTN_NO`/
|
||||
`_FONT` constants are the one place in the package that already knows
|
||||
centralizing tokens is worth doing — promoting this pattern to a shared
|
||||
`screen_locker/_theme.py` (or, better, sourcing from gatelock's
|
||||
`LockConfig`) would fix Rule 4 and cascade-fix several of the violations
|
||||
above in one pass.
|
||||
|
||||
## Flutter app (stronglift_replacement/workout_app/)
|
||||
|
||||
Design-token entry point: `lib/main.dart:68-74` declares
|
||||
`ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo,
|
||||
brightness: Brightness.dark), useMaterial3: true)` — a real Material 3 seed
|
||||
theme exists. However, **`Theme.of(context)` / `colorScheme` is referenced
|
||||
zero times anywhere in `lib/screens/` or `lib/widgets/`** (confirmed via
|
||||
repo-wide grep). The theme is declared but never consumed — every one of the
|
||||
24 .dart files under `lib/` hardcodes colors directly instead.
|
||||
|
||||
- `Colors.*` literals: **~210 occurrences** across `screens/` and
|
||||
`widgets/`, 27 distinct named colors. Most common: `Colors.white` (98×),
|
||||
`Colors.grey.shade800` (18×), `Colors.redAccent` (12×),
|
||||
`Colors.greenAccent` (11×), `Colors.grey.shade900` (10×).
|
||||
- Raw hex `Color(0xFF...)` literals bypassing `Colors.*` entirely:
|
||||
`manual_workout_screen.dart:173,201` (`Color(0xFFFF4444)`) and
|
||||
`manual_workout_screen.dart:238,246` (`Color(0xFF88CCFF)`) — these are the
|
||||
**exact same hex values** independently hardcoded on the Python/Tkinter
|
||||
side (`#ff4444` and `#88ccff`, see e.g. `_sick_dialog.py:70`,
|
||||
`_manual_workout_dialog.py:58`), coincidentally kept in sync only because
|
||||
no one has touched either yet.
|
||||
- `fontSize:`/`fontWeight:` literals: 72 occurrences; `history_screen.dart`
|
||||
alone uses 12 distinct font sizes (9, 11, 12, 13, 14, 15, 16, 17, 18, 20,
|
||||
22, 26).
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — `main.dart`
|
||||
builds a `ColorScheme.fromSeed`, but it is dead code from a theming
|
||||
standpoint: no screen or widget reads it. Every screen re-derives its own
|
||||
ad hoc dark palette from `Colors.grey.shade900/800/700` plus assorted
|
||||
accent colors, so a single rebrand (e.g. changing the seed color) would
|
||||
require manually editing all 24 files instead of one.
|
||||
- **Rule 1 (near-black/white, not pure)** — `Colors.white` (pure `#FFFFFF`)
|
||||
used 98 times for primary text/icons, e.g. `home_screen.dart:113,122,128,
|
||||
211,248,267`, `settings_screen.dart:231,278,430`,
|
||||
`history_screen.dart:209,410`. `Colors.black` also appears at
|
||||
`rep_circle.dart:76` (`Colors.black87`, near-pure) as text-on-white in the
|
||||
neutral rep-circle state. None of these are the theme's actual
|
||||
near-white/near-black — they're Flutter's pure-value constants.
|
||||
- **Rule 2 (saturate your neutrals)** — `Colors.grey.shade900/800/700/400`
|
||||
are Material's standard zero-saturation grays (equal R=G=B), used as the
|
||||
entire background/surface system in place of `colorScheme.surface`
|
||||
(which, being seeded from indigo, *would* be saturated). Bypassing the
|
||||
theme produces exactly the generic-gray outcome the theme was set up to
|
||||
avoid.
|
||||
- **Rule 9 (distinct brightness values)** — `Colors.redAccent` (errors) and
|
||||
`Colors.orangeAccent`/`Colors.orange.shade800` (pending/resume state) are
|
||||
both used as status-signal colors of similar brightness in adjacent UI
|
||||
(e.g. `home_screen.dart:222` orangeAccent for active-session text next to
|
||||
`Colors.greenAccent` for success at line 200 — three status colors of
|
||||
comparable weight competing in one card).
|
||||
- **Rule 18 (container brightness limits, dark ≤~12%)** — The repeated
|
||||
`Scaffold(backgroundColor: Colors.grey.shade900)` /
|
||||
`AppBar(backgroundColor: Colors.grey.shade800)` pairing (Material
|
||||
`shade900`=`#212121`, luma 12.9%; `shade800`=`#424242`, luma 25.9% — a
|
||||
~13-point jump) appears in every screen's `Scaffold`/`AppBar`:
|
||||
`home_screen.dart:104,106`, `settings_screen.dart:275,277`,
|
||||
`history_screen.dart:206,208`, `workout_screen.dart:495,498`,
|
||||
`manual_workout_screen.dart:154,156`. This exceeds the ~12% dark-interface
|
||||
guideline every time it's used.
|
||||
- **Rule 20 (body text ≥16px)** — Extensive small body text below 16px:
|
||||
`fontSize: 9` at `history_screen.dart:612`, `fontSize: 11` (11 occurrences,
|
||||
e.g. `home_screen.dart:311`, `history_screen.dart:333,486,612`,
|
||||
`settings_screen.dart:388`), `fontSize: 12` (14 occurrences),
|
||||
`fontSize: 13` (7 occurrences) — well under the 16px minimum for
|
||||
supporting/secondary text throughout.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — `home_screen.dart:
|
||||
242` and `:261` set `padding: const EdgeInsets.symmetric(vertical: 14)`
|
||||
on full-width `ElevatedButton`s with no `horizontal:` argument, which
|
||||
defaults `horizontal` to `0.0` — the inverse of "horizontal ≈2x vertical".
|
||||
- **Rule 26 (no shadows in dark interfaces)** — The app declares
|
||||
`brightness: Brightness.dark` (`main.dart:71`), yet `rep_circle.dart:
|
||||
105-111` adds an explicit `BoxShadow(color: Colors.black26, blurRadius: 4,
|
||||
offset: Offset(0, 2))` to the rep-tracking circle — the one shadow in the
|
||||
whole app, in a UI this rule says shouldn't have any.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — standard Material icons/widgets are already
|
||||
optically centered by the framework; no custom asymmetric glyphs.
|
||||
- Rule 6 (letter-spacing/line-height by size) — the only `letterSpacing`
|
||||
uses found (`home_screen.dart:311` → 1.1, `history_screen.dart:333` → 1.3,
|
||||
`settings_screen.dart:388` → 1.4) are all on the same small `fontSize: 11`
|
||||
eyebrow-label text, consistently given positive tracking as the rule
|
||||
recommends for small text — no counter-example at larger sizes to check
|
||||
against, so marked N/A rather than a forced Pass.
|
||||
- Rule 7 (border contrast) — `Border.all(color: color.withValues(alpha:
|
||||
0.4))` (`settings_screen.dart:491`) derives border color from the same
|
||||
status color as the fill, by design (a tinted pill), not a
|
||||
container-edge border this rule targets.
|
||||
- Rule 8 (align with something else) — standard `Column`/`Row`/`ListView`
|
||||
layouts; no cross-screen alignment grid to check.
|
||||
- Rule 12 (order by visual weight) — screens are single-column flows
|
||||
(cards stacked top-to-bottom); no left/right or center/edge weight
|
||||
arrangement to evaluate.
|
||||
- Rule 13 (12-column grid) — mobile single-column layouts throughout; no
|
||||
multi-column grid system in use.
|
||||
- Rule 14 (space between contrast edges) — cannot be verified statically
|
||||
without rendering the widget tree.
|
||||
- Rule 15 (closer elements lighter) — `Card`s at `shade800` sit on
|
||||
`shade900` backgrounds (lighter-on-darker as they "lift"), which is
|
||||
directionally correct, but see Rule 18 above for the magnitude issue.
|
||||
- Rule 17 (simple on complex) — flat-colored cards/containers throughout;
|
||||
nothing complex to conflict with.
|
||||
- Rule 19 (outer padding ≥ inner padding) — spot-checked
|
||||
`home_screen.dart:143` (`EdgeInsets.all(24)` outer) vs. its nested
|
||||
`_WorkoutCard` internal padding (`EdgeInsets.all(16)`,
|
||||
`home_screen.dart:188`) — outer ≥ inner, consistent with the rule; not
|
||||
exhaustively checked across all 24 files.
|
||||
- Rule 21 (line length ~70 chars) — Flutter `Text` wraps by default at
|
||||
widget width; no unbounded-line risk equivalent to the Tk surface.
|
||||
- Rule 23 (two typefaces max) — no custom `fontFamily` set anywhere; the
|
||||
whole app uses the Material/system default typeface. Trivially compliant.
|
||||
- Rule 24 (nest corners) — `BorderRadius.circular(8)` is reused verbatim
|
||||
across unrelated containers (`home_screen.dart:301`,
|
||||
`calendar_widget.dart:63`, `history_screen.dart:402,643,705,772`,
|
||||
`settings_screen.dart:490,548,587`) but none of these visibly nest inside
|
||||
another rounded container in the surrounding code, so there's no
|
||||
outer/inner radius relationship to check.
|
||||
- Rule 25 (avoid adjacent hard divides) — only one `Divider` found
|
||||
(`exercise_tile.dart:115`), not adjacent to another border/divide.
|
||||
- Rule 27 (don't mix depth techniques) — the app consistently uses flat
|
||||
`Container`/`Card` fills with no shadow except the single instance flagged
|
||||
under Rule 26; effectively one depth style (none) throughout, so no
|
||||
mixing to flag.
|
||||
- Rule 28 (lower icon contrast next to text) — icons consistently use
|
||||
`Colors.white54`/`Colors.white38`/`Colors.white70` (already
|
||||
lower-contrast than adjacent full-white/near-white text) rather than full
|
||||
`Colors.white`, e.g. `exercise_tile.dart:150,160,167,177,248,252`,
|
||||
`history_screen.dart:331,486,507` — this one is actually already followed
|
||||
reasonably consistently. Pass.
|
||||
|
||||
### Notes
|
||||
|
||||
- Rule 4 is the dominant finding for this surface too: an unused
|
||||
`ColorScheme.fromSeed` plus ~210 ad hoc `Colors.*`/`Color(0x...)` literals
|
||||
means every other color/contrast rule (1, 2, 9, 18) is failing as a direct
|
||||
consequence of the same root cause, not independently. Routing all 24
|
||||
files through `Theme.of(context).colorScheme` (or a small shared
|
||||
`AppColors`/`AppTextStyles` class) would be the highest-leverage single
|
||||
fix.
|
||||
- The coincidental hex overlap between `Color(0xFFFF4444)`/`Color(0xFF88CCFF)`
|
||||
(Flutter) and `#ff4444`/`#88ccff` (Python/Tkinter) shows the two UI
|
||||
surfaces are visually related by convention only — there is no shared
|
||||
token file either could import from, on either language side.
|
||||
|
||||
## Shared gatelock library
|
||||
|
||||
`~/utils/gatelock` is **not** its own git repo — `git -C ~/utils/gatelock
|
||||
rev-parse --show-toplevel` resolves to `/home/kuhy/utils`, so it's a
|
||||
subdirectory of the `~/utils` monorepo. Per audit scope, gatelock itself was
|
||||
not walked against all 28 rules and no separate
|
||||
`~/utils/gatelock/DESIGN_AUDIT_TODO.md` was written.
|
||||
|
||||
What's relevant here: gatelock defines exactly **one** real design token —
|
||||
`LockConfig.bg: str = "#1a1a1a"` (`~/utils/gatelock/gatelock/_window.py:71`),
|
||||
applied via `self.root.configure(bg=self._config.bg, ...)` in
|
||||
`LockWindow.setup()` (`_window.py:143`). Both consumer repos re-hardcode
|
||||
this same literal instead of reading it back off their own `LockConfig`
|
||||
instance:
|
||||
|
||||
- **screen-locker** (this repo) — `#1a1a1a` appears 31 times across 9 files
|
||||
(see the Tkinter section above) despite `screen_lock.py:148-153`
|
||||
constructing a `LockConfig` instance (as `config`) just a few lines above
|
||||
each of those files' widget-creation call sites.
|
||||
- **diet-guard** — not inspected as part of this audit (out of scope for
|
||||
this repo's report), but per the shared-infra note in the task, it is the
|
||||
other known consumer of `LockConfig`/`LockWindow` and should be checked
|
||||
for the same duplication pattern if/when a design audit is run there.
|
||||
|
||||
Fixing the screen-locker Rule 4 finding above by having widget-creation code
|
||||
read `self._lock_config.bg` (threaded through from the `LockConfig` already
|
||||
built in `ScreenLocker.__init__`) instead of re-typing `"#1a1a1a"` would
|
||||
close this loop without needing any gatelock-side change.
|
||||
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Krzysztof Rudnicki
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
77
README.md
77
README.md
@ -1,81 +1,8 @@
|
||||
# screen-locker
|
||||
|
||||
Tkinter/systemd screen locker with workout tracking, shared sick days, and
|
||||
Tkinter/systemd screen locker with workout tracking, sick-day management, and
|
||||
wake-alarm integration. It enforces a workout cadence by locking the screen
|
||||
until a verified (RunnerUp, StrongLifts) or budgeted manual workout is logged.
|
||||
|
||||
## Sick days
|
||||
|
||||
A sick day is a date in the fleet-wide [`sickdays`](https://github.com/kuhyx/utils/tree/main/sickdays)
|
||||
pool, nothing else: no budget, countdown, justification or debt. The lock
|
||||
screen's **I'm sick** button (retry screen, no-phone screen and the Tue-Thu
|
||||
prompt) marks today with one tap and unlocks; `sickdays add` or the phone do
|
||||
the same. On a sick day the workout lock stands down,
|
||||
wake-alarm's workday penalty is void, and shutdown is 20:00 plus the gaming
|
||||
pay of everything credited that day, capped at 23:00
|
||||
(`earned_time.sick_shutdown_from`). A day marked after its daily reset is
|
||||
raised to it by the next live pass (`_sick_floor`), and every later credit
|
||||
that day raises it again.
|
||||
|
||||
A credit landing after tonight's shutdown adds its reward to that shutdown,
|
||||
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`).
|
||||
|
||||
A sick day may *keep* lockers (`sickdays add --keep workout`). A kept workout
|
||||
lock behaves exactly as on a normal day (lock, quota, relaxed-day penalty on
|
||||
that date); only the 20:00 shutdown floor still applies, since it belongs to
|
||||
the day, not to a locker. The one-tap button keeps nothing. The missed-alarm
|
||||
penalty is void on its ring day only if `alarm` is off, and on its penalty day
|
||||
only if `workout` is off. All of it goes through `_sick.stands_down_workout`.
|
||||
|
||||
## Shutdown time
|
||||
|
||||
Every day starts at **19:00** from 2026-10-01, 20:00 before it (`base_minutes()` in
|
||||
`screen_locker/_shutdown_base.py`)
|
||||
and bonuses push it later, capped at 23:00: the first counted workout +2h,
|
||||
each further one +1h, an accepted LeetCode submission that day +1h (flat,
|
||||
read from leetcode-guard's ledger, once per day), and a credited paper-book
|
||||
reading session of 20+ pages / 20+ minutes +1h (flat, read from
|
||||
[book-guard](https://github.com/kuhyx/book-guard)'s ledger, once per day, keyed
|
||||
on when the reading ended). The config is re-derived from
|
||||
those sources on each new day, so nothing has to be "remembered" across reboots.
|
||||
|
||||
A RunnerUp run is credited from its TCX export, found in the WebDAV drop
|
||||
directory RunnerUp uploads to on this machine (`~/data/cloud/RunnerUp/`, plus
|
||||
`processed/` once endurain-import has taken it) or, when a phone is adb-visible,
|
||||
in `/sdcard/Documents/RunnerUp/`. The 15-minute `workout-sync.timer` scans both,
|
||||
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
|
||||
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.
|
||||
until a RunnerUp-verified (or explicitly justified) workout is logged.
|
||||
|
||||
## MCP server (Claude Code integration)
|
||||
|
||||
|
||||
141
arm.sh
141
arm.sh
@ -1,141 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Arm the workout screen locker — install units, enable timers, verify.
|
||||
#
|
||||
# One command, because re-arming used to be a four-command sequence that was
|
||||
# easy to half-do. On 2026-08-04 a systemd ordering cycle silently disabled
|
||||
# early-bird-workout-check.timer and enforcement stopped for thirteen days with
|
||||
# nothing on the machine saying so; `systemctl enable` alone would NOT have
|
||||
# caught that, because enable "succeeds" while systemd deletes the timer job.
|
||||
# So this script always finishes by asking systemd what it actually scheduled,
|
||||
# and fails loudly when the answer is "nothing".
|
||||
#
|
||||
# Usage:
|
||||
# ./arm.sh # install, enable, verify
|
||||
# ./arm.sh --skip-today # ...but do not lock today (adds a scheduled skip)
|
||||
# ./arm.sh --status # verify only; change nothing
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly SCRIPT_DIR
|
||||
readonly USER_UNIT_DIR="$HOME/.config/systemd/user"
|
||||
|
||||
# shellcheck source=scripts/disarm_guard.sh
|
||||
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
|
||||
|
||||
# Units that must be on disk for enforcement to be schedulable.
|
||||
readonly UNITS=(
|
||||
"workout-locker.service"
|
||||
"workout-locker.timer"
|
||||
"early-bird-workout-check.timer"
|
||||
"workout-sync.service"
|
||||
"workout-sync.timer"
|
||||
"earner-bonus.service"
|
||||
)
|
||||
|
||||
# Only the timers (and the ledger watch) get enabled; the services are
|
||||
# triggered by them and by login.
|
||||
readonly TIMERS=(
|
||||
"early-bird-workout-check.timer"
|
||||
"workout-locker.timer"
|
||||
"workout-sync.timer"
|
||||
"earner-bonus.path"
|
||||
)
|
||||
|
||||
SKIP_TODAY=0
|
||||
STATUS_ONLY=0
|
||||
REARM=0
|
||||
|
||||
usage() {
|
||||
echo "Usage: $(basename "$0") [--skip-today] [--status] [--rearm]"
|
||||
echo " --skip-today Arm the locker but exempt today (no lock until tomorrow)"
|
||||
echo " --status Report whether enforcement is armed; change nothing"
|
||||
echo " --rearm Clear the disarm marker + unmask units, then arm"
|
||||
exit 0
|
||||
}
|
||||
|
||||
verify_armed() {
|
||||
python3 "$SCRIPT_DIR/scripts/check_enforcement_armed.py"
|
||||
}
|
||||
|
||||
add_skip_for_today() {
|
||||
# Delegated to Python rather than hand-editing JSON in bash: the file is
|
||||
# the same one the lock chain reads, and a malformed write would be read as
|
||||
# "not a skip" and lock anyway.
|
||||
python3 "$SCRIPT_DIR/scripts/add_scheduled_skip.py" --date today
|
||||
}
|
||||
|
||||
main() {
|
||||
if ((STATUS_ONLY)); then
|
||||
# --status changes nothing, so it stays usable while disarmed - but it
|
||||
# must say so loudly, or "armed: no" reads like a bug instead of intent.
|
||||
if report_disarmed; then
|
||||
return
|
||||
fi
|
||||
verify_armed
|
||||
return
|
||||
fi
|
||||
|
||||
if ((REARM)); then
|
||||
clear_disarm_marker
|
||||
else
|
||||
refuse_if_disarmed
|
||||
fi
|
||||
|
||||
echo "Installing units into $USER_UNIT_DIR"
|
||||
mkdir -p "$USER_UNIT_DIR"
|
||||
for unit in "${UNITS[@]}"; do
|
||||
cp "$SCRIPT_DIR/$unit" "$USER_UNIT_DIR/$unit"
|
||||
done
|
||||
# Rendered from the earned_time registry rather than copied.
|
||||
PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker._earner_units "$USER_UNIT_DIR"
|
||||
|
||||
systemctl --user daemon-reload
|
||||
|
||||
if ((SKIP_TODAY)); then
|
||||
# Register the exemption BEFORE the timers can fire, so arming can
|
||||
# never race the first re-check and lock the machine anyway.
|
||||
add_skip_for_today
|
||||
fi
|
||||
|
||||
echo "Enabling timers"
|
||||
systemctl --user enable --now "${TIMERS[@]}"
|
||||
|
||||
# The whole point: `enable` returning 0 is not proof of anything.
|
||||
echo ""
|
||||
verify_armed
|
||||
echo ""
|
||||
echo "✓ Screen locker armed."
|
||||
if ((SKIP_TODAY)); then
|
||||
echo " Today is exempt — enforcement begins tomorrow."
|
||||
fi
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--skip-today)
|
||||
SKIP_TODAY=1
|
||||
shift
|
||||
;;
|
||||
--status)
|
||||
STATUS_ONLY=1
|
||||
shift
|
||||
;;
|
||||
--rearm)
|
||||
REARM=1
|
||||
shift
|
||||
;;
|
||||
-h | --help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
main "$@"
|
||||
@ -1,6 +0,0 @@
|
||||
{
|
||||
"_comment": "Shared literal fixture for the phone->PC workout poke (v1). Both the Python receiver and the Dart sender test against THESE bytes. body_utf8 is the exact request body; signature = hex(HMAC-SHA256(bytes.fromhex(key_hex), body_utf8.encode('utf-8'))). Never re-serialize before verifying.",
|
||||
"key_hex": "7f3c9a1e5b2d4f6081a3c5e7092b4d6f8a1c3e5072946b8d0f2a4c6e8013579b",
|
||||
"body_utf8": "{\"v\":1,\"sent_at_ms\":1791558449000,\"nonce\":\"0b1e6c2a-9f4d-4c1b-8e7a-3d5f6a7b8c9d\",\"sandbox\":false,\"record_id\":\"2026-10-09T15:10:40.953\",\"payload\":{\"date\":\"2026-10-09\",\"start_time\":\"2026-10-09T15:10:40.953\",\"workout_type\":\"A\",\"duration_seconds\":7020.5,\"succeeded\":true,\"exercises\":[{\"name\":\"Squat\",\"weight_kg\":100.0,\"sets\":[5,5,5,5,5]}],\"note\":\"zażółć gęślą jaźń\"}}",
|
||||
"signature_hex": "98b0b80fe717079c800e79562f669fd0189d89c3578a5bbf973761a0e7a3a3f5"
|
||||
}
|
||||
@ -1,78 +0,0 @@
|
||||
# Workout poke: phone -> PC wire contract (v1)
|
||||
|
||||
The phone sends a finished StrongLifts session straight to the PC over the
|
||||
home LAN, so the credit (shutdown time, notification) lands in
|
||||
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
|
||||
session that arrives both ways is credited once.
|
||||
|
||||
## Transport
|
||||
|
||||
- `POST http://<pc-host>:8774/v1/workout`, `Content-Type: application/json`.
|
||||
(8773 until 2026-10-10: that is book-guard's desktop wrapper's port.)
|
||||
- `<pc-host>` is a phone setting, default `192.168.1.43` (static on the PC).
|
||||
LAN only: the PC firewall accepts tcp/8774 from `192.168.1.0/24` and nothing
|
||||
else. No WireGuard. Off the home LAN the poke fails fast and the regular
|
||||
sync is the only path.
|
||||
- Header `X-Poke-Signature: <hex HMAC-SHA256(key, raw body bytes)>`.
|
||||
The PC verifies the MAC over the bytes **as received** and only then parses
|
||||
them. Neither side may re-serialize JSON to compute or check the MAC.
|
||||
- Key: 32 random bytes, hex, PC copy at `~/.config/workout_poke/key`
|
||||
(mode 600); phone copy in the Android keystore, put there by
|
||||
`scripts/pair_phone.sh` over adb.
|
||||
|
||||
## Request body
|
||||
|
||||
```json
|
||||
{"v":1,"sent_at_ms":<int epoch ms>,"nonce":"<uuid4>","sandbox":<bool>,
|
||||
"record_id":"<sync record id>","payload":{<session exactly as synced>}}
|
||||
```
|
||||
|
||||
- `payload` is the same map the phone puts in its sync log for the session;
|
||||
the PC feeds `(record_id, payload)` to `ingest_session_records`, which
|
||||
re-validates it (never trusts `succeeded`).
|
||||
- `sandbox` is inside the signed body. A sandbox request is verified, timed
|
||||
and answered, but **never written anywhere** and never credited.
|
||||
|
||||
## PC checks, in order (each rejection is logged at warning)
|
||||
|
||||
1. Signature matches -> else `401`.
|
||||
2. `|now - sent_at_ms| <= 120 s` -> else `401` (replay window).
|
||||
3. `nonce` not seen within the window -> else `409`.
|
||||
4. `v == 1` and fields present -> else `400`.
|
||||
|
||||
## Response (always JSON)
|
||||
|
||||
```json
|
||||
{"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>,
|
||||
"shutdown":"HH:MM"|null,"pc_ms":<int>,
|
||||
"reason":"<sentence a human can act on>"}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
| case | ok | credited | duplicate |
|
||||
|---|---|---|---|
|
||||
| newly credited | true | true | false |
|
||||
| already in `log.json` (e.g. the sync got there first) | true | false | true |
|
||||
| logged, but today's credit slot was already paid by another copy of the same workout | true | false | false |
|
||||
| signed but does not count (too short, no date): `reason` says why | false | false | false |
|
||||
| sandbox | true | false | false |
|
||||
|
||||
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
|
||||
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`
|
||||
`null`. The PC answers a `413` without reading
|
||||
the body, so the phone may see a connection reset instead of the reply.
|
||||
|
||||
## Shared fixture
|
||||
|
||||
`contracts/workout_poke_v1.json` holds a literal key, body and expected
|
||||
signature (with a float and non-ASCII text, the usual cross-language traps).
|
||||
The Python receiver and the Dart sender both test against it, so a drift on
|
||||
either side fails that side's tests.
|
||||
@ -1,146 +0,0 @@
|
||||
## Flutter app (stronglift_replacement/workout_app/)
|
||||
|
||||
Design-token entry point: `lib/main.dart:68-74` declares
|
||||
`ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo,
|
||||
brightness: Brightness.dark), useMaterial3: true)` — a real Material 3 seed
|
||||
theme exists. However, **`Theme.of(context)` / `colorScheme` is referenced
|
||||
zero times anywhere in `lib/screens/` or `lib/widgets/`** (confirmed via
|
||||
repo-wide grep). The theme is declared but never consumed — every one of the
|
||||
24 .dart files under `lib/` hardcodes colors directly instead.
|
||||
|
||||
- `Colors.*` literals: **~210 occurrences** across `screens/` and
|
||||
`widgets/`, 27 distinct named colors. Most common: `Colors.white` (98×),
|
||||
`Colors.grey.shade800` (18×), `Colors.redAccent` (12×),
|
||||
`Colors.greenAccent` (11×), `Colors.grey.shade900` (10×).
|
||||
- Raw hex `Color(0xFF...)` literals bypassing `Colors.*` entirely:
|
||||
`manual_workout_screen.dart:173,201` (`Color(0xFFFF4444)`) and
|
||||
`manual_workout_screen.dart:238,246` (`Color(0xFF88CCFF)`) — these are the
|
||||
**exact same hex values** independently hardcoded on the Python/Tkinter
|
||||
side (`#ff4444` and `#88ccff`, see e.g. `_sick_dialog.py:70`,
|
||||
`_manual_workout_dialog.py:58`), coincidentally kept in sync only because
|
||||
no one has touched either yet.
|
||||
- `fontSize:`/`fontWeight:` literals: 72 occurrences; `history_screen.dart`
|
||||
alone uses 12 distinct font sizes (9, 11, 12, 13, 14, 15, 16, 17, 18, 20,
|
||||
22, 26).
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — `main.dart`
|
||||
builds a `ColorScheme.fromSeed`, but it is dead code from a theming
|
||||
standpoint: no screen or widget reads it. Every screen re-derives its own
|
||||
ad hoc dark palette from `Colors.grey.shade900/800/700` plus assorted
|
||||
accent colors, so a single rebrand (e.g. changing the seed color) would
|
||||
require manually editing all 24 files instead of one.
|
||||
- **Rule 1 (near-black/white, not pure)** — `Colors.white` (pure `#FFFFFF`)
|
||||
used 98 times for primary text/icons, e.g. `home_screen.dart:113,122,128,
|
||||
211,248,267`, `settings_screen.dart:231,278,430`,
|
||||
`history_screen.dart:209,410`. `Colors.black` also appears at
|
||||
`rep_circle.dart:76` (`Colors.black87`, near-pure) as text-on-white in the
|
||||
neutral rep-circle state. None of these are the theme's actual
|
||||
near-white/near-black — they're Flutter's pure-value constants.
|
||||
- **Rule 2 (saturate your neutrals)** — `Colors.grey.shade900/800/700/400`
|
||||
are Material's standard zero-saturation grays (equal R=G=B), used as the
|
||||
entire background/surface system in place of `colorScheme.surface`
|
||||
(which, being seeded from indigo, *would* be saturated). Bypassing the
|
||||
theme produces exactly the generic-gray outcome the theme was set up to
|
||||
avoid.
|
||||
- **Rule 9 (distinct brightness values)** — `Colors.redAccent` (errors) and
|
||||
`Colors.orangeAccent`/`Colors.orange.shade800` (pending/resume state) are
|
||||
both used as status-signal colors of similar brightness in adjacent UI
|
||||
(e.g. `home_screen.dart:222` orangeAccent for active-session text next to
|
||||
`Colors.greenAccent` for success at line 200 — three status colors of
|
||||
comparable weight competing in one card).
|
||||
- **Rule 18 (container brightness limits, dark ≤~12%)** — The repeated
|
||||
`Scaffold(backgroundColor: Colors.grey.shade900)` /
|
||||
`AppBar(backgroundColor: Colors.grey.shade800)` pairing (Material
|
||||
`shade900`=`#212121`, luma 12.9%; `shade800`=`#424242`, luma 25.9% — a
|
||||
~13-point jump) appears in every screen's `Scaffold`/`AppBar`:
|
||||
`home_screen.dart:104,106`, `settings_screen.dart:275,277`,
|
||||
`history_screen.dart:206,208`, `workout_screen.dart:495,498`,
|
||||
`manual_workout_screen.dart:154,156`. This exceeds the ~12% dark-interface
|
||||
guideline every time it's used.
|
||||
- **Rule 20 (body text ≥16px)** — Extensive small body text below 16px:
|
||||
`fontSize: 9` at `history_screen.dart:612`, `fontSize: 11` (11 occurrences,
|
||||
e.g. `home_screen.dart:311`, `history_screen.dart:333,486,612`,
|
||||
`settings_screen.dart:388`), `fontSize: 12` (14 occurrences),
|
||||
`fontSize: 13` (7 occurrences) — well under the 16px minimum for
|
||||
supporting/secondary text throughout.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — `home_screen.dart:
|
||||
242` and `:261` set `padding: const EdgeInsets.symmetric(vertical: 14)`
|
||||
on full-width `ElevatedButton`s with no `horizontal:` argument, which
|
||||
defaults `horizontal` to `0.0` — the inverse of "horizontal ≈2x vertical".
|
||||
- **Rule 26 (no shadows in dark interfaces)** — The app declares
|
||||
`brightness: Brightness.dark` (`main.dart:71`), yet `rep_circle.dart:
|
||||
105-111` adds an explicit `BoxShadow(color: Colors.black26, blurRadius: 4,
|
||||
offset: Offset(0, 2))` to the rep-tracking circle — the one shadow in the
|
||||
whole app, in a UI this rule says shouldn't have any.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — standard Material icons/widgets are already
|
||||
optically centered by the framework; no custom asymmetric glyphs.
|
||||
- Rule 6 (letter-spacing/line-height by size) — the only `letterSpacing`
|
||||
uses found (`home_screen.dart:311` → 1.1, `history_screen.dart:333` → 1.3,
|
||||
`settings_screen.dart:388` → 1.4) are all on the same small `fontSize: 11`
|
||||
eyebrow-label text, consistently given positive tracking as the rule
|
||||
recommends for small text — no counter-example at larger sizes to check
|
||||
against, so marked N/A rather than a forced Pass.
|
||||
- Rule 7 (border contrast) — `Border.all(color: color.withValues(alpha:
|
||||
0.4))` (`settings_screen.dart:491`) derives border color from the same
|
||||
status color as the fill, by design (a tinted pill), not a
|
||||
container-edge border this rule targets.
|
||||
- Rule 8 (align with something else) — standard `Column`/`Row`/`ListView`
|
||||
layouts; no cross-screen alignment grid to check.
|
||||
- Rule 12 (order by visual weight) — screens are single-column flows
|
||||
(cards stacked top-to-bottom); no left/right or center/edge weight
|
||||
arrangement to evaluate.
|
||||
- Rule 13 (12-column grid) — mobile single-column layouts throughout; no
|
||||
multi-column grid system in use.
|
||||
- Rule 14 (space between contrast edges) — cannot be verified statically
|
||||
without rendering the widget tree.
|
||||
- Rule 15 (closer elements lighter) — `Card`s at `shade800` sit on
|
||||
`shade900` backgrounds (lighter-on-darker as they "lift"), which is
|
||||
directionally correct, but see Rule 18 above for the magnitude issue.
|
||||
- Rule 17 (simple on complex) — flat-colored cards/containers throughout;
|
||||
nothing complex to conflict with.
|
||||
- Rule 19 (outer padding ≥ inner padding) — spot-checked
|
||||
`home_screen.dart:143` (`EdgeInsets.all(24)` outer) vs. its nested
|
||||
`_WorkoutCard` internal padding (`EdgeInsets.all(16)`,
|
||||
`home_screen.dart:188`) — outer ≥ inner, consistent with the rule; not
|
||||
exhaustively checked across all 24 files.
|
||||
- Rule 21 (line length ~70 chars) — Flutter `Text` wraps by default at
|
||||
widget width; no unbounded-line risk equivalent to the Tk surface.
|
||||
- Rule 23 (two typefaces max) — no custom `fontFamily` set anywhere; the
|
||||
whole app uses the Material/system default typeface. Trivially compliant.
|
||||
- Rule 24 (nest corners) — `BorderRadius.circular(8)` is reused verbatim
|
||||
across unrelated containers (`home_screen.dart:301`,
|
||||
`calendar_widget.dart:63`, `history_screen.dart:402,643,705,772`,
|
||||
`settings_screen.dart:490,548,587`) but none of these visibly nest inside
|
||||
another rounded container in the surrounding code, so there's no
|
||||
outer/inner radius relationship to check.
|
||||
- Rule 25 (avoid adjacent hard divides) — only one `Divider` found
|
||||
(`exercise_tile.dart:115`), not adjacent to another border/divide.
|
||||
- Rule 27 (don't mix depth techniques) — the app consistently uses flat
|
||||
`Container`/`Card` fills with no shadow except the single instance flagged
|
||||
under Rule 26; effectively one depth style (none) throughout, so no
|
||||
mixing to flag.
|
||||
- Rule 28 (lower icon contrast next to text) — icons consistently use
|
||||
`Colors.white54`/`Colors.white38`/`Colors.white70` (already
|
||||
lower-contrast than adjacent full-white/near-white text) rather than full
|
||||
`Colors.white`, e.g. `exercise_tile.dart:150,160,167,177,248,252`,
|
||||
`history_screen.dart:331,486,507` — this one is actually already followed
|
||||
reasonably consistently. Pass.
|
||||
|
||||
### Notes
|
||||
|
||||
- Rule 4 is the dominant finding for this surface too: an unused
|
||||
`ColorScheme.fromSeed` plus ~210 ad hoc `Colors.*`/`Color(0x...)` literals
|
||||
means every other color/contrast rule (1, 2, 9, 18) is failing as a direct
|
||||
consequence of the same root cause, not independently. Routing all 24
|
||||
files through `Theme.of(context).colorScheme` (or a small shared
|
||||
`AppColors`/`AppTextStyles` class) would be the highest-leverage single
|
||||
fix.
|
||||
- The coincidental hex overlap between `Color(0xFFFF4444)`/`Color(0xFF88CCFF)`
|
||||
(Flutter) and `#ff4444`/`#88ccff` (Python/Tkinter) shows the two UI
|
||||
surfaces are visually related by convention only — there is no shared
|
||||
token file either could import from, on either language side.
|
||||
@ -1,28 +0,0 @@
|
||||
## Shared gatelock library
|
||||
|
||||
`~/src/utils/gatelock` is **not** its own git repo — `git -C ~/src/utils/gatelock
|
||||
rev-parse --show-toplevel` resolves to `/home/kuhy/src/utils`, so it's a
|
||||
subdirectory of the `~/src/utils` monorepo. Per audit scope, gatelock itself was
|
||||
not walked against all 28 rules and no separate
|
||||
`~/src/utils/gatelock/DESIGN_AUDIT_TODO.md` was written.
|
||||
|
||||
What's relevant here: gatelock defines exactly **one** real design token —
|
||||
`LockConfig.bg: str = "#1a1a1a"` (`~/src/utils/gatelock/gatelock/_window.py:71`),
|
||||
applied via `self.root.configure(bg=self._config.bg, ...)` in
|
||||
`LockWindow.setup()` (`_window.py:143`). Both consumer repos re-hardcode
|
||||
this same literal instead of reading it back off their own `LockConfig`
|
||||
instance:
|
||||
|
||||
- **screen-locker** (this repo) — `#1a1a1a` appears 31 times across 9 files
|
||||
(see the Tkinter section above) despite `screen_lock.py:148-153`
|
||||
constructing a `LockConfig` instance (as `config`) just a few lines above
|
||||
each of those files' widget-creation call sites.
|
||||
- **diet-guard** — not inspected as part of this audit (out of scope for
|
||||
this repo's report), but per the shared-infra note in the task, it is the
|
||||
other known consumer of `LockConfig`/`LockWindow` and should be checked
|
||||
for the same duplication pattern if/when a design audit is run there.
|
||||
|
||||
Fixing the screen-locker Rule 4 finding above by having widget-creation code
|
||||
read `self._lock_config.bg` (threaded through from the `LockConfig` already
|
||||
built in `ScreenLocker.__init__`) instead of re-typing `"#1a1a1a"` would
|
||||
close this loop without needing any gatelock-side change.
|
||||
@ -1,154 +0,0 @@
|
||||
## Python/Tkinter lock UI (screen_locker/)
|
||||
|
||||
Design-token entry point check: **no `ttk.Style()` call anywhere in the
|
||||
package** (confirmed via repo-wide grep) and `_constants.py` holds only
|
||||
business-logic constants (budgets, timeouts, file paths) — zero color/font/
|
||||
spacing tokens. Every color, font, and padding value is a literal typed
|
||||
directly at each `tk.Label`/`tk.Button`/`tk.Frame`/`tk.Entry` call site,
|
||||
independently, in 9 files. Evidence:
|
||||
|
||||
- Hex color literals: **100 occurrences, 23 distinct values**, across
|
||||
`screen_lock.py` (6), `_ui_widgets.py` (6), `_window_setup.py` (3),
|
||||
`status_view.py` (21), `_heat_skip.py` (7 + 4 module-level constants),
|
||||
`_manual_workout_dialog.py` (15), `_manual_workout_widgets.py` (12),
|
||||
`_sick_dialog.py` (18), `_temperature_status_mixin.py` (5).
|
||||
`#1a1a1a` alone (the background) appears **31 times** — and it is *also*
|
||||
already defined once, correctly, as `LockConfig.bg = "#1a1a1a"` in
|
||||
`~/src/utils/gatelock/gatelock/_window.py:71`. None of the 31 in-repo literals
|
||||
import or reference it; `LockWindow.setup()` in gatelock applies
|
||||
`config.bg` to the root window (`_window.py:143`), and then every
|
||||
screen-locker dialog re-hardcodes the same string as if gatelock's value
|
||||
didn't exist.
|
||||
- `font=("Arial", N[, "bold"])` literals: **25 occurrences**, 6 distinct
|
||||
size/weight combos, e.g. `_ui_widgets.py:45,64`, `_sick_dialog.py:111,121`,
|
||||
`_manual_workout_widgets.py:70,89,97,116,126,137,145,164,174`.
|
||||
`_heat_skip.py:12-17` breaks pattern entirely with its own local
|
||||
`_FONT = "monospace"` constant (line 17) plus four color constants
|
||||
(`_BG`, `_FG_MAIN`, `_FG_SUB`, `_BTN_SKIP`, `_BTN_NO`) — the only file in
|
||||
the package that centralizes *anything*, and it does so locally/unshared
|
||||
rather than in a common module.
|
||||
- `padx=`/`pady=` literals: **59 occurrences**, 13 distinct values (1, 2, 5,
|
||||
6, 8, 10, 12, 14, 15, 20, 28, 30) spread across 7 of the 9 files.
|
||||
|
||||
### Violations
|
||||
|
||||
- **Rule 4 (everything deliberate / single source of truth)** — No
|
||||
`ttk.Style()`, no shared colors/fonts/spacing module. Same visual decision
|
||||
(e.g. background `#1a1a1a`) is independently re-typed 31 times across 9
|
||||
files instead of imported once. `_heat_skip.py:12-17` even invents its own
|
||||
local token block, proving the pattern was known and simply not applied
|
||||
package-wide. Fixing any single visual value (e.g. rebranding the
|
||||
background) means editing up to 9 files by hand with no compiler/lint
|
||||
check that all sites were caught.
|
||||
- **Rule 1 (near-black/white, not pure)** — `bg="#1a1a1a"` (near-black,
|
||||
fine) is paired with pure white text: `_ui_widgets.py:38,57` default
|
||||
`color: str = "white"`, plus explicit `fg="white"` at `_window_setup.py:40`,
|
||||
`_sick_dialog.py:112,128,138` (X11 name `"white"` = `#FFFFFF`), and 6 more
|
||||
in `_manual_workout_widgets.py` (lines 90, 112→ label fg, 116, 137, 158,
|
||||
165). Pure-white-on-near-black is the harsh contrast this rule warns
|
||||
against; should be a near-white (e.g. `#f0f0f0`/`#eaeaea`).
|
||||
- **Rule 2 (saturate your neutrals)** — `#1a1a1a` and `#2a2a2a` have equal
|
||||
R=G=B (26,26,26 and 42,42,42): true zero-saturation gray, not tinted warm
|
||||
or cool. Generic gray per the rule's definition.
|
||||
- **Rule 9 (distinct brightness values in a palette)** — `#ffaa00` (warning/
|
||||
bonus amber, e.g. `screen_lock.py:319`, `status_view.py:181`) and
|
||||
`#ff8844` (network/temp-check failure, e.g. `status_view.py:121,243`,
|
||||
`_temperature_status_mixin.py:50,57,65`) are near-identical in hue and
|
||||
brightness despite signaling different states (bonus/pending vs.
|
||||
error/failure) — they will read as the same color at a glance.
|
||||
- **Rule 11 (mathematically related measurements)** — `padx`/`pady` values
|
||||
(1, 2, 5, 6, 8, 10, 12, 14, 15, 20, 28, 30) don't follow a consistent
|
||||
scale (not all multiples of 4 or 8); e.g. `pady=1` at `status_view.py:177`
|
||||
sits next to `pady=2` (`status_view.py:160`) and `pady=28`
|
||||
(`_heat_skip.py:74`) elsewhere — no discernible spacing system.
|
||||
- **Rule 20 (body text ≥16px)** — Multiple body-text sizes sit well under
|
||||
16px: `font_size=10` at `status_view.py:248,253,255` (the last one,
|
||||
line 255, also uses the lowest-contrast color in the file, `#666666`, for
|
||||
a 10px label — compounding readability), `font_size=11` at
|
||||
`status_view.py:199`, `_heat_skip.py:91,104` (`font=(_FONT, 11)`),
|
||||
`font_size=12` at `status_view.py:160,212,225,239,243`,
|
||||
`_temperature_status_mixin.py:43,50,57,65`, `_sick_dialog.py:135`
|
||||
(`font=("Arial", 12)` on the `tk.Text` justification box), `font_size=13`
|
||||
at `status_view.py:121,123,181`.
|
||||
- **Rule 21 (line length ~70 chars)** — No widget in the package sets
|
||||
`wraplength` (confirmed: zero matches for `wraplength` repo-wide), so long
|
||||
strings render as one unbroken line regardless of window width. Concrete
|
||||
case: `_sick_dialog.py:205-207`, the commitment-prompt text "If you say
|
||||
YES and skip via 'I'm sick' tomorrow, the sick day costs 2x normal." is
|
||||
~80 characters and will render as a single line at `font_size=16` with no
|
||||
wrap control.
|
||||
- **Rule 22 (button padding: horizontal ≈2x vertical)** — Only
|
||||
`_heat_skip.py:92,93,105,106` sets explicit button padding
|
||||
(`padx=14, pady=5`, ratio 2.8x — roughly compliant). Every other button in
|
||||
the package goes through `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`), which sets no `padx`/`pady` at all and relies on
|
||||
Tk's built-in default padding — a different, unspecified ratio. Button
|
||||
proportions are therefore inconsistent across dialogs, not a deliberate
|
||||
choice.
|
||||
- **Rule 27 (don't mix depth techniques)** — `UIWidgetsMixin._button()`
|
||||
(`_ui_widgets.py:71-90`) sets no `relief`, so every button in
|
||||
`status_view.py`, `_sick_dialog.py`, `_manual_workout_dialog.py`, and
|
||||
`_manual_workout_widgets.py` uses Tk's default `relief="raised"` (a faux
|
||||
3D bevel). `_heat_skip.py:94,107` explicitly overrides to
|
||||
`relief="flat"` for its two buttons only — one dialog in the app uses a
|
||||
flat depth style while every other dialog uses a raised/beveled one.
|
||||
|
||||
### Not applicable
|
||||
|
||||
- Rule 5 (optical alignment) — no asymmetric icon/shape glyphs requiring
|
||||
eye-adjusted centering; text/emoji labels only.
|
||||
- Rule 6 (letter-spacing/line-height by size) — Tk's `font=` tuple has no
|
||||
letter-spacing or line-height controls; not expressible in this stack.
|
||||
- Rule 7 (border contrast) — no widget in the package sets `borderwidth`
|
||||
or a visible border color (only one incidental `highlightthickness=0` at
|
||||
`_manual_workout_dialog.py:72`, which removes a border, not adds one).
|
||||
- Rule 8 (align with something else) — pack/grid layouts are internally
|
||||
consistent per-dialog; no cross-dialog layout grid to check against.
|
||||
- Rule 12 (order by visual weight) — button rows use uniform-weight buttons
|
||||
(same size/style, only color differs); no weight hierarchy to evaluate.
|
||||
- Rule 13 (12-column grid) — fixed 2-column form grid
|
||||
(`_manual_workout_widgets.py:26-49`) is a bespoke field layout, not a page
|
||||
grid system this rule targets.
|
||||
- Rule 14 (space between contrast edges, not bounding box) — cannot be
|
||||
verified from source without rendering; Tk widgets' effective visual
|
||||
edges vs. bounding boxes aren't determinable statically.
|
||||
- Rule 15 (closer elements lighter) — single flat z-plane throughout; no
|
||||
layered/stacked surfaces.
|
||||
- Rule 16 (shadow blur ≈ 2x offset) — no shadows anywhere in the package.
|
||||
- Rule 17 (simple on complex) — flat solid backgrounds behind all text;
|
||||
trivially compliant, nothing to flag.
|
||||
- Rule 18 (container brightness limits) — the one adjacent pair found,
|
||||
`#1a1a1a` (bg, luma 10.2%) vs. `#2a2a2a` (entry/spinbox fields, luma
|
||||
16.5%), differs by ~6.3 percentage points — within the ~12% dark-mode
|
||||
limit. Pass.
|
||||
- Rule 19 (outer padding ≥ inner padding) — the lock window has no bounded
|
||||
"container" with edge padding (content is `place(relx=0.5, rely=0.5,
|
||||
anchor="center")` on a fullscreen root); the outer/inner relationship this
|
||||
rule assumes doesn't apply to a centered-content-on-fullscreen-canvas
|
||||
layout.
|
||||
- Rule 23 (two typefaces max) — only "Arial" and "monospace"
|
||||
(`_heat_skip.py:17`) appear; 2 total, within the limit (the inconsistency
|
||||
of *where* each is used is captured under Rule 4 above, not this rule).
|
||||
- Rule 24 (nest corners) — no widget sets a corner radius (stock Tk widgets
|
||||
are rectangular); nothing to nest.
|
||||
- Rule 25 (avoid adjacent hard divides) — no borders/dividers used anywhere;
|
||||
nothing to conflict.
|
||||
- Rule 26 (no shadows in dark interfaces) — Pass by omission: no shadows
|
||||
exist in this dark-background UI.
|
||||
- Rule 28 (lower icon contrast next to text) — emoji glyphs (💪, 😷, ✓, ☀,
|
||||
⚠, 🔥) share the same `fg=` color as their surrounding text; Tk offers no
|
||||
per-glyph opacity control within one Label's text, so this can't be
|
||||
addressed without moving emoji into separate, independently-colored
|
||||
widgets.
|
||||
|
||||
### Notes
|
||||
|
||||
- The absence of any shared theme/constants module means every rule above
|
||||
that *did* pass (18, 26) did so incidentally, not by design — there's no
|
||||
guard rail keeping it that way as new dialogs get added.
|
||||
- `_heat_skip.py`'s local `_BG`/`_FG_MAIN`/`_FG_SUB`/`_BTN_SKIP`/`_BTN_NO`/
|
||||
`_FONT` constants are the one place in the package that already knows
|
||||
centralizing tokens is worth doing — promoting this pattern to a shared
|
||||
`screen_locker/_theme.py` (or, better, sourcing from gatelock's
|
||||
`LockConfig`) would fix Rule 4 and cascade-fix several of the violations
|
||||
above in one pass.
|
||||
@ -0,0 +1,464 @@
|
||||
<!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 & 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<void> _tapReal(WidgetTester tester, Finder f) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(f);
|
||||
await Future<void>.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>
|
||||
@ -0,0 +1,686 @@
|
||||
<!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/workout_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>workout_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 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>workout_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 > 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># 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>
|
||||
@ -0,0 +1,672 @@
|
||||
<!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 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 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 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 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 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>
|
||||
|
||||
<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>
|
||||
51
docs/explanations/index.html
Normal file
51
docs/explanations/index.html
Normal file
@ -0,0 +1,51 @@
|
||||
<!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>
|
||||
@ -2,14 +2,6 @@
|
||||
|
||||
## Status
|
||||
|
||||
**Superseded (2026-10-09): screen-locker sync is Firebase RTDB only.** The
|
||||
phone stopped writing the GitHub repo on 2026-08-21, and from 2026-10-09 the
|
||||
PC does not use it either: the push, `sync_client()` and
|
||||
`scripts/tombstone_sync_record.py` all use `firebase_client_for("screen_locker")`,
|
||||
and the sync_token / GitHub client / mirror code paths are deleted.
|
||||
`kuhyx/syncs/screen-locker-sync` stays as a frozen archive that no code reads
|
||||
and nothing deletes. The rest of this document is the historical design record.
|
||||
|
||||
**Blocked on Workstream D** (2026-07-04 user decision — see "Sequencing
|
||||
decision" below). No code has been written for this workstream. The design
|
||||
questions below (sync pattern, repo name, scope) have been pre-decided so the
|
||||
@ -55,7 +47,7 @@ production in this user's other repos — read both before designing this
|
||||
one:
|
||||
|
||||
1. **diet-guard's Contents-API repo sync**
|
||||
(`~/src/diet-guard/diet_guard/_sync.py` + `_sync_github.py` +
|
||||
(`~/diet-guard/diet_guard/_sync.py` + `_sync_github.py` +
|
||||
`_sync_merge.py`, ~120/190/80 lines respectively). `GitHubSyncClient`
|
||||
(`_sync_github.py:38`) wraps the GitHub Contents API with
|
||||
`get_file_text(path)`, `put_file_text(path, text, message=...)`,
|
||||
@ -67,7 +59,7 @@ one:
|
||||
fine-grained PAT read from `~/.config/diet_guard/sync_token` (scoped to
|
||||
just that one repo's contents).
|
||||
2. **wake-alarm's Gist-based sync**
|
||||
(`~/src/wake-alarm/shutdown-wrapper.sh`, phone app writes to a **private
|
||||
(`~/wake-alarm/shutdown-wrapper.sh`, phone app writes to a **private
|
||||
Gist**, not a repo). Config at `~/.config/wake_alarm/gist_sync.json`
|
||||
with `token`/`gist_id`. Much simpler (single JSON blob, no per-device
|
||||
paths, no merge step) — matches wake-alarm's much simpler data shape (one
|
||||
@ -156,7 +148,7 @@ sync code first.
|
||||
- `screen_locker/_constants.py` (`WORKOUT_APP_JSON_REMOTES`,
|
||||
`WORKOUT_HTTP_PORT` — new `SYNC_*` constants go here too)
|
||||
- `stronglift_replacement/workout_app/lib/` (phone-side push, new work)
|
||||
- Reference-only, do not modify: `~/src/diet-guard/diet_guard/_sync_github.py`,
|
||||
`_sync.py`, `_sync_merge.py`; `~/src/wake-alarm/shutdown-wrapper.sh`
|
||||
- Reference-only, do not modify: `~/diet-guard/diet_guard/_sync_github.py`,
|
||||
`_sync.py`, `_sync_merge.py`; `~/wake-alarm/shutdown-wrapper.sh`
|
||||
- **Do not touch**: `screen_locker/_runnerup_verification.py`,
|
||||
`_runnerup_db.py` (hard boundary, see Context above)
|
||||
@ -15,7 +15,7 @@ to have very different shareability:
|
||||
`put_file_text` / `list_directory` against a private repo) is genuinely
|
||||
shared already — it's independently duplicated almost line-for-line
|
||||
between todo's `GitHubClient` and diet-guard's `GitHubSyncClient`
|
||||
(`~/src/diet-guard/diet_guard/_sync_github.py`, 191 lines, `requests`-only).
|
||||
(`~/diet-guard/diet_guard/_sync_github.py`, 191 lines, `requests`-only).
|
||||
Extracting this into a shared Python lib (and a shared Dart lib for
|
||||
todo's/diet-guard's Dart-side client) is low-risk, small, and is the part
|
||||
Workstream C already committed to (Contents-API pattern, not Gist —
|
||||
@ -70,7 +70,7 @@ library too:
|
||||
## 3. Per-app migration cost (revised — the original doc's "todo = smallest
|
||||
lift" assumption does not hold)
|
||||
|
||||
Checked `~/src/todo/lib/data/note_repository.dart`: notes are **mutated in
|
||||
Checked `~/todo/lib/data/note_repository.dart`: notes are **mutated in
|
||||
place** — `upsert()` does `INSERT ... ON CONFLICT DO UPDATE SET text = ?,
|
||||
priority = ?, status = ?, updated_at = ?`, relying on `sqlite_crdt`'s
|
||||
per-column Hybrid-Logical-Clock last-writer-wins to reconcile concurrent
|
||||
@ -138,8 +138,8 @@ off the shelf.
|
||||
|
||||
## Critical files referenced (read-only during this pass)
|
||||
|
||||
- `~/src/todo/lib/sync/sync_service.dart`, `~/src/todo/lib/data/note_repository.dart`
|
||||
- `~/src/diet-guard/diet_guard/_sync.py`, `_sync_github.py`, `_sync_merge.py`
|
||||
- `~/src/diet-guard/app/lib/services/sync_merge.dart`
|
||||
- `~/src/wake-alarm/shutdown-wrapper.sh`
|
||||
- `~/todo/lib/sync/sync_service.dart`, `~/todo/lib/data/note_repository.dart`
|
||||
- `~/diet-guard/diet_guard/_sync.py`, `_sync_github.py`, `_sync_merge.py`
|
||||
- `~/diet-guard/app/lib/services/sync_merge.dart`
|
||||
- `~/wake-alarm/shutdown-wrapper.sh`
|
||||
- `docs/todo/workstream-c-github-sync-workout-data.md` (this repo)
|
||||
@ -8,9 +8,9 @@ fell out of it (both resolved by explicit user call, 2026-07-04).
|
||||
|
||||
**The two shared libraries are now implemented and locally verified
|
||||
(2026-07-05):**
|
||||
- `~/src/utils/crdt-sync` (Python) — 60 tests, 100% branch coverage, clean
|
||||
- `~/crdt-sync` (Python) — 60 tests, 100% branch coverage, clean
|
||||
ruff/mypy/pylint/bandit/pre-commit. Local git repo, one commit.
|
||||
- `~/src/utils/crdt_sync_dart` (pure Dart, no Flutter dep) — 59 tests, clean
|
||||
- `~/crdt_sync_dart` (pure Dart, no Flutter dep) — 59 tests, clean
|
||||
`dart analyze`. Local git repo, one commit.
|
||||
|
||||
Both implement the unified LWW-map-with-sticky-remove scheme (`Hlc`,
|
||||
@ -62,7 +62,7 @@ from-scratch CRDT implementation.
|
||||
|
||||
**diet-guard and wake-alarm do NOT use CRDTs today.** Their existing
|
||||
"merge" mechanisms are much simpler:
|
||||
- diet-guard: `_sync_merge.merge_logs` (`~/src/diet-guard/diet_guard/_sync_merge.py`,
|
||||
- diet-guard: `_sync_merge.merge_logs` (`~/diet-guard/diet_guard/_sync_merge.py`,
|
||||
81 lines) is a tombstone-aware, entry-key-based merge — closer to
|
||||
last-write-wins per entry than a general CRDT. Transport is
|
||||
`_sync_github.GitHubSyncClient` against a private repo's Contents API
|
||||
@ -151,9 +151,9 @@ time this is scoped for real.
|
||||
|
||||
## Critical files (reference only — read, do not modify, during scoping)
|
||||
|
||||
- `~/src/todo/lib/sync/sync_service.dart`, `sync_settings.dart` (CRDT-via-package pattern)
|
||||
- `~/src/diet-guard/diet_guard/_sync.py`, `_sync_github.py`, `_sync_merge.py`
|
||||
- `~/src/diet-guard/app/lib/services/sync_service.dart`, `sync_merge.dart`
|
||||
- `~/src/wake-alarm/shutdown-wrapper.sh`
|
||||
- `~/todo/lib/sync/sync_service.dart`, `sync_settings.dart` (CRDT-via-package pattern)
|
||||
- `~/diet-guard/diet_guard/_sync.py`, `_sync_github.py`, `_sync_merge.py`
|
||||
- `~/diet-guard/app/lib/services/sync_service.dart`, `sync_merge.dart`
|
||||
- `~/wake-alarm/shutdown-wrapper.sh`
|
||||
- `docs/todo/workstream-c-github-sync-workout-data.md` (this repo — resolve
|
||||
its open questions jointly with this one, not independently)
|
||||
@ -1,28 +1,15 @@
|
||||
[Unit]
|
||||
Description=Re-check workout after early bird grace period expires (08:30 normal, 09:05 extended)
|
||||
# NO After=graphical-session.target here. This timer is WantedBy=timers.target,
|
||||
# and timers.target is ordered before basic.target before
|
||||
# graphical-session.target -- so that After= closes a dependency cycle.
|
||||
# systemd resolves such a cycle by DELETING this timer's job, which is exactly
|
||||
# what happened on 2026-08-04 ("Job early-bird-workout-check.timer/start deleted
|
||||
# to break ordering cycle"). The timer went disabled and the locker silently
|
||||
# stopped enforcing for days. The service it triggers keeps its own
|
||||
# After=graphical-session.target, which is where that ordering belongs.
|
||||
After=graphical-session.target
|
||||
|
||||
[Timer]
|
||||
# The early-bird window is the wake-alarm morning-session carrot since
|
||||
# 2026-09-20 (screen_locker/_early_bird.py): it ends at the signed
|
||||
# exempt_until -- 11:00 after a completed morning, min(start+90 min, 09:30)
|
||||
# after an aborted one, alarm+15 min when no session started. These runs land
|
||||
# just after the two boundaries the 5-minute tick could miss by up to five
|
||||
# minutes; every run is idempotent ("already logged", "carrot still in force").
|
||||
OnCalendar=*-*-* 09:30:30
|
||||
OnCalendar=*-*-* 11:00:30
|
||||
# Fires at 08:30 for the normal early-bird window (5:00–8:30).
|
||||
# Also fires at 09:05 to catch the extended window (5:00–9:00) earned by 5+ workout weeks.
|
||||
# Both runs are idempotent: the service handles "already logged" and "window still active".
|
||||
OnCalendar=*-*-* 08:30:00
|
||||
OnCalendar=*-*-* 09:05:00
|
||||
Unit=workout-locker.service
|
||||
# Persistent=true: a machine asleep or off at a boundary would otherwise skip
|
||||
# the re-check entirely, leaving the early-bird marker banked and the day
|
||||
# unenforced. Both runs are idempotent (see above), so a catch-up run is safe.
|
||||
Persistent=true
|
||||
Persistent=false
|
||||
AccuracySec=1s
|
||||
RandomizedDelaySec=0
|
||||
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
[Unit]
|
||||
Description=Apply newly earned flat shutdown bonuses (LeetCode, reading, Anki, ...)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
# Started by earner-bonus.path the moment a gate writes its ledger. Only the
|
||||
# flat-bonus pass: no phone sync, no Tk, no lock screen, so a solve moves the
|
||||
# shutdown time within seconds instead of at the next 15-minute workout-sync.
|
||||
# The path unit itself is generated from the earned_time registry
|
||||
# (screen_locker._earner_units), so it is not a file in this repo.
|
||||
ExecStart=/usr/bin/python3 -m screen_locker.screen_lock --apply-bonuses
|
||||
@ -1,14 +0,0 @@
|
||||
[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
|
||||
@ -1,14 +0,0 @@
|
||||
[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
|
||||
24
install.sh
24
install.sh
@ -42,7 +42,7 @@ readonly REPO_DIR="$SCRIPT_DIR"
|
||||
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
|
||||
readonly PROD_PYTHON="/usr/bin/python3"
|
||||
# The shared lock backend, developed in lockstep with this repo.
|
||||
readonly GATELOCK_DIR="$HOME/src/utils/gatelock"
|
||||
readonly GATELOCK_DIR="$HOME/utils/gatelock"
|
||||
|
||||
echo "=== Screen Locker Installer ==="
|
||||
|
||||
@ -58,7 +58,7 @@ fi
|
||||
# 2. Install the package ------------------------------------------------------
|
||||
# --break-system-packages is required on Arch (PEP 668). Editable so a later
|
||||
# `git pull` in THIS clone updates the running service with no reinstall. That
|
||||
# is also why the clone must live somewhere durable (~/src/screen-locker), never a
|
||||
# is also why the clone must live somewhere durable (~/screen-locker), never a
|
||||
# scratch directory: a non-editable snapshot would freeze at this commit and
|
||||
# silently stop tracking the repo.
|
||||
echo "[2/4] Installing screen_locker into user site-packages (editable)..."
|
||||
@ -69,7 +69,7 @@ echo "[2/4] Installing screen_locker into user site-packages (editable)..."
|
||||
# pyproject.toml pins `gatelock @ git+https://.../@gatelock-v0.2.1`, so the
|
||||
# install above resolves that pin and overwrites any local editable gatelock
|
||||
# with a frozen wheel built from the tag. That silently reverts every
|
||||
# unreleased change in ~/src/utils/gatelock and breaks the other lockers that
|
||||
# unreleased change in ~/utils/gatelock and breaks the other lockers that
|
||||
# depend on them -- observed: it removed `ScrollableSurface` and took
|
||||
# diet_guard down with it.
|
||||
#
|
||||
@ -87,12 +87,6 @@ else
|
||||
fi
|
||||
|
||||
# 3. systemd units ------------------------------------------------------------
|
||||
# This step installs *and enables* every unit in the repo, which would clobber
|
||||
# the systemd mask symlinks. Respect the disarm marker; ./arm.sh --rearm undoes.
|
||||
# shellcheck source=scripts/disarm_guard.sh
|
||||
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
|
||||
refuse_if_disarmed
|
||||
|
||||
echo "[3/4] Installing systemd user units..."
|
||||
mkdir -p "$SYSTEMD_USER_DIR"
|
||||
shopt -s nullglob
|
||||
@ -122,7 +116,7 @@ if ! (cd /tmp && "$PROD_PYTHON" -c "import screen_locker" 2>/dev/null); then
|
||||
fi
|
||||
if ! (cd /tmp && "$PROD_PYTHON" -c "import gatelock" 2>/dev/null); then
|
||||
echo "ERROR: $PROD_PYTHON cannot import gatelock (the shared lock" >&2
|
||||
echo " backend). Install it editable from ~/src/utils/gatelock." >&2
|
||||
echo " backend). Install it editable from ~/utils/gatelock." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -d "$GATELOCK_DIR" ]]; then
|
||||
@ -138,16 +132,6 @@ if [[ -d "$GATELOCK_DIR" ]]; then
|
||||
fi
|
||||
echo " ok: screen_locker and gatelock both import under $PROD_PYTHON"
|
||||
|
||||
# One-shot, idempotent: the old sick_history.json's dates move into the shared
|
||||
# sickdays pool and the file is removed once they read back. Rerunning (or a
|
||||
# machine that never had the file) is a no-op. A failure keeps the file and
|
||||
# is retried by the next install; it does not block the locker itself.
|
||||
echo "Migrating the legacy sick history into the sickdays pool..."
|
||||
if ! "$PROD_PYTHON" "$REPO_DIR/scripts/migrate_sick_history.py"; then
|
||||
echo " WARNING: sick-history migration failed (file kept); rerun" >&2
|
||||
echo " $REPO_DIR/scripts/migrate_sick_history.py" >&2
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== Done ==="
|
||||
echo "The locker is live. Check when it next fires with:"
|
||||
|
||||
@ -4,89 +4,9 @@
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
SERVICE_FILE="$SCRIPT_DIR/workout-locker.service"
|
||||
EARLY_BIRD_TIMER_FILE="$SCRIPT_DIR/early-bird-workout-check.timer"
|
||||
LOCKER_TIMER_FILE="$SCRIPT_DIR/workout-locker.timer"
|
||||
SYNC_SERVICE_FILE="$SCRIPT_DIR/workout-sync.service"
|
||||
SYNC_TIMER_FILE="$SCRIPT_DIR/workout-sync.timer"
|
||||
USER_SERVICE_DIR="$HOME/.config/systemd/user"
|
||||
SERVICE_NAME="workout-locker.service"
|
||||
EARLY_BIRD_TIMER_NAME="early-bird-workout-check.timer"
|
||||
LOCKER_TIMER_NAME="workout-locker.timer"
|
||||
SYNC_SERVICE_NAME="workout-sync.service"
|
||||
SYNC_TIMER_NAME="workout-sync.timer"
|
||||
BONUS_SERVICE_NAME="earner-bonus.service"
|
||||
BONUS_PATH_NAME="earner-bonus.path"
|
||||
RUNNERUP_WATCH_NAME="runnerup-watch.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
|
||||
# the tkinter MODULE ships inside the `python` package, but the shared library
|
||||
# it dlopens does not: without `tk` the import dies with
|
||||
# "ImportError: libtk8.6.so: cannot open shared object file" and this installer
|
||||
# exits 1. That is exactly how a fresh Arch box behaves, since `tk` is only an
|
||||
# optional dependency of python. Install it rather than documenting it: a fresh
|
||||
# install must not require the user to know this.
|
||||
ensure_runtime_deps() {
|
||||
if ! python3 -c 'import tkinter' 2>/dev/null; then
|
||||
if command -v pacman >/dev/null 2>&1; then
|
||||
echo "Installing missing system dependency: tk"
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
pacman -S --needed --noconfirm tk
|
||||
else
|
||||
sudo pacman -S --needed --noconfirm tk
|
||||
fi
|
||||
else
|
||||
echo "WARNING: tkinter missing and pacman unavailable - install tk manually" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
# inotifywait drives runnerup-watch.service (instant RunnerUp credit).
|
||||
if ! command -v inotifywait >/dev/null 2>&1; then
|
||||
if command -v pacman >/dev/null 2>&1; then
|
||||
echo "Installing missing system dependency: inotify-tools"
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
pacman -S --needed --noconfirm inotify-tools
|
||||
else
|
||||
sudo pacman -S --needed --noconfirm inotify-tools
|
||||
fi
|
||||
else
|
||||
echo "WARNING: inotifywait missing and pacman unavailable - RunnerUp runs are credited only by the 15-min timer" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
# The two shared RUNTIME dependencies, both pinned git deps in
|
||||
# pyproject.toml: gatelock (lock-window/HMAC backend) and crdt-sync (the
|
||||
# workout-sync transport). Nothing here used to install either, so a fresh
|
||||
# checkout died with "ModuleNotFoundError: No module named 'gatelock'" the
|
||||
# first time the post-install workout check ran, and with crdt_sync right
|
||||
# after that. requirements.txt is NOT used here on purpose: it also pins the
|
||||
# dev toolchain (pytest, mypy, ruff...), which a fresh install does not need.
|
||||
#
|
||||
# Arch marks its system Python externally-managed, so a plain `pip install`
|
||||
# refuses; --break-system-packages is what the sibling installers already use.
|
||||
_pip_runtime_dep() { # <import-name> <pip-spec>
|
||||
python3 -c "import $1" 2>/dev/null && return 0
|
||||
echo "Installing missing Python dependency: $1"
|
||||
pip3 install --user --quiet "$2" 2>/dev/null ||
|
||||
pip3 install --user --break-system-packages --quiet "$2" ||
|
||||
echo "WARNING: could not install $1 automatically" >&2
|
||||
}
|
||||
_pip_runtime_dep gatelock \
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.10.0#subdirectory=gatelock"
|
||||
_pip_runtime_dep 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
|
||||
|
||||
# shellcheck source=scripts/disarm_guard.sh
|
||||
source "$SCRIPT_DIR/scripts/disarm_guard.sh"
|
||||
# Installing units here would overwrite the systemd mask symlinks, so this
|
||||
# path has to respect the disarm marker too. Re-arm via: ./arm.sh --rearm
|
||||
refuse_if_disarmed
|
||||
|
||||
# Check if service is already installed
|
||||
if [ -f "$USER_SERVICE_DIR/$SERVICE_NAME" ]; then
|
||||
@ -111,12 +31,11 @@ if systemctl --user is-active "workout-locker.timer" &>/dev/null; then
|
||||
fi
|
||||
rm -f "$USER_SERVICE_DIR/workout-locker.timer"
|
||||
|
||||
# Seed shutdown_base.json if not already present. It holds only date stamps;
|
||||
# the base hour itself comes from the earned_time registry (kuhyx/utils).
|
||||
# Seed shutdown_base.json with base=21 if not already present
|
||||
SHUTDOWN_BASE="$SCRIPT_DIR/screen_locker/shutdown_base.json"
|
||||
if [[ ! -f "$SHUTDOWN_BASE" ]]; then
|
||||
printf '{\n "last_reset_date": ""\n}\n' > "$SHUTDOWN_BASE"
|
||||
echo "✓ Created shutdown_base.json"
|
||||
printf '{\n "base_mon_wed_hour": 21,\n "base_thu_sun_hour": 21,\n "last_reset_date": ""\n}\n' > "$SHUTDOWN_BASE"
|
||||
echo "✓ Created shutdown_base.json with base=21:00"
|
||||
fi
|
||||
|
||||
# Copy service file to user systemd directory
|
||||
@ -125,39 +44,6 @@ cp "$SERVICE_FILE" "$USER_SERVICE_DIR/$SERVICE_NAME"
|
||||
# Copy early bird timer
|
||||
cp "$EARLY_BIRD_TIMER_FILE" "$USER_SERVICE_DIR/$EARLY_BIRD_TIMER_NAME"
|
||||
|
||||
# Copy the periodic re-check timer. Without it the locker only ever decides at
|
||||
# login and at 08:30/09:05, so a day or ISO-week boundary crossed inside a long
|
||||
# session is never re-evaluated.
|
||||
cp "$LOCKER_TIMER_FILE" "$USER_SERVICE_DIR/$LOCKER_TIMER_NAME"
|
||||
|
||||
# Copy the periodic workout-sync units. Without these, syncing happens only
|
||||
# once per locker start, so a workout finished after login is not seen until
|
||||
# the next login.
|
||||
cp "$SYNC_SERVICE_FILE" "$USER_SERVICE_DIR/$SYNC_SERVICE_NAME"
|
||||
cp "$SYNC_TIMER_FILE" "$USER_SERVICE_DIR/$SYNC_TIMER_NAME"
|
||||
|
||||
# The ledger watch: a gate writing its ledger applies the earned shutdown
|
||||
# bonus at once instead of at the next 15-minute sync. The .path unit is
|
||||
# rendered from the earned_time registry, so it is generated, not copied.
|
||||
cp "$SCRIPT_DIR/$BONUS_SERVICE_NAME" "$USER_SERVICE_DIR/$BONUS_SERVICE_NAME"
|
||||
PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker._earner_units "$USER_SERVICE_DIR"
|
||||
|
||||
# The RunnerUp upload watch: a TCX landing in ~/data/cloud/RunnerUp starts
|
||||
# workout-sync at once instead of waiting for the next timer tick.
|
||||
cp "$SCRIPT_DIR/$RUNNERUP_WATCH_NAME" "$USER_SERVICE_DIR/$RUNNERUP_WATCH_NAME"
|
||||
|
||||
# The phone's LAN poke: a finished StrongLifts session is credited within a
|
||||
# second instead of at the next sync. The key must exist before the unit
|
||||
# starts, or it refuses to (docs/DOCS-workout-poke-contract.md).
|
||||
bash "$SCRIPT_DIR/scripts/workout_poke_keygen.sh"
|
||||
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
|
||||
REPO_ROOT="$SCRIPT_DIR"
|
||||
sed -i "s|WorkingDirectory=.*|WorkingDirectory=$REPO_ROOT|" "$USER_SERVICE_DIR/$SERVICE_NAME"
|
||||
@ -170,29 +56,11 @@ systemctl --user daemon-reload
|
||||
# Enable the service to start on login (one-shot, no periodic timer)
|
||||
systemctl --user enable "$SERVICE_NAME"
|
||||
|
||||
# Timers: early bird re-check, periodic re-check, workout sync, the instant
|
||||
# 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"
|
||||
|
||||
# Instant RunnerUp credit on upload, and the LAN workout poke listener
|
||||
# (restart picks up new code)
|
||||
for unit in "$RUNNERUP_WATCH_NAME" "$WORKOUT_POKE_NAME"; do
|
||||
systemctl --user enable "$unit"
|
||||
systemctl --user restart "$unit"
|
||||
done
|
||||
|
||||
# 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
|
||||
# on 2026-08-04 -- so a successful `enable` is NOT proof the locker will run.
|
||||
if ! python3 "$SCRIPT_DIR/scripts/check_enforcement_armed.py"; then
|
||||
echo "✗ Enforcement is NOT armed after install — see the errors above" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Enable the early bird re-check timer
|
||||
systemctl --user enable --now "$EARLY_BIRD_TIMER_NAME"
|
||||
|
||||
echo "✓ Workout locker service installed"
|
||||
echo "✓ Early bird re-check timer installed (fires daily at 08:30)"
|
||||
echo "✓ Periodic re-check timer installed (every 30 min)"
|
||||
echo "✓ Service will start automatically on next login"
|
||||
echo ""
|
||||
echo "To start now: systemctl --user start workout-locker"
|
||||
@ -213,11 +81,6 @@ if systemctl --user is-enabled "$EARLY_BIRD_TIMER_NAME" &>/dev/null; then
|
||||
else
|
||||
echo "✗ early bird timer: NOT enabled"
|
||||
fi
|
||||
if systemctl --user is-enabled "$SYNC_TIMER_NAME" &>/dev/null; then
|
||||
echo "✓ workout sync timer: INSTALLED and enabled (every 15 min)"
|
||||
else
|
||||
echo "✗ workout sync timer: NOT enabled"
|
||||
fi
|
||||
|
||||
I3_CONFIG="$HOME/.config/i3/config"
|
||||
if [ -f "$I3_CONFIG" ] && grep -q "exec.*screen_lock.py" "$I3_CONFIG"; then
|
||||
@ -229,21 +92,7 @@ else
|
||||
echo " exec --no-startup-id /usr/bin/python3 -m screen_locker.screen_lock --production"
|
||||
fi
|
||||
|
||||
# Immediately check if today's workout is done; block if not.
|
||||
#
|
||||
# --production builds the real Tk UI and, when today is non-compliant, GRABS
|
||||
# THE SCREEN and waits for a workout to be logged. That is correct for an
|
||||
# interactive install, but it never returns on its own -- so when this script
|
||||
# is driven non-interactively (install_core_system.sh, CI, `vm run`) the whole
|
||||
# installer hangs forever on its last line. Only take the blocking path when
|
||||
# there is a terminal to answer it; otherwise report status and exit.
|
||||
# SCREEN_LOCKER_ENFORCE_AFTER_INSTALL=1 forces the blocking check.
|
||||
# Immediately check if today's workout is done; block if not
|
||||
echo ""
|
||||
echo "=== Checking today's workout status ==="
|
||||
if [ -t 0 ] || [ "${SCREEN_LOCKER_ENFORCE_AFTER_INSTALL:-0}" = "1" ]; then
|
||||
PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker.screen_lock --production
|
||||
else
|
||||
echo "(non-interactive install: reporting status instead of enforcing)"
|
||||
PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker.screen_lock --status || true
|
||||
echo "Enforcement is armed via the systemd units installed above."
|
||||
fi
|
||||
PYTHONPATH="$SCRIPT_DIR" python3 -m screen_locker.screen_lock --production
|
||||
|
||||
@ -1,24 +1,18 @@
|
||||
[project]
|
||||
name = "screen-locker"
|
||||
version = "1.0.0"
|
||||
description = "Tkinter/systemd screen locker with workout tracking, shared sick days, and wake-alarm integration"
|
||||
requires-python = ">=3.14"
|
||||
description = "Tkinter/systemd screen locker with workout tracking, sick-day management, and wake-alarm integration"
|
||||
requires-python = ">=3.10"
|
||||
# gatelock: shared lock-window/HMAC backend, also used by diet_guard and wake_alarm
|
||||
# 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
|
||||
# crdt-sync: shared CRDT merge scheme + GitHub-Contents-API sync transport,
|
||||
# also used by diet_guard; here for phone-workout GitHub sync (Workstream C)
|
||||
dependencies = [
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock",
|
||||
"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.4#subdirectory=freedays",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time",
|
||||
"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",
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock",
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.3.0#subdirectory=crdt-sync",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
screen-locker-status = "screen_locker.status_view:main"
|
||||
screen-locker-web = "screen_locker._web_server:main"
|
||||
|
||||
# Optional extras. The `mcp` group is ONLY needed by the read-only MCP server
|
||||
# (screen_locker._mcp), which Claude Code spawns via a dedicated venv (see
|
||||
@ -26,7 +20,7 @@ screen-locker-web = "screen_locker._web_server:main"
|
||||
# so the systemd/CLI system-python path stays dependency-light and never has
|
||||
# to import the MCP SDK.
|
||||
[project.optional-dependencies]
|
||||
mcp = ["mcp==2.3.0"]
|
||||
mcp = ["mcp>=2,<3"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
# This repo also holds stronglift_replacement/ (an unrelated Flutter app, not
|
||||
@ -36,7 +30,7 @@ mcp = ["mcp==2.3.0"]
|
||||
include = ["screen_locker*"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py314"
|
||||
target-version = "py310"
|
||||
include = ["*.py", "**/*.py"]
|
||||
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs"]
|
||||
|
||||
@ -46,9 +40,6 @@ ignore = [
|
||||
"D203",
|
||||
"D213",
|
||||
"COM812",
|
||||
# Personal repo, no copyright policy (ruff 0.17 made CPY001 stable under
|
||||
# select=ALL).
|
||||
"CPY001",
|
||||
"ISC001",
|
||||
"S603",
|
||||
]
|
||||
@ -64,10 +55,7 @@ unfixable = []
|
||||
"ANN", "ARG", "D", "DTZ011", "E501", "FBT",
|
||||
"PLC0415", "PLR0913", "PLR2004", "PTH", "RUF003", "S101", "SLF001",
|
||||
]
|
||||
# The ET.parse call this covers moved to _runnerup_tcx.py when
|
||||
# _runnerup_verification.py was split for the 250-line cap. Same waiver, new
|
||||
# home -- the TCX files are pulled off the user's own phone by adb.
|
||||
"screen_locker/_runnerup_tcx.py" = ["S314"]
|
||||
"screen_locker/_runnerup_verification.py" = ["S314"]
|
||||
# URL is always built from the hardcoded https:// _WTTR_URL constant with
|
||||
# only the (quoted) city interpolated — never user/attacker controlled.
|
||||
# ruff's S310 can't verify that via static analysis of a variable URL, so
|
||||
@ -99,7 +87,7 @@ unfixable = []
|
||||
# -truth reuse status_view.py above is exempted for — and _make_bare_verifier
|
||||
# imports ScreenLocker inside the function to avoid an import cycle.
|
||||
"screen_locker/_status_view_verify.py" = ["PLC0415", "SLF001"]
|
||||
# explain_lock_decision takes one arg per real file path and input, and
|
||||
# explain_lock_decision takes one arg per real file path + sick history, and
|
||||
# returns early per lock-decision-chain stage (see module docstring) — both
|
||||
# are the deliberate design, not something to collapse into a config object.
|
||||
"screen_locker/_compliance_state.py" = ["C901", "PLR0911", "PLR0913"]
|
||||
@ -139,7 +127,7 @@ line-ending = "auto"
|
||||
docstring-code-format = true
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.14"
|
||||
python_version = "3.10"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
@ -172,13 +160,8 @@ exclude = [".venv/"]
|
||||
init-hook = "import sys; sys.path.insert(0, '.')"
|
||||
analyse-fallback-blocks = true
|
||||
persistent = true
|
||||
# Serial on purpose. With jobs != 1 pylint ships the linter to its workers via
|
||||
# dill.dumps(), and dill 0.4.1 (newest release) reads code.co_lnotab, which
|
||||
# CPython 3.15 removed -- every run crashed once setup-python's "3.x" became
|
||||
# 3.15.1. The fix sits on dill master, unreleased; return to 0 once a dill
|
||||
# release past 0.4.1 ships. The pre-commit hooks take this value too.
|
||||
jobs = 1
|
||||
py-version = "3.14"
|
||||
jobs = 0
|
||||
py-version = "3.10"
|
||||
ignore = [".venv", "__pycache__"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
|
||||
@ -189,42 +172,7 @@ disable = []
|
||||
[tool.pylint.design]
|
||||
min-public-methods = 0
|
||||
max-module-lines = 1000
|
||||
# ScreenLocker composes ~30 mixins; collapsing them is not the goal.
|
||||
max-parents = 40
|
||||
# Keyword-only arguments count: the gather_*/explain_* entry points take one
|
||||
# per real file path so tests can override each.
|
||||
max-args = 8
|
||||
# ManualWorkoutDraft is a flat 23-field record mirroring the evidence form and
|
||||
# the wire payload; StatusWindow / ScreenLocker hold UI and injected state.
|
||||
max-attributes = 25
|
||||
|
||||
[tool.pylint.similarities]
|
||||
# The remaining overlaps are 6-11 line fragments of deliberately parallel code
|
||||
# (Tk button rows, the two JSON ledgers' loaders, mixin host stubs); a real
|
||||
# copy-paste block is longer than this.
|
||||
min-similarity-lines = 12
|
||||
|
||||
[tool.pylint.format]
|
||||
# BaseHTTPRequestHandler dispatches on the method names do_GET / do_POST.
|
||||
good-names-rgxs = "^do_(GET|POST)$"
|
||||
|
||||
[tool.pylint.classes]
|
||||
# The mixin-host surface: module-level helpers (shutdown_base, status, the
|
||||
# status window's verify flow) drive the ScreenLocker's own mixin methods, the
|
||||
# same single-source-of-truth reuse ruff exempts via per-file SLF001.
|
||||
exclude-protected = [
|
||||
"_asdict", "_fields", "_replace", "_source", "_make", "os._exit",
|
||||
"_adjust_shutdown_time_by",
|
||||
"_apply_sick_floor",
|
||||
"_apply_workout_credit",
|
||||
"_credit_ingested_workout",
|
||||
"_read_shutdown_config",
|
||||
"_scan_and_fill_week_runnerup",
|
||||
"_try_fill_stronglifts_for_week",
|
||||
"_verify_phone_workout",
|
||||
"_verify_runnerup_workout",
|
||||
"_write_shutdown_config",
|
||||
]
|
||||
max-attributes = 10
|
||||
|
||||
[tool.pylint.typecheck]
|
||||
generated-members = [
|
||||
@ -255,21 +203,10 @@ addopts = [
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=lcov",
|
||||
# The commit gate runs plain `python -m pytest -q`; serial it took 26 s of
|
||||
# its 60 s budget, 4 workers 9 s. Fixed, not `auto`: auto is 24 workers
|
||||
# here, past capped.sh's 4 GiB. CI's own `-n auto` comes later and wins;
|
||||
# `-n0` gets a serial run back.
|
||||
"-n",
|
||||
"4",
|
||||
"--dist",
|
||||
"worksteal",
|
||||
# A fixture-only plugin module, not conftest.py (already at the
|
||||
# repo's 400-line-per-file cap) -- see its own docstring.
|
||||
"-p",
|
||||
"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 = [
|
||||
"error",
|
||||
@ -280,9 +217,6 @@ filterwarnings = [
|
||||
[tool.coverage.run]
|
||||
source = ["screen_locker"]
|
||||
branch = true
|
||||
# sys.monitoring (PEP 669) rather than the C tracer: test_shutdown_ceiling_
|
||||
# invariant.py alone measured 13 s vs 22 s, for the same line+branch data.
|
||||
core = "sysmon"
|
||||
omit = [
|
||||
"*/__pycache__/*",
|
||||
"*/tests/*",
|
||||
|
||||
@ -5,29 +5,19 @@ SERVICE_NAME="workout-locker.service"
|
||||
TIMER_NAME="workout-locker.timer"
|
||||
USER_SERVICE_DIR="$HOME/.config/systemd/user"
|
||||
|
||||
# Every unit install_systemd.sh creates. Removal has to enumerate all of them,
|
||||
# or a "removed" locker keeps firing from a timer nobody remembers installing.
|
||||
UNITS=(
|
||||
"$SERVICE_NAME"
|
||||
"$TIMER_NAME"
|
||||
"early-bird-workout-check.timer"
|
||||
"workout-sync.timer"
|
||||
"workout-sync.service"
|
||||
"earner-bonus.path"
|
||||
"earner-bonus.service"
|
||||
"runnerup-watch.service"
|
||||
"workout-poke.service"
|
||||
"runnerup-retire.timer"
|
||||
"runnerup-retire.service"
|
||||
)
|
||||
# Stop the service and timer if running
|
||||
systemctl --user stop "$TIMER_NAME" 2>/dev/null
|
||||
systemctl --user stop "$SERVICE_NAME" 2>/dev/null
|
||||
|
||||
for unit in "${UNITS[@]}"; do
|
||||
systemctl --user stop "$unit" 2>/dev/null
|
||||
systemctl --user disable "$unit" 2>/dev/null
|
||||
rm -f "$USER_SERVICE_DIR/$unit"
|
||||
done
|
||||
# Disable the service and timer
|
||||
systemctl --user disable "$TIMER_NAME" 2>/dev/null
|
||||
systemctl --user disable "$SERVICE_NAME" 2>/dev/null
|
||||
|
||||
# Remove service and timer files
|
||||
rm -f "$USER_SERVICE_DIR/$SERVICE_NAME"
|
||||
rm -f "$USER_SERVICE_DIR/$TIMER_NAME"
|
||||
|
||||
# Reload systemd daemon
|
||||
systemctl --user daemon-reload
|
||||
|
||||
echo "✓ Workout locker services and timers removed"
|
||||
echo "✓ Workout locker service and timer removed"
|
||||
|
||||
@ -1,31 +1,17 @@
|
||||
# Screen Locker — runtime + development dependencies
|
||||
# Runtime: tkinter/subprocess/socket/sqlite3 (stdlib) plus gatelock (below).
|
||||
bandit==1.9.4
|
||||
codespell==2.4.3
|
||||
coverage==7.17.4
|
||||
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.24.0#subdirectory=earned_time
|
||||
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
|
||||
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
|
||||
mypy==2.4.1
|
||||
pre-commit==4.7.0
|
||||
pylint==4.1.4
|
||||
pytest==9.2.0
|
||||
pytest-cov==7.1.0
|
||||
pytest-randomly==5.1.0
|
||||
pytest-sugar==1.1.1
|
||||
pytest-xdist==3.8.0
|
||||
# Direct dependency since the Firebase session recovery exchanges a refresh
|
||||
# token over the REST endpoint; crdt-sync already pulls requests in, but this
|
||||
# module imports it itself, so it is declared rather than assumed.
|
||||
requests==2.34.2
|
||||
ruff==0.17.6
|
||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
|
||||
types-requests==2.33.0.20261030
|
||||
# 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
|
||||
# the module imports it itself, so it is declared rather than assumed.
|
||||
urllib3==2.8.0
|
||||
bandit>=1.7.0
|
||||
codespell>=2.2.0
|
||||
coverage>=7.4.0
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.3.0#subdirectory=crdt-sync
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||
mcp>=2,<3
|
||||
mypy>=1.8.0
|
||||
pre-commit>=3.6.0
|
||||
pylint>=3.0.0
|
||||
pytest>=8.0.0
|
||||
pytest-cov>=4.1.0
|
||||
pytest-randomly>=3.15.0
|
||||
pytest-sugar>=1.0.0
|
||||
pytest-xdist>=3.5.0
|
||||
ruff>=0.8.0
|
||||
|
||||
36
run.sh
36
run.sh
@ -1,40 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
set -e
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
VENV="$SCRIPT_DIR/.venv"
|
||||
[[ ! -d "$VENV" ]] && python3 -m venv "$VENV"
|
||||
# tkinter is from Python stdlib; install python-tk system package if missing:
|
||||
# Arch: sudo pacman -S python-tk
|
||||
# Debian: sudo apt-get install python3-tk
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
if [[ ! -d "$VENV" ]]; then
|
||||
python3 -m venv "$VENV"
|
||||
fi
|
||||
|
||||
# Reconcile the venv against requirements.txt whenever that file changes.
|
||||
# Without this the venv is created once and never updated, so a dependency pin
|
||||
# bump stays invisible until it surfaces as an ImportError at startup --
|
||||
# crdt-sync sat at 0.6.0 for months after the pin moved to 0.9.0.
|
||||
#
|
||||
# Gated on a hash stamp so the common case costs nothing: pip re-resolves the
|
||||
# git-pinned deps over the network (~5s) on every call, and this is a screen
|
||||
# locker that must still start when the network is down.
|
||||
STAMP="$VENV/.requirements.sha256"
|
||||
WANT="$(sha256sum requirements.txt | cut -d" " -f1)"
|
||||
HAVE="$(cat "$STAMP" 2>/dev/null || true)"
|
||||
|
||||
if [[ "$WANT" != "$HAVE" ]]; then
|
||||
echo "Dependencies changed; reconciling venv against requirements.txt..." >&2
|
||||
if "$VENV/bin/pip" install -q -r requirements.txt; then
|
||||
printf '%s\n' "$WANT" > "$STAMP"
|
||||
else
|
||||
# Do not stamp on failure, so the next launch retries. Abort rather
|
||||
# than run on dependencies we know are wrong.
|
||||
echo "ERROR: failed to install dependencies from requirements.txt" >&2
|
||||
echo " Refusing to launch with unreconciled dependencies." >&2
|
||||
echo " Retry manually: $VENV/bin/pip install -r requirements.txt" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$VENV/bin/python" -m screen_locker.screen_lock "$@"
|
||||
"$VENV/bin/python" -m screen_locker.screen_lock "$@"
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
[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
|
||||
@ -1,18 +0,0 @@
|
||||
[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
|
||||
@ -1,13 +0,0 @@
|
||||
[Unit]
|
||||
Description=Credit a RunnerUp run the moment its TCX upload lands (starts workout-sync)
|
||||
|
||||
[Service]
|
||||
# Long-running inotify watcher on ~/data/cloud/RunnerUp: idle until dufs
|
||||
# finishes writing a *.tcx, then starts workout-sync.service. See the script
|
||||
# header for why this is not a .path unit.
|
||||
ExecStart=%h/src/screen-locker/scripts/runnerup_watch.sh
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@ -1,19 +0,0 @@
|
||||
[Unit]
|
||||
Description=Screen Locker status web UI (localhost only)
|
||||
# No After=graphical-session.target: this serves HTTP and reads state files, it
|
||||
# never touches the display. Ordering it after the graphical session would also
|
||||
# stop it starting on a headless boot, which is exactly when you most want to
|
||||
# be able to ask whether enforcement is armed.
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/python3 -m screen_locker._web_server
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
# steam-backlog-enforcer asks this server whether today has a workout before
|
||||
# deciding the gaming budget, and fails CLOSED to the smaller budget when the
|
||||
# answer does not arrive. So a crash costs gaming time rather than silently
|
||||
# handing it back -- but it should still come straight back up.
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@ -1,140 +0,0 @@
|
||||
"""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,
|
||||
)
|
||||
@ -1,137 +0,0 @@
|
||||
"""ADB transport for phone verification: connect, reconnect, run commands.
|
||||
|
||||
Split out of :mod:`screen_locker._phone_verification` to keep every file under
|
||||
the 250-line cap. Composed back into ``PhoneVerificationMixin`` there, so
|
||||
callers see no change.
|
||||
|
||||
Everything here is plumbing: reaching the phone and running a command on it.
|
||||
Deciding whether what came back counts as a workout stays in
|
||||
``_phone_verification``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import (
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
import logging
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
|
||||
from screen_locker._constants import ADB_TIMEOUT
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AdbTransportMixin:
|
||||
"""Finds the phone over USB or wifi and runs adb commands against it."""
|
||||
|
||||
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
|
||||
"""Run an ADB command and return success flag and stdout."""
|
||||
adb = shutil.which("adb") or "adb"
|
||||
# When multiple devices are connected (e.g. USB + wireless), pin to
|
||||
# the wireless device's serial to avoid "more than one device" errors.
|
||||
_discovery_cmds = {"devices", "connect", "disconnect", "kill-server"}
|
||||
serial = (
|
||||
self._get_wireless_serial()
|
||||
if args and args[0] not in _discovery_cmds
|
||||
else None
|
||||
)
|
||||
serial_args = ["-s", serial] if serial else []
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, *serial_args, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=ADB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
except (FileNotFoundError, OSError) as exc:
|
||||
_logger.warning("ADB not available: %s", exc)
|
||||
return False, ""
|
||||
except subprocess.TimeoutExpired:
|
||||
_logger.warning("ADB command timed out: %s", args)
|
||||
return False, ""
|
||||
return not result.returncode, result.stdout
|
||||
|
||||
def _adb_shell(self, command: str, *, root: bool = False) -> tuple[bool, str]:
|
||||
"""Run a shell command on the connected Android device."""
|
||||
if root:
|
||||
return self._run_adb(["shell", "su", "-c", command])
|
||||
return self._run_adb(["shell", command])
|
||||
|
||||
def _get_wireless_serial(self) -> str | None:
|
||||
"""Return the serial (ip:port) of the first connected wireless ADB device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return None
|
||||
for line in output.strip().split("\n")[1:]:
|
||||
parts = line.split()
|
||||
if parts and ":" in parts[0] and "device" in line and "offline" not in line:
|
||||
return parts[0]
|
||||
return None
|
||||
|
||||
def _has_adb_device(self) -> bool:
|
||||
"""Return True if adb devices shows at least one connected device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return False
|
||||
lines = output.strip().split("\n")[1:]
|
||||
return any("device" in line and "offline" not in line for line in lines)
|
||||
|
||||
def _try_adb_connect(self, address: str) -> bool:
|
||||
"""Run adb connect to address. Returns True on success."""
|
||||
_, output = self._run_adb(["connect", address])
|
||||
lower = output.lower()
|
||||
return "connected" in lower and "unable" not in lower and "failed" not in lower
|
||||
|
||||
def _get_local_subnet_prefix(self) -> str | None:
|
||||
"""Detect the local /24 network prefix (e.g. '192.168.1')."""
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
|
||||
):
|
||||
sock.connect(("8.8.8.8", 80))
|
||||
return ".".join(sock.getsockname()[0].split(".")[:3])
|
||||
return None
|
||||
|
||||
def _try_wireless_reconnect(self) -> bool:
|
||||
"""Scan local /24 subnet on port 5555 and attempt ADB connect to phone."""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
_logger.info("Could not determine local subnet for wireless scan")
|
||||
return False
|
||||
|
||||
def probe(i: int) -> bool:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, 5555), timeout=0.5),
|
||||
):
|
||||
if self._try_adb_connect(f"{ip}:5555"):
|
||||
return self._has_adb_device()
|
||||
return False
|
||||
|
||||
_logger.info("Scanning %s.1-254:5555 for phone...", prefix)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
if future.result():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_phone_connected(self) -> bool:
|
||||
"""Check if an Android device is connected via ADB.
|
||||
|
||||
If no device is visible, attempts wireless reconnection via subnet scan.
|
||||
"""
|
||||
if self._has_adb_device():
|
||||
return True
|
||||
_logger.info("No ADB device detected — attempting wireless reconnect...")
|
||||
return self._try_wireless_reconnect()
|
||||
|
||||
# ── ADB verification ──────────────────────────────────────────────────────
|
||||
@ -1,219 +0,0 @@
|
||||
"""Whether systemd would actually run the locker, read from systemd itself.
|
||||
|
||||
The 2026-08 outage was not a logic bug. Every predicate worked; the timer that
|
||||
*invokes* them had been disabled by an ordering cycle, and nothing on the
|
||||
machine considered that worth mentioning. ``systemctl status`` showed no failed
|
||||
unit, because a job deleted to break a cycle is not a failure -- it is an
|
||||
absence, and absences do not page anyone.
|
||||
|
||||
This module answers one question -- *would enforcement actually happen?* -- from
|
||||
systemd's own view rather than from the unit files on disk, because the files
|
||||
were correct-looking the entire time the timer sat disabled.
|
||||
|
||||
It lives in the package rather than in ``scripts/`` because two surfaces need
|
||||
the same answer: ``scripts/check_enforcement_armed.py`` (the gate that rides
|
||||
along with ``workout-sync.service``) and the Health view of the local web UI.
|
||||
Two copies of this logic would be free to disagree about whether the locker is
|
||||
alive, which is the failure it exists to detect.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Every unit that must be armed for a workout-less day to end in a lock.
|
||||
# The timers are what make enforcement recur.
|
||||
REQUIRED_TIMERS = (
|
||||
"early-bird-workout-check.timer",
|
||||
"workout-locker.timer",
|
||||
)
|
||||
|
||||
# workout-locker.service is WantedBy=graphical-session.target: a login
|
||||
# one-shot that closes the window between a boot and the next timer tick.
|
||||
# It is checked here because on 2026-08-30 it had silently drifted to
|
||||
# `disabled`, the machine rebooted at 14:06, and nothing enforced until
|
||||
# 14:30 -- while this very module reported "armed" the whole time, because
|
||||
# it only ever looked at the two timers.
|
||||
REQUIRED_SERVICES = ("workout-locker.service",)
|
||||
|
||||
# The target the login run hangs off. Checked as well as `is-enabled`
|
||||
# because ~/.config/i3/config notes that i3 "does not reliably activate
|
||||
# graphical-session.target" -- an enabled service anchored to an inactive
|
||||
# target is exactly the correct-looking-but-disarmed state this module was
|
||||
# written to catch.
|
||||
_LOGIN_TARGET = "graphical-session.target"
|
||||
|
||||
_TIMEOUT_SECONDS = 10
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimerState:
|
||||
"""What systemd currently believes about one timer."""
|
||||
|
||||
name: str
|
||||
enabled: bool
|
||||
enabled_raw: str
|
||||
scheduled: bool
|
||||
|
||||
@property
|
||||
def armed(self) -> bool:
|
||||
"""True only when the timer is both enabled and actually scheduled.
|
||||
|
||||
Both halves matter. ``is-enabled`` alone passes for a timer whose job
|
||||
systemd deleted to break an ordering cycle; ``list-timers`` alone passes
|
||||
for a transient ``start``ed timer that will not survive a reboot.
|
||||
|
||||
Returns:
|
||||
True when this timer would really fire.
|
||||
"""
|
||||
return self.enabled and self.scheduled
|
||||
|
||||
def describe(self) -> str:
|
||||
"""Return a one-line human summary of this unit's state.
|
||||
|
||||
Returns:
|
||||
An ``OK``/``DISARMED`` line naming every reason it is not armed.
|
||||
"""
|
||||
if self.armed:
|
||||
return f"OK {self.name}: {self._ready_phrase}"
|
||||
problems = []
|
||||
if not self.enabled:
|
||||
problems.append(f"not enabled (is-enabled={self.enabled_raw or 'unknown'})")
|
||||
if not self.scheduled:
|
||||
problems.append(self._missing_phrase)
|
||||
return f"DISARMED {self.name}: {', '.join(problems)}"
|
||||
|
||||
@property
|
||||
def _ready_phrase(self) -> str:
|
||||
"""Return the wording for an armed unit of this kind."""
|
||||
if self.name.endswith(".timer"):
|
||||
return "enabled and scheduled"
|
||||
return f"enabled and anchored to an active {_LOGIN_TARGET}"
|
||||
|
||||
@property
|
||||
def _missing_phrase(self) -> str:
|
||||
"""Return the wording for the not-scheduled half of this kind."""
|
||||
if self.name.endswith(".timer"):
|
||||
return "no next trigger in list-timers"
|
||||
return f"{_LOGIN_TARGET} is not active, so the login run cannot fire"
|
||||
|
||||
|
||||
def systemctl_available() -> bool:
|
||||
"""Return whether ``systemctl`` can be run at all.
|
||||
|
||||
Reachable in containers and CI. Callers must treat False as "did not
|
||||
check", never as "checked and fine".
|
||||
|
||||
Returns:
|
||||
True when ``systemctl`` is on PATH.
|
||||
"""
|
||||
return shutil.which("systemctl") is not None
|
||||
|
||||
|
||||
def _run(args: list[str]) -> tuple[int, str]:
|
||||
"""Run ``args``, returning ``(returncode, stdout)``. Never raises.
|
||||
|
||||
Args:
|
||||
args: The argument vector, passed without a shell.
|
||||
|
||||
Returns:
|
||||
The process return code and its stdout; ``(1, "")`` if it could not run.
|
||||
"""
|
||||
try:
|
||||
# Explicit argument list, never shell=True.
|
||||
proc = subprocess.run(
|
||||
args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_TIMEOUT_SECONDS,
|
||||
check=False,
|
||||
)
|
||||
except OSError, subprocess.SubprocessError:
|
||||
# A check that cannot run must not look like a check that passed.
|
||||
_logger.exception("Could not run %s", " ".join(args))
|
||||
return 1, ""
|
||||
return proc.returncode, proc.stdout
|
||||
|
||||
|
||||
def _scheduled_timers() -> set[str]:
|
||||
"""Return the timer names systemd currently has a next trigger for.
|
||||
|
||||
Returns:
|
||||
The subset of :data:`REQUIRED_TIMERS` with a scheduled next run.
|
||||
"""
|
||||
_, out = _run(["systemctl", "--user", "list-timers", "--all", "--no-pager"])
|
||||
scheduled: set[str] = set()
|
||||
for line in out.splitlines():
|
||||
for name in REQUIRED_TIMERS:
|
||||
# A timer with no next trigger prints "n/a" in the NEXT column.
|
||||
if name in line and " n/a " not in f" {line} ":
|
||||
scheduled.add(name)
|
||||
return scheduled
|
||||
|
||||
|
||||
LOCKER_UNIT = "workout-locker.service"
|
||||
|
||||
|
||||
def locker_unit_active() -> bool | None:
|
||||
"""Return whether the locker unit is running right now.
|
||||
|
||||
"The lock would fire" is a statement about the *decision*; it says
|
||||
nothing about whether anything is currently enforcing it. On 2026-08-30
|
||||
the machine had rebooted, no locker process existed, and the status page
|
||||
read exactly the same as it does with a lock on screen.
|
||||
|
||||
Returns:
|
||||
True/False, or None when systemd could not be asked -- which must
|
||||
never be rendered as "not running".
|
||||
"""
|
||||
if not systemctl_available():
|
||||
return None
|
||||
code, out = _run(["systemctl", "--user", "is-active", LOCKER_UNIT])
|
||||
if code and not out.strip():
|
||||
return None
|
||||
return out.strip() == "active"
|
||||
|
||||
|
||||
def _login_target_active() -> bool:
|
||||
"""Return whether the target the login run hangs off is active.
|
||||
|
||||
Returns:
|
||||
True when ``graphical-session.target`` is active.
|
||||
"""
|
||||
code, out = _run(["systemctl", "--user", "is-active", _LOGIN_TARGET])
|
||||
return not code and out.strip() == "active"
|
||||
|
||||
|
||||
def collect_states() -> list[TimerState]:
|
||||
"""Return the current arming state of every unit enforcement depends on.
|
||||
|
||||
Returns:
|
||||
One :class:`TimerState` per entry in :data:`REQUIRED_TIMERS` and
|
||||
:data:`REQUIRED_SERVICES`.
|
||||
"""
|
||||
scheduled = _scheduled_timers()
|
||||
login_target_up = _login_target_active()
|
||||
states = []
|
||||
for name in (*REQUIRED_TIMERS, *REQUIRED_SERVICES):
|
||||
code, out = _run(["systemctl", "--user", "is-enabled", name])
|
||||
raw = out.strip()
|
||||
states.append(
|
||||
TimerState(
|
||||
name=name,
|
||||
enabled=not code and raw == "enabled",
|
||||
enabled_raw=raw,
|
||||
# For a timer this is "systemd has a next trigger for it";
|
||||
# for the login-run service it is "the target it is wanted by
|
||||
# is actually up". Both answer the same question: would this
|
||||
# unit really fire?
|
||||
scheduled=(
|
||||
name in scheduled if name.endswith(".timer") else login_target_up
|
||||
),
|
||||
)
|
||||
)
|
||||
return states
|
||||
@ -1,20 +1,9 @@
|
||||
"""Mixin: the today-state rungs of the lock ladder, and the early-bird upgrade.
|
||||
"""Mixin: auto-upgrade early_bird/sick_day pending states via phone or RunnerUp.
|
||||
|
||||
early_bird is a same-day pending marker (``_early_bird.py``), not a log.json
|
||||
entry — this module only checks its pending state and, on success, writes
|
||||
the *real* outcome (phone_verified/runnerup_verified) there.
|
||||
|
||||
A sick day is a date in the shared ``sickdays`` pool (``_sick.py``): the
|
||||
lock stands down for it and nothing is written. A workout done on a sick
|
||||
day still reaches the log through the ordinary sync paths and earns
|
||||
normally, so there is no sick-day upgrade any more.
|
||||
|
||||
The upgrade credits through ``_apply_workout_credit`` -- save first, reward
|
||||
only if the entry was actually appended. It used to push the shutdown hour
|
||||
and THEN save: when the same run was already in the log (the 15-minute sync
|
||||
pass had pulled the TCX at 20:25 on 2026-09-16) the save deduped to nothing
|
||||
and the +2h landed anyway, and again on every 5-minute tick while the
|
||||
pending marker lasted -- a runaway that only the 23:00 ceiling stopped.
|
||||
Neither early_bird (a same-day pending marker, see ``_early_bird.py``) nor
|
||||
sick_day (tracked in ``sick_history.json`` via ``_sick_tracker.py``) live in
|
||||
workout_log.json — this module only checks their pending state and, on
|
||||
success, writes the *real* outcome (phone_verified/runnerup_verified) there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -22,64 +11,13 @@ from __future__ import annotations
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from screen_locker._decision_log import LockDecision, record_decision
|
||||
from screen_locker._decision_reasons import reasons_extra
|
||||
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._sick import stands_down_workout
|
||||
from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day
|
||||
from screen_locker import _sick_tracker
|
||||
from screen_locker._wake_state import has_workout_skip_today
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _skip(reason: str, detail: str, **extra: object) -> None:
|
||||
"""Record a decision NOT to enforce, then exit.
|
||||
|
||||
Every branch that abandons enforcement goes through here. Before this
|
||||
existed each one just logged at INFO and called ``sys.exit(0)``, which is
|
||||
how the locker managed to stop enforcing for thirteen days without leaving
|
||||
a single line saying so.
|
||||
"""
|
||||
record_decision(
|
||||
LockDecision(locked=False, reason=reason, detail=detail, extra=extra)
|
||||
)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
class _ReasonsMixin:
|
||||
"""Supplies the side-effect-free conditions that annotate a decision.
|
||||
|
||||
The ladder below is first-match-wins, so only the acting reason was ever
|
||||
recorded. These predicates let a line also name the conditions that held
|
||||
but were never reached -- notably "the workout is already logged" hiding
|
||||
behind "the early-bird window is open".
|
||||
"""
|
||||
|
||||
def _other_conditions(self, acting: str) -> dict[str, object]:
|
||||
"""Return the ``also=`` extra naming every other condition that holds.
|
||||
|
||||
Strictly read-only. ``_try_auto_upgrade_*`` and
|
||||
``_save_early_bird_pending`` are deliberately absent: they write log
|
||||
entries and state, and must never run to produce a log line.
|
||||
"""
|
||||
return reasons_extra(
|
||||
acting,
|
||||
{
|
||||
"scheduled_skip_day": self._is_scheduled_skip_today,
|
||||
"early_bird_window_active": self._is_early_bird_pending,
|
||||
"sick_day": self._is_sick_day_today,
|
||||
"workout_logged_today": self.has_logged_today,
|
||||
"wake_alarm_skip": has_workout_skip_today,
|
||||
"relaxed_day": is_relaxed_day,
|
||||
"weekly_minimum_met": lambda: has_weekly_minimum(self.log_file),
|
||||
"evening_lockdown_today": has_evening_lockdown_today,
|
||||
"test_hold_active": workout_hold_active,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class AutoUpgradeMixin(_ReasonsMixin):
|
||||
class AutoUpgradeMixin:
|
||||
"""Handles today-state detection and silent log-entry upgrading.
|
||||
|
||||
Relies on methods from EarlyBirdMixin, PhoneVerificationMixin,
|
||||
@ -87,99 +25,84 @@ class AutoUpgradeMixin(_ReasonsMixin):
|
||||
"""
|
||||
|
||||
def _is_sick_day_today(self) -> bool:
|
||||
"""Whether the sickdays pool switches the workout lock off today.
|
||||
"""Check if today is marked as a sick day in sick_history.json."""
|
||||
return _sick_tracker.is_sick_day(_sick_tracker.load_history())
|
||||
|
||||
A sick day that keeps the workout locker is a normal day here.
|
||||
"""
|
||||
return stands_down_workout()
|
||||
|
||||
def _check_early_exits(self) -> None:
|
||||
def _check_early_exits(self, *, verify_only: bool) -> None:
|
||||
"""Check startup conditions and exit early when appropriate."""
|
||||
if verify_only:
|
||||
if not self._is_sick_day_today():
|
||||
_logger.info("No sick day logged today. Nothing to verify.")
|
||||
sys.exit(0)
|
||||
return
|
||||
self._check_non_verify_exits()
|
||||
|
||||
def _check_today_state_exits(self) -> bool:
|
||||
"""Handle early-bird and today's log states. Return True to stop startup."""
|
||||
pending = self._is_early_bird_pending()
|
||||
window_open = self._is_early_bird_time()
|
||||
if pending and not window_open and self._try_auto_upgrade_early_bird():
|
||||
_skip(
|
||||
"early_bird_auto_upgraded",
|
||||
"Auto-upgraded early_bird entry to phone_verified.",
|
||||
)
|
||||
return True
|
||||
# An expired marker with nothing to upgrade is NOT a lock on its own.
|
||||
# It used to `return False` right here, ahead of has_logged_today, so
|
||||
# a workout logged by any other path after 08:30 never counted while
|
||||
# the marker lasted: on 2026-09-18 a manual walk entered on the lock
|
||||
# screen at 09:32 closed the lock, and the 09:35 tick locked again --
|
||||
# every 5 minutes, for the rest of the day -- while the explain chain
|
||||
# (_compliance_state, where the expired marker is non-terminal) said
|
||||
# "lock skipped". Fall through to the same ladder as any other morning.
|
||||
if pending and window_open:
|
||||
# The window is the wake-alarm carrot (see EarlyBirdMixin): it
|
||||
# closes when the signed exempt_until passes, and the 5-minute
|
||||
# tick plus early-bird-workout-check.timer then re-decide.
|
||||
_skip(
|
||||
"early_bird_window_active",
|
||||
f"Morning-session carrot still in force: {self._morning_skip}.",
|
||||
recheck_by="workout-locker.timer",
|
||||
**self._other_conditions("early_bird_window_active"),
|
||||
)
|
||||
if self._is_early_bird_pending() and not self._is_early_bird_time():
|
||||
if self._try_auto_upgrade_early_bird():
|
||||
_logger.info("Auto-upgraded early_bird entry to phone_verified.")
|
||||
sys.exit(0)
|
||||
return True
|
||||
return False # Expired early bird, upgrade unavailable — full lock.
|
||||
if self._is_early_bird_pending():
|
||||
_logger.info("Early bird window still active — skipping lock.")
|
||||
elif self._is_sick_day_today():
|
||||
_skip(
|
||||
"sick_day",
|
||||
"Today is a sick day (sickdays pool); the workout lock is off.",
|
||||
**self._other_conditions("sick_day"),
|
||||
)
|
||||
if self._try_auto_upgrade_sick_day():
|
||||
_logger.info("Auto-upgraded today's sick_day entry to phone_verified.")
|
||||
else:
|
||||
_logger.info("Sick day already logged today.")
|
||||
elif self.has_logged_today():
|
||||
_skip(
|
||||
"workout_logged_today",
|
||||
"Workout already logged today.",
|
||||
**self._other_conditions("workout_logged_today"),
|
||||
)
|
||||
elif window_open:
|
||||
# Bank the marker so the run that sees the carrot end tries a
|
||||
# phone/RunnerUp workout before falling through to a lock.
|
||||
_logger.info("Workout already logged today. Skipping screen lock.")
|
||||
elif has_workout_skip_today():
|
||||
_logger.info("Wake alarm earned workout skip. Skipping screen lock.")
|
||||
elif self._is_early_bird_time():
|
||||
self._save_early_bird_pending()
|
||||
skip = self._morning_skip
|
||||
_skip(
|
||||
"wake_alarm_skip",
|
||||
f"Morning session earned it: {skip or 'carrot in force'}.",
|
||||
exempt_until=skip.exempt_until.isoformat() if skip else None,
|
||||
outcome=skip.outcome if skip else None,
|
||||
**self._other_conditions("wake_alarm_skip"),
|
||||
)
|
||||
_logger.info("Early bird time — skipping lock, will re-check at 08:30.")
|
||||
else:
|
||||
return False
|
||||
sys.exit(0)
|
||||
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,
|
||||
},
|
||||
def _try_auto_upgrade_sick_day(self) -> bool:
|
||||
"""Upgrade sick_day entry when phone or RunnerUp detects a valid workout."""
|
||||
try:
|
||||
status, message = self._verify_phone_workout()
|
||||
except (OSError, RuntimeError) as exc:
|
||||
_logger.warning(
|
||||
"Sick-day auto-upgrade could not reach the phone (%s) — today's "
|
||||
"sick_day entry stays unverified; trying RunnerUp next",
|
||||
exc,
|
||||
)
|
||||
)
|
||||
_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()
|
||||
status, message = "error", str(exc)
|
||||
if status == "verified":
|
||||
self.workout_data["type"] = "phone_verified"
|
||||
self.workout_data["source"] = message
|
||||
self.workout_data["after_sick_day"] = "true"
|
||||
self._adjust_shutdown_time_later()
|
||||
self.save_workout_log()
|
||||
return True
|
||||
_logger.info("Auto-upgrade phone skipped (%s), trying RunnerUp...", status)
|
||||
try:
|
||||
runnerup_status, runnerup_msg = self._verify_runnerup_workout()
|
||||
except (OSError, RuntimeError) as exc:
|
||||
_logger.warning(
|
||||
"Sick-day auto-upgrade could not read RunnerUp either (%s) — "
|
||||
"today stays a sick_day, NOT upgraded to a verified workout",
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if runnerup_status != "verified":
|
||||
_logger.info(
|
||||
"Auto-upgrade RunnerUp skipped (%s): %s", runnerup_status, runnerup_msg
|
||||
)
|
||||
return False
|
||||
self.workout_data["type"] = "runnerup_verified"
|
||||
self.workout_data["source"] = runnerup_msg
|
||||
self.workout_data["after_sick_day"] = "true"
|
||||
self._adjust_shutdown_time_later()
|
||||
self.save_workout_log()
|
||||
return True
|
||||
|
||||
def _try_auto_upgrade_early_bird(self) -> bool:
|
||||
"""Try phone then RunnerUp to upgrade an early_bird log entry."""
|
||||
@ -196,7 +119,8 @@ class AutoUpgradeMixin(_ReasonsMixin):
|
||||
self.workout_data["type"] = "phone_verified"
|
||||
self.workout_data["source"] = message
|
||||
self.workout_data["after_early_bird"] = "true"
|
||||
self._apply_workout_credit()
|
||||
self._adjust_shutdown_time_later()
|
||||
self.save_workout_log()
|
||||
return True
|
||||
_logger.info("Early bird phone skipped (%s), trying RunnerUp...", status)
|
||||
try:
|
||||
@ -217,5 +141,6 @@ class AutoUpgradeMixin(_ReasonsMixin):
|
||||
self.workout_data["type"] = "runnerup_verified"
|
||||
self.workout_data["source"] = runnerup_msg
|
||||
self.workout_data["after_early_bird"] = "true"
|
||||
self._apply_workout_credit()
|
||||
self._adjust_shutdown_time_later()
|
||||
self.save_workout_log()
|
||||
return True
|
||||
|
||||
@ -1,38 +0,0 @@
|
||||
"""One writer at a time for the shutdown bonus state.
|
||||
|
||||
The daily reset and the live bonus pass both read ``shutdown_base.json``,
|
||||
push ``/etc/shutdown-schedule.conf`` with a read-add-write and stamp the file.
|
||||
They run from three processes -- the locker at login, the 15-minute
|
||||
``workout-sync`` pass and the ledger-triggered ``earner-bonus`` pass -- so two
|
||||
of them can see the same unstamped earner and each add its time. Holding this
|
||||
lock across check, write and stamp makes the second one see the stamp.
|
||||
|
||||
A dedicated file, not the state file itself: ``_save_state`` truncates that.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
import fcntl
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = ["bonus_lock"]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def bonus_lock(state_file: Path) -> Iterator[None]:
|
||||
"""Hold an exclusive lock beside *state_file* for the ``with`` body.
|
||||
|
||||
Blocks until any other holder is done; the passes it serialises take a
|
||||
second or two, so waiting is cheaper than skipping a bonus.
|
||||
"""
|
||||
with state_file.with_suffix(".lock").open("a") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
@ -1,76 +0,0 @@
|
||||
"""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)
|
||||
@ -1,39 +0,0 @@
|
||||
"""The latest shutdown a day can earn: ``earned_time``'s ceiling, bounded at 23:00."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import earned_time
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# adjust_shutdown_schedule.sh's RESTORE_CEILING (23:00): the hard upper bound
|
||||
# every --restore write is clamped to, and the answer when the lookup fails.
|
||||
HARD_CEILING_MINUTES = 23 * 60
|
||||
|
||||
|
||||
def ceiling(day: date) -> int:
|
||||
"""The latest shutdown ``day`` can earn, minutes after its midnight.
|
||||
|
||||
Never above :data:`HARD_CEILING_MINUTES`. A lookup that raises fails open
|
||||
to that bound -- the same cap the helper enforces anyway -- and says so at
|
||||
warning, so a broken registry cannot silently lift or lower the cap.
|
||||
"""
|
||||
fn = getattr(earned_time, "shutdown_ceiling_for", None)
|
||||
if fn is None:
|
||||
return min(HARD_CEILING_MINUTES, int(earned_time.SHUTDOWN_CEILING_MINUTES))
|
||||
try:
|
||||
return min(HARD_CEILING_MINUTES, int(fn(day)))
|
||||
except (ArithmeticError, LookupError, TypeError, ValueError) as err:
|
||||
_logger.warning(
|
||||
"shutdown ceiling for %s unavailable (%s); using %s",
|
||||
day,
|
||||
err,
|
||||
f"{HARD_CEILING_MINUTES // 60:02d}:{HARD_CEILING_MINUTES % 60:02d}",
|
||||
)
|
||||
return HARD_CEILING_MINUTES
|
||||
@ -1,156 +0,0 @@
|
||||
"""Command-line entry points for ``screen_lock.py``.
|
||||
|
||||
Split out of ``screen_lock.py`` to keep every file under the 250-line cap.
|
||||
The argument handling lives here; ``screen_lock.py`` keeps only the
|
||||
``ScreenLocker`` class and a one-line ``__main__`` delegation, so the module
|
||||
that every mixin imports stays small.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker import _errors
|
||||
from screen_locker._constants import SHUTDOWN_BASE_FILE
|
||||
from screen_locker._decision_log import record_no_decision
|
||||
from screen_locker._manual_cli import run_manual_log
|
||||
from screen_locker._rest_day_cli import run_declare_rest_day
|
||||
from screen_locker._shutdown_base import apply_flat_bonuses_if_new
|
||||
from screen_locker._status import run_status
|
||||
from screen_locker._workout_ledger_cli import run_backfill
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from screen_locker.screen_lock import ScreenLocker
|
||||
|
||||
__all__ = ["main"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_LOG_FILE_NAME = "log.json"
|
||||
_LOG_MANUAL_FLAG = "--log-manual-workout"
|
||||
_REST_DAY_FLAG = "--declare-rest-day"
|
||||
_BACKFILL_FLAG = "--backfill-workout-ledger"
|
||||
|
||||
# Subcommands that own every argument after them (each has its own argparse,
|
||||
# which also answers its own --help).
|
||||
_TRAILING_ARG_FLAGS = (_LOG_MANUAL_FLAG, _REST_DAY_FLAG, _BACKFILL_FLAG)
|
||||
_MODE_FLAGS = frozenset({"--status", "--sync-only", "--apply-bonuses", "--production"})
|
||||
_HELP_FLAGS = frozenset({"-h", "--help"})
|
||||
_EXIT_USAGE = 2
|
||||
|
||||
_USAGE = """\
|
||||
usage: python3 -m screen_locker.screen_lock [MODE]
|
||||
|
||||
With no mode: the demo lock screen (Tk). Modes:
|
||||
--production the real lock screen (what workout-locker.service runs)
|
||||
--status print this week's workout status and exit
|
||||
--sync-only headless: pull synced workouts, apply credit, exit
|
||||
--apply-bonuses headless: apply newly earned flat bonuses, exit
|
||||
--log-manual-workout ARGS headless manual workout log (see its --help)
|
||||
--declare-rest-day ARGS sign a future rest day (see its --help)
|
||||
--backfill-workout-ledger ARGS
|
||||
backfill the workout ledger (see its --help)
|
||||
-h, --help show this help and exit
|
||||
"""
|
||||
|
||||
|
||||
def _own_args(argv: list[str]) -> list[str]:
|
||||
"""``argv[1:]`` up to the first subcommand that owns the rest."""
|
||||
args = argv[1:]
|
||||
for index, arg in enumerate(args):
|
||||
if arg in _TRAILING_ARG_FLAGS:
|
||||
return args[:index]
|
||||
return args
|
||||
|
||||
|
||||
def _handle_help_and_unknown(argv: list[str]) -> None:
|
||||
"""Exit 0 on ``--help``; exit 2 on an unknown argument.
|
||||
|
||||
Before this, ``--help`` matched no branch and fell through to building
|
||||
the demo lock screen, and a typo'd flag did the same silently.
|
||||
"""
|
||||
own = _own_args(argv)
|
||||
if _HELP_FLAGS & set(own):
|
||||
# The usage on stdout IS the work --help asked for, so exiting 0 here
|
||||
# abandons nothing. SystemExit is raised directly, not via sys.exit:
|
||||
# the suite stubs sys.exit process-wide, and a help request must never
|
||||
# fall through to building the lock screen even then.
|
||||
sys.stdout.write(_USAGE)
|
||||
raise SystemExit(0)
|
||||
unknown = [arg for arg in own if arg not in _MODE_FLAGS]
|
||||
if unknown:
|
||||
sys.stderr.write(f"error: unknown argument(s): {' '.join(unknown)}\n{_USAGE}")
|
||||
sys.exit(_EXIT_USAGE)
|
||||
|
||||
|
||||
def _headless_locker(locker_cls: type[ScreenLocker]) -> ScreenLocker:
|
||||
"""A ScreenLocker with ``__init__`` bypassed, for the no-UI subcommands.
|
||||
|
||||
``--status`` and ``--sync-only`` touch only ``log_file`` and
|
||||
``workout_data``; constructing the real object would build a Tk UI and,
|
||||
in the ``--production`` case, grab the screen.
|
||||
"""
|
||||
locker = object.__new__(locker_cls)
|
||||
locker.log_file = Path(__file__).resolve().parent / _LOG_FILE_NAME
|
||||
locker.workout_data = {}
|
||||
return locker
|
||||
|
||||
|
||||
def main(locker_cls: type[ScreenLocker], argv: list[str]) -> None:
|
||||
"""Dispatch on ``argv`` and run the requested mode."""
|
||||
_handle_help_and_unknown(argv)
|
||||
# Configure logging for EVERY mode, not just --sync-only. This used to sit
|
||||
# inside the --sync-only branch, so `--production` -- the mode systemd
|
||||
# actually runs -- had no handler and fell back to lastResort, which drops
|
||||
# everything below WARNING. The result: zero INFO lines from
|
||||
# workout-locker.service since June, and a thirteen-day enforcement outage
|
||||
# that left no trace at all. Never narrow this back to one branch.
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
_errors.install()
|
||||
if "--status" in argv:
|
||||
run_status(_headless_locker(locker_cls))
|
||||
|
||||
if _LOG_MANUAL_FLAG in argv:
|
||||
# Headless manual logging: no Tk, no phone, no app in the foreground.
|
||||
# Everything after the flag is the workout's evidence, validated by
|
||||
# the same rules the phone form applies.
|
||||
rest = argv[argv.index(_LOG_MANUAL_FLAG) + 1 :]
|
||||
sys.exit(run_manual_log(_headless_locker(locker_cls).log_file, rest))
|
||||
|
||||
if _REST_DAY_FLAG in argv:
|
||||
# Headless, no Tk: sign a FUTURE rest day (see screen_locker._rest_day).
|
||||
sys.exit(run_declare_rest_day(argv[argv.index(_REST_DAY_FLAG) + 1 :]))
|
||||
|
||||
if _BACKFILL_FLAG in argv:
|
||||
rest = argv[argv.index(_BACKFILL_FLAG) + 1 :]
|
||||
sys.exit(run_backfill(_headless_locker(locker_cls).log_file, rest))
|
||||
|
||||
if "--sync-only" in argv:
|
||||
# Headless sync for the timer unit: pull other devices' workouts and
|
||||
# apply their credit, with no Tk and no lock screen. Sync used to run
|
||||
# ONLY at process start, so a workout finished after login was not seen
|
||||
# until the next login — the timer closes that window.
|
||||
_headless_locker(locker_cls).sync_now()
|
||||
# Say so explicitly: --sync-only NEVER locks, so a reader tracing "why
|
||||
# didn't it lock?" through the journal must not mistake a sync run for
|
||||
# an enforcement run that decided to skip.
|
||||
record_no_decision("--sync-only")
|
||||
sys.exit(0)
|
||||
|
||||
if "--apply-bonuses" in argv:
|
||||
# earner-bonus.service, started by earner-bonus.path when a gate
|
||||
# writes its ledger: only the flat-bonus pass, no phone sync, so a
|
||||
# solve moves shutdown within seconds rather than at the next sync.
|
||||
_logger.info("Ledger changed: applying any newly earned flat bonus.")
|
||||
apply_flat_bonuses_if_new(SHUTDOWN_BASE_FILE, _headless_locker(locker_cls))
|
||||
record_no_decision("--apply-bonuses")
|
||||
sys.exit(0)
|
||||
|
||||
locker = locker_cls(demo_mode="--production" not in argv)
|
||||
locker.run()
|
||||
@ -1,137 +0,0 @@
|
||||
"""Pure, read-only leaf predicates for the lock-decision chain.
|
||||
|
||||
Split out of :mod:`screen_locker._compliance_state` to keep every file under
|
||||
the 250-line cap. That module re-exports everything here, so existing
|
||||
importers are unaffected.
|
||||
|
||||
Nothing in this module touches ADB, sudo, subprocess, or the network, and
|
||||
nothing writes to disk.
|
||||
|
||||
Note for tests: the ``gatelock.log_integrity`` helpers are imported *here*
|
||||
now, so patch them at ``screen_locker._compliance_predicates.verify_entry_hmac``
|
||||
rather than at the old ``_compliance_state`` path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import freedays
|
||||
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick import stands_down_workout
|
||||
from screen_locker._weekly_check import RELAXED_DAY_SKIP_TYPE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _today_str() -> str:
|
||||
"""Return today's LOCAL date as ``YYYY-MM-DD`` (see ``screen_locker._day``)."""
|
||||
return today_str()
|
||||
|
||||
|
||||
def is_scheduled_skip_today(today: date | None = None) -> bool:
|
||||
"""Return True if *today* is in the shared free-day pool.
|
||||
|
||||
The source moved from this app's own ``scheduled_skips.json`` to the
|
||||
fleet-wide pool (``~/src/utils/freedays``), so one marked day now stands down
|
||||
every gate app at once instead of only this one.
|
||||
|
||||
The date is **local**, not UTC. The file-backed check this replaces
|
||||
compared against a UTC day while ``add_scheduled_skip.py`` wrote a local
|
||||
one, so a skip added near midnight could name a date the chain never
|
||||
matched. freedays owns "what is today" for all of them now.
|
||||
|
||||
Still fails closed: an unreadable pool reads as "not free", so the lock
|
||||
chain continues rather than the lock silently switching itself off.
|
||||
"""
|
||||
return freedays.is_free_day(today)
|
||||
|
||||
|
||||
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if a validly-signed workout is logged for *today*.
|
||||
|
||||
The day may hold multiple workouts; return True if ANY of today's entries
|
||||
verifies (or is acceptably unsigned when no HMAC key is configured).
|
||||
A ``relaxed_day_skip`` entry does NOT count — it is a UI-dismissal marker,
|
||||
not a workout, and must not be mistaken for one by ``workout_logged_today``
|
||||
(which would otherwise mask the more accurate
|
||||
``relaxed_day_already_skipped`` reason in the decision trail).
|
||||
"""
|
||||
entries = [
|
||||
entry
|
||||
for entry in load_workout_log(log_file).get(today or _today_str(), [])
|
||||
if entry.get("workout_data", {}).get("type") != RELAXED_DAY_SKIP_TYPE
|
||||
]
|
||||
if not entries:
|
||||
return False
|
||||
key_unavailable = compute_entry_hmac({"_probe": True}) is None
|
||||
for entry in entries:
|
||||
if verify_entry_hmac(entry):
|
||||
return True
|
||||
if key_unavailable and "hmac" not in entry:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned entry")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for today's log entries")
|
||||
return False
|
||||
|
||||
|
||||
def is_relaxed_day_skipped_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if today's relaxed-day prompt was already dismissed.
|
||||
|
||||
Written by ``UIFlowsRelaxedMixin._skip_relaxed_day`` when the user clicks
|
||||
"Skip — No Penalty". Without this, the recurring 30-minute
|
||||
``workout-locker.timer`` re-derives ``relaxed_day`` from scratch every
|
||||
tick and re-shows the popup, since ``is_relaxed_day`` is a pure date
|
||||
check with no memory of a same-day dismissal on its own.
|
||||
"""
|
||||
entries = load_workout_log(log_file).get(today or _today_str(), [])
|
||||
return any(
|
||||
entry.get("workout_data", {}).get("type") == RELAXED_DAY_SKIP_TYPE
|
||||
for entry in entries
|
||||
)
|
||||
|
||||
|
||||
def is_early_bird_pending(pending_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if today has an unresolved early-bird pending marker."""
|
||||
if not pending_file.exists():
|
||||
return False
|
||||
try:
|
||||
with pending_file.open() as f:
|
||||
state = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read the early-bird pending marker at %s: %s — treating "
|
||||
"it as not pending, so the lock chain proceeds as if no early bird "
|
||||
"was claimed today",
|
||||
pending_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if not isinstance(state, dict) or state.get("date") != (today or _today_str()):
|
||||
return False
|
||||
if verify_entry_hmac(state):
|
||||
return True
|
||||
if compute_entry_hmac({"_probe": True}) is None and "hmac" not in state:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned pending marker")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for early-bird pending marker")
|
||||
return False
|
||||
|
||||
|
||||
def is_sick_day_today(today: date | None = None) -> bool:
|
||||
"""Return True if the sickdays pool switches the workout lock off that day.
|
||||
|
||||
Kept here so callers of the status layer have one predicate module to
|
||||
import from; the answer itself is ``_sick.stands_down_workout``'s, so a
|
||||
sick day that keeps the workout locker reads False.
|
||||
"""
|
||||
return stands_down_workout(today)
|
||||
@ -6,6 +6,7 @@ Single source of truth for the leaf checks walked by
|
||||
mixins delegate their read-only checks to the functions here; this module
|
||||
never touches ADB, sudo, subprocess, or the network, and never writes to
|
||||
disk.
|
||||
|
||||
``explain_lock_decision`` re-derives the same ordered chain for the status
|
||||
view. One branch is a deliberate simplification: when an early-bird pending
|
||||
marker has expired, the real code attempts a live phone/RunnerUp
|
||||
@ -18,194 +19,224 @@ surfaces the pending opportunity separately via ``AutoUpgradeOpportunity``.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._compliance_predicates import (
|
||||
has_logged_today,
|
||||
is_early_bird_pending,
|
||||
is_relaxed_day_skipped_today,
|
||||
is_scheduled_skip_today,
|
||||
is_sick_day_today,
|
||||
from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_END_HOUR,
|
||||
EARLY_BIRD_END_MINUTE,
|
||||
EARLY_BIRD_START_HOUR,
|
||||
)
|
||||
from screen_locker._compliance_trace import (
|
||||
AutoUpgradeOpportunity,
|
||||
LockExplanation,
|
||||
PredicateResult,
|
||||
StageContext,
|
||||
_stage,
|
||||
describe_auto_upgrade_opportunity,
|
||||
describe_degraded_sources,
|
||||
)
|
||||
from screen_locker._day import today_str as local_day
|
||||
from screen_locker._hold import workout_hold_active
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick_tracker import is_sick_day as _is_sick_day
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._degraded_sources import DegradedSource
|
||||
from screen_locker._sick_tracker import SickHistory
|
||||
|
||||
__all__ = [
|
||||
"AutoUpgradeOpportunity",
|
||||
"LockExplanation",
|
||||
"PredicateResult",
|
||||
"describe_auto_upgrade_opportunity",
|
||||
"explain_lock_decision",
|
||||
"has_logged_today",
|
||||
"is_early_bird_pending",
|
||||
"is_relaxed_day_skipped_today",
|
||||
"is_scheduled_skip_today",
|
||||
"is_sick_day_today",
|
||||
]
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _today_str() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` in UTC."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Step:
|
||||
"""One predicate of the lock-decision chain, in evaluation order."""
|
||||
class PredicateResult:
|
||||
"""One evaluated step in a :class:`LockExplanation` trace."""
|
||||
|
||||
name: str
|
||||
reason_true: str
|
||||
reason_false: str
|
||||
terminal_reason: str | None = None
|
||||
note_when_false: bool = False
|
||||
fired: bool
|
||||
reason: str
|
||||
|
||||
|
||||
# Order mirrors ``_check_non_verify_exits`` / ``_check_today_state_exits``.
|
||||
# ``early_bird_pending_expired`` is recorded but never terminal on its own: an
|
||||
# expired pending marker still falls through toward a full lock, with the
|
||||
# upgrade opportunity surfaced separately (see module docstring).
|
||||
_CHAIN: tuple[_Step, ...] = (
|
||||
_Step(
|
||||
"scheduled_skip",
|
||||
"Today is in scheduled_skips.json (unconditional manual skip).",
|
||||
"Today is not a manually scheduled skip day.",
|
||||
"Manually scheduled skip day — no lock, no workout required.",
|
||||
),
|
||||
_Step(
|
||||
"early_bird_pending_expired",
|
||||
"Logged in during the early-bird window and it has since closed "
|
||||
"with no workout confirmed yet.",
|
||||
"No expired early-bird pending marker.",
|
||||
),
|
||||
_Step(
|
||||
"early_bird_window_open",
|
||||
"Logged in during the early-bird window earlier today; still "
|
||||
"waiting to see a workout before the window closes.",
|
||||
"Not pending inside an open early-bird window.",
|
||||
"Early-bird window still open — lock skipped while waiting for a workout.",
|
||||
),
|
||||
_Step(
|
||||
"sick_day",
|
||||
"Today is a sick day in the shared sickdays pool.",
|
||||
"Today is not a sick day.",
|
||||
"Sick day today — lock skipped.",
|
||||
),
|
||||
_Step(
|
||||
"already_logged",
|
||||
"A validly-signed workout is already logged for today.",
|
||||
"No workout logged for today yet.",
|
||||
"Workout already logged today — lock skipped.",
|
||||
note_when_false=True,
|
||||
),
|
||||
_Step(
|
||||
"wake_alarm_skip",
|
||||
"The morning session earned a workout skip for now.",
|
||||
"No morning-session skip in force.",
|
||||
"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(
|
||||
"relaxed_day_already_skipped",
|
||||
"Relaxed day already dismissed via Skip — No Penalty today.",
|
||||
"No same-day relaxed-day dismissal on record.",
|
||||
"Relaxed day already skipped today — lock skipped, prompt not shown again.",
|
||||
),
|
||||
_Step(
|
||||
"relaxed_day",
|
||||
"Today is a relaxed day (Tue/Wed/Thu).",
|
||||
"Today is not a relaxed day.",
|
||||
"Relaxed day (Tue/Wed/Thu) — workout optional, lock skipped.",
|
||||
),
|
||||
_Step(
|
||||
"weekly_minimum_met",
|
||||
"Weekly workout minimum already reached.",
|
||||
"Weekly workout minimum not yet reached.",
|
||||
"Weekly workout minimum already met — lock skipped.",
|
||||
),
|
||||
_Step(
|
||||
"evening_lockdown_today",
|
||||
"Tonight's night lockdown already fired (>= 12:00 today).",
|
||||
"No evening night lockdown yet today.",
|
||||
"Night lockdown already happened tonight — the workout lock does not re-arm.",
|
||||
),
|
||||
@dataclass(frozen=True)
|
||||
class AutoUpgradeOpportunity:
|
||||
"""Describes whether the real locker would attempt a live auto-upgrade."""
|
||||
|
||||
would_attempt: bool
|
||||
via: str # "early_bird_expired" | "sick_day" | "none"
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LockExplanation:
|
||||
"""Read-only reconstruction of what the lock-decision chain would do."""
|
||||
|
||||
fired: bool
|
||||
stage: str
|
||||
reason: str
|
||||
trace: tuple[PredicateResult, ...]
|
||||
auto_upgrade: AutoUpgradeOpportunity
|
||||
heat_skip_evaluated: bool
|
||||
|
||||
|
||||
_NO_UPGRADE = AutoUpgradeOpportunity(
|
||||
would_attempt=False,
|
||||
via="none",
|
||||
reason="No pending auto-upgrade opportunity.",
|
||||
)
|
||||
|
||||
|
||||
def _chain_flags(
|
||||
def is_scheduled_skip_today(
|
||||
scheduled_skips_file: Path, *, today: str | None = None
|
||||
) -> bool:
|
||||
"""Return True if *today* is listed in *scheduled_skips_file*."""
|
||||
if not scheduled_skips_file.exists():
|
||||
return False
|
||||
try:
|
||||
with scheduled_skips_file.open() as f:
|
||||
skips = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read scheduled skips from %s: %s — treating today as NOT "
|
||||
"a scheduled skip (the lock chain continues)",
|
||||
scheduled_skips_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
return (today or _today_str()) in skips
|
||||
|
||||
|
||||
def has_logged_today(log_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if a validly-signed workout is logged for *today*.
|
||||
|
||||
The day may hold multiple workouts; return True if ANY of today's entries
|
||||
verifies (or is acceptably unsigned when no HMAC key is configured).
|
||||
"""
|
||||
entries = load_workout_log(log_file).get(today or _today_str(), [])
|
||||
if not entries:
|
||||
return False
|
||||
key_unavailable = compute_entry_hmac({"_probe": True}) is None
|
||||
for entry in entries:
|
||||
if verify_entry_hmac(entry):
|
||||
return True
|
||||
if key_unavailable and "hmac" not in entry:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned entry")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for today's log entries")
|
||||
return False
|
||||
|
||||
|
||||
def is_early_bird_pending(pending_file: Path, *, today: str | None = None) -> bool:
|
||||
"""Return True if today has an unresolved early-bird pending marker."""
|
||||
if not pending_file.exists():
|
||||
return False
|
||||
try:
|
||||
with pending_file.open() as f:
|
||||
state = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read the early-bird pending marker at %s: %s — treating "
|
||||
"it as not pending, so the lock chain proceeds as if no early bird "
|
||||
"was claimed today",
|
||||
pending_file,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if not isinstance(state, dict) or state.get("date") != (today or _today_str()):
|
||||
return False
|
||||
if verify_entry_hmac(state):
|
||||
return True
|
||||
if compute_entry_hmac({"_probe": True}) is None and "hmac" not in state:
|
||||
_logger.info("HMAC key unavailable — accepting unsigned pending marker")
|
||||
return True
|
||||
_logger.warning("HMAC verification failed for early-bird pending marker")
|
||||
return False
|
||||
|
||||
|
||||
def is_sick_day_today(history: SickHistory, *, today: str | None = None) -> bool:
|
||||
"""Return True if today is recorded as a sick day.
|
||||
|
||||
Thin wrapper around ``_sick_tracker.is_sick_day`` kept here so callers of
|
||||
the status layer have one predicate module to import from.
|
||||
"""
|
||||
return _is_sick_day(history, today=today)
|
||||
|
||||
|
||||
def _early_bird_window_open(*, extended: bool, local_minutes: int) -> bool:
|
||||
"""Deliberate, independent reimplementation of ``_is_early_bird_time``.
|
||||
|
||||
Not shared with ``EarlyBirdMixin._is_early_bird_time`` because too many
|
||||
existing tests are pinned to its ``_get_local_time_minutes`` patch point.
|
||||
Kept here as a small, separate, pure re-implementation for the status
|
||||
layer only — see the module docstring in ``_early_bird.py``.
|
||||
"""
|
||||
start = EARLY_BIRD_START_HOUR * 60
|
||||
end = 9 * 60 if extended else EARLY_BIRD_END_HOUR * 60 + EARLY_BIRD_END_MINUTE
|
||||
return start <= local_minutes < end
|
||||
|
||||
|
||||
def describe_auto_upgrade_opportunity(
|
||||
*,
|
||||
log_file: Path,
|
||||
weekly_minimum_met: bool,
|
||||
relaxed_day: bool,
|
||||
wake_skip: bool,
|
||||
evening_lockdown: bool,
|
||||
local_dt: datetime,
|
||||
pending: bool,
|
||||
) -> dict[str, bool]:
|
||||
"""Evaluate every predicate once; the keys are the ``_CHAIN`` step names."""
|
||||
today_str = local_day(local_dt)
|
||||
# The early-bird window IS the wake-alarm carrot (EarlyBirdMixin).
|
||||
return {
|
||||
"scheduled_skip": is_scheduled_skip_today(local_dt.date()),
|
||||
"early_bird_pending_expired": pending and not wake_skip,
|
||||
"early_bird_window_open": pending and wake_skip,
|
||||
"sick_day": is_sick_day_today(local_dt.date()),
|
||||
"already_logged": has_logged_today(log_file, today=today_str),
|
||||
"wake_alarm_skip": wake_skip,
|
||||
"test_hold_active": workout_hold_active(local_dt),
|
||||
"relaxed_day_already_skipped": relaxed_day
|
||||
and is_relaxed_day_skipped_today(log_file, today=today_str),
|
||||
"relaxed_day": relaxed_day,
|
||||
"weekly_minimum_met": weekly_minimum_met,
|
||||
"evening_lockdown_today": evening_lockdown,
|
||||
}
|
||||
early_bird_pending: bool,
|
||||
early_bird_window_open: bool,
|
||||
is_sick_day: bool,
|
||||
) -> AutoUpgradeOpportunity:
|
||||
"""Describe what the real ``_try_auto_upgrade_*`` methods would attempt.
|
||||
|
||||
Read-only stand-in for ``AutoUpgradeMixin._check_today_state_exits``'s
|
||||
branching — never calls phone/RunnerUp verification and never writes to
|
||||
``workout_log.json``.
|
||||
"""
|
||||
if early_bird_pending and not early_bird_window_open:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="early_bird_expired",
|
||||
reason=(
|
||||
"Early-bird window closed with no workout logged — the next "
|
||||
"lock run will try phone/RunnerUp verification before "
|
||||
"falling back to a full lock."
|
||||
),
|
||||
)
|
||||
if is_sick_day:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="sick_day",
|
||||
reason=(
|
||||
"Sick day logged — the next lock run will try phone/RunnerUp "
|
||||
"verification to upgrade it to a real workout."
|
||||
),
|
||||
)
|
||||
return _NO_UPGRADE
|
||||
|
||||
|
||||
def _walk_chain(
|
||||
fired: dict[str, bool], context: StageContext, degraded_note: str
|
||||
) -> LockExplanation | None:
|
||||
"""Record each step in ``context.trace``; return the first terminal one."""
|
||||
for step in _CHAIN:
|
||||
hit = fired[step.name]
|
||||
reason = step.reason_true if hit else step.reason_false
|
||||
if step.note_when_false and not hit:
|
||||
reason += degraded_note
|
||||
context.trace.append(PredicateResult(step.name, hit, reason))
|
||||
if hit and step.terminal_reason is not None:
|
||||
return _stage(
|
||||
fired=False,
|
||||
stage=step.name,
|
||||
reason=step.terminal_reason,
|
||||
context=context,
|
||||
)
|
||||
return None
|
||||
def _stage(
|
||||
*,
|
||||
fired: bool,
|
||||
stage: str,
|
||||
reason: str,
|
||||
trace: list[PredicateResult],
|
||||
auto_upgrade: AutoUpgradeOpportunity,
|
||||
) -> LockExplanation:
|
||||
"""Build a terminal :class:`LockExplanation` from the trace so far."""
|
||||
return LockExplanation(
|
||||
fired=fired,
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
trace=tuple(trace),
|
||||
auto_upgrade=auto_upgrade,
|
||||
heat_skip_evaluated=False,
|
||||
)
|
||||
|
||||
|
||||
def explain_lock_decision(
|
||||
*,
|
||||
log_file: Path,
|
||||
scheduled_skips_file: Path,
|
||||
early_bird_pending_file: Path,
|
||||
sick_history: SickHistory,
|
||||
extended_early_bird: bool,
|
||||
weekly_minimum_met: bool,
|
||||
relaxed_day: bool,
|
||||
wake_skip: bool = False,
|
||||
evening_lockdown: bool = False,
|
||||
now: datetime | None = None,
|
||||
degraded_sources: Sequence[DegradedSource] = (),
|
||||
) -> LockExplanation:
|
||||
"""Re-derive the lock-decision chain without ADB, sudo, or writes.
|
||||
|
||||
@ -213,36 +244,156 @@ def explain_lock_decision(
|
||||
order. Heat-skip is never evaluated (it needs a live ``wttr.in`` call) —
|
||||
reported via ``heat_skip_evaluated=False``, not guessed.
|
||||
"""
|
||||
instant = now if now is not None else datetime.now(tz=UTC)
|
||||
pending = is_early_bird_pending(early_bird_pending_file, today=local_day(instant))
|
||||
fired = _chain_flags(
|
||||
log_file=log_file,
|
||||
weekly_minimum_met=weekly_minimum_met,
|
||||
relaxed_day=relaxed_day,
|
||||
wake_skip=wake_skip,
|
||||
evening_lockdown=evening_lockdown,
|
||||
local_dt=instant.astimezone(),
|
||||
pending=pending,
|
||||
instant = now if now is not None else datetime.now(tz=timezone.utc)
|
||||
today_str = instant.astimezone(timezone.utc).strftime("%Y-%m-%d")
|
||||
local_dt = instant.astimezone()
|
||||
local_minutes = local_dt.hour * 60 + local_dt.minute
|
||||
|
||||
scheduled = is_scheduled_skip_today(scheduled_skips_file, today=today_str)
|
||||
pending = is_early_bird_pending(early_bird_pending_file, today=today_str)
|
||||
window_open = _early_bird_window_open(
|
||||
extended=extended_early_bird, local_minutes=local_minutes
|
||||
)
|
||||
expired = pending and not window_open
|
||||
early_bird_open_and_pending = pending and window_open
|
||||
window_end_label = "09:00" if extended_early_bird else "08:30"
|
||||
sick_today = is_sick_day_today(sick_history, today=today_str)
|
||||
logged = has_logged_today(log_file, today=today_str)
|
||||
|
||||
auto_upgrade = describe_auto_upgrade_opportunity(
|
||||
early_bird_pending=pending,
|
||||
early_bird_window_open=wake_skip,
|
||||
early_bird_window_open=window_open,
|
||||
is_sick_day=sick_today,
|
||||
)
|
||||
context = StageContext([], auto_upgrade, bool(degraded_sources))
|
||||
degraded_note = describe_degraded_sources(degraded_sources)
|
||||
terminal = _walk_chain(fired, context, degraded_note)
|
||||
if terminal is not None:
|
||||
return terminal
|
||||
|
||||
# Named for the conclusion; "..._pending_heat_check" read as "stuck".
|
||||
trace: list[PredicateResult] = []
|
||||
|
||||
def _check(
|
||||
name: str,
|
||||
*,
|
||||
fired: bool,
|
||||
reason_true: str,
|
||||
reason_false: str,
|
||||
terminal_reason: str | None = None,
|
||||
) -> LockExplanation | None:
|
||||
"""Record one trace step; return an explanation if it terminates the chain."""
|
||||
reason = reason_true if fired else reason_false
|
||||
trace.append(PredicateResult(name, fired, reason))
|
||||
if fired and terminal_reason is not None:
|
||||
return _stage(
|
||||
fired=False,
|
||||
stage=name,
|
||||
reason=terminal_reason,
|
||||
trace=trace,
|
||||
auto_upgrade=auto_upgrade,
|
||||
)
|
||||
return None
|
||||
|
||||
result = _check(
|
||||
"scheduled_skip",
|
||||
fired=scheduled,
|
||||
reason_true="Today is in scheduled_skips.json (unconditional manual skip).",
|
||||
reason_false="Today is not a manually scheduled skip day.",
|
||||
terminal_reason="Manually scheduled skip day — no lock, no workout required.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
# Recorded but never terminal on its own: an expired pending marker still
|
||||
# falls through toward a full lock, with the upgrade opportunity surfaced
|
||||
# separately via `auto_upgrade` (see module docstring).
|
||||
_check(
|
||||
"early_bird_pending_expired",
|
||||
fired=expired,
|
||||
reason_true="Logged in during the early-bird window and it has since closed "
|
||||
"with no workout confirmed yet.",
|
||||
reason_false="No expired early-bird pending marker.",
|
||||
)
|
||||
|
||||
result = _check(
|
||||
"early_bird_window_open",
|
||||
fired=early_bird_open_and_pending,
|
||||
reason_true="Logged in during the early-bird window earlier today; still "
|
||||
"waiting to see a workout before the window closes.",
|
||||
reason_false="Not pending inside an open early-bird window.",
|
||||
terminal_reason=(
|
||||
"Early-bird window still open — lock skipped while waiting for a workout."
|
||||
),
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"sick_day",
|
||||
fired=sick_today,
|
||||
reason_true="Today is marked as a sick day in sick_history.json.",
|
||||
reason_false="Today is not marked as a sick day.",
|
||||
terminal_reason="Sick day logged today — lock skipped.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"already_logged",
|
||||
fired=logged,
|
||||
reason_true="A validly-signed workout is already logged for today.",
|
||||
reason_false="No workout logged for today yet.",
|
||||
terminal_reason="Workout already logged today — lock skipped.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"wake_alarm_skip",
|
||||
fired=wake_skip,
|
||||
reason_true="Wake-alarm earned a workout skip for today.",
|
||||
reason_false="No wake-alarm workout skip earned today.",
|
||||
terminal_reason="Wake-alarm earned a workout skip — lock skipped.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"early_bird_time_fresh",
|
||||
fired=window_open,
|
||||
reason_true=(
|
||||
f"Currently inside the early-bird window (05:00-{window_end_label})."
|
||||
),
|
||||
reason_false="Not currently inside the early-bird window.",
|
||||
terminal_reason="Inside the early-bird window — lock skipped, pending marker "
|
||||
f"would be saved for the {window_end_label} re-check.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"relaxed_day",
|
||||
fired=relaxed_day,
|
||||
reason_true="Today is a relaxed day (Tue/Wed/Thu).",
|
||||
reason_false="Today is not a relaxed day.",
|
||||
terminal_reason="Relaxed day (Tue/Wed/Thu) — workout optional, lock skipped.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
result = _check(
|
||||
"weekly_minimum_met",
|
||||
fired=weekly_minimum_met,
|
||||
reason_true="Weekly workout minimum already reached.",
|
||||
reason_false="Weekly workout minimum not yet reached.",
|
||||
terminal_reason="Weekly workout minimum already met — lock skipped.",
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
return _stage(
|
||||
fired=True,
|
||||
stage="would_lock",
|
||||
stage="full_lock_pending_heat_check",
|
||||
reason=(
|
||||
"No skip condition applies, so a locker run starting now would "
|
||||
"lock. This page re-derives the decision only: no live "
|
||||
"temperature is checked, and a run may or may not be happening "
|
||||
"right now (see Health)." + degraded_note
|
||||
"No skip condition applies. The real locker still checks live "
|
||||
"Warsaw temperature before showing the full lock — not "
|
||||
"evaluated here."
|
||||
),
|
||||
context=context,
|
||||
trace=trace,
|
||||
auto_upgrade=auto_upgrade,
|
||||
)
|
||||
|
||||
@ -1,134 +0,0 @@
|
||||
"""Trace dataclasses and auto-upgrade description for the lock explanation.
|
||||
|
||||
Split out of :mod:`screen_locker._compliance_state` to keep every file under
|
||||
the 250-line cap. Re-exported from there, so existing imports and patch
|
||||
targets for the predicate functions are unchanged.
|
||||
|
||||
Nothing here touches ADB, sudo, subprocess, the network or the disk.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from screen_locker._degraded_sources import DegradedSource
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PredicateResult:
|
||||
"""One evaluated step in a :class:`LockExplanation` trace."""
|
||||
|
||||
name: str
|
||||
fired: bool
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoUpgradeOpportunity:
|
||||
"""Describes whether the real locker would attempt a live auto-upgrade."""
|
||||
|
||||
would_attempt: bool
|
||||
via: str # "early_bird_expired" | "none"
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LockExplanation:
|
||||
"""Read-only reconstruction of what the lock-decision chain would do."""
|
||||
|
||||
fired: bool
|
||||
stage: str
|
||||
reason: str
|
||||
trace: tuple[PredicateResult, ...]
|
||||
auto_upgrade: AutoUpgradeOpportunity
|
||||
heat_skip_evaluated: bool
|
||||
# True when a workout backend could not be read on this run, so "no
|
||||
# workout logged" is an absence of evidence rather than evidence of
|
||||
# absence. Defaulted so every existing construction site stays valid.
|
||||
sources_degraded: bool = False
|
||||
|
||||
|
||||
_NO_UPGRADE = AutoUpgradeOpportunity(
|
||||
would_attempt=False,
|
||||
via="none",
|
||||
reason="No pending auto-upgrade opportunity.",
|
||||
)
|
||||
|
||||
|
||||
def describe_auto_upgrade_opportunity(
|
||||
*,
|
||||
early_bird_pending: bool,
|
||||
early_bird_window_open: bool,
|
||||
) -> AutoUpgradeOpportunity:
|
||||
"""Describe what the real ``_try_auto_upgrade_*`` methods would attempt.
|
||||
|
||||
Read-only stand-in for ``AutoUpgradeMixin._check_today_state_exits``'s
|
||||
branching — never calls phone/RunnerUp verification and never writes to
|
||||
``log.json``.
|
||||
"""
|
||||
if early_bird_pending and not early_bird_window_open:
|
||||
return AutoUpgradeOpportunity(
|
||||
would_attempt=True,
|
||||
via="early_bird_expired",
|
||||
reason=(
|
||||
"Early-bird window closed with no workout logged — the next "
|
||||
"lock run will try phone/RunnerUp verification before "
|
||||
"falling back to a full lock."
|
||||
),
|
||||
)
|
||||
return _NO_UPGRADE
|
||||
|
||||
|
||||
def describe_degraded_sources(sources: Sequence[DegradedSource]) -> str:
|
||||
"""Return a clause naming the backends that could not be read, or "".
|
||||
|
||||
"No workout logged" is only trustworthy when every backend answered. On
|
||||
2026-08-24 Firebase was unreadable and the phone had already stopped
|
||||
writing to the GitHub mirror, so an empty log was reported as though the
|
||||
user had simply not trained -- and a screen was locked after a two-hour
|
||||
session. Naming the dark source turns that verdict into a question.
|
||||
"""
|
||||
if not sources:
|
||||
return ""
|
||||
named = ", ".join(f"{src.name} ({src.reason})" for src in sources)
|
||||
return (
|
||||
f" Could not read: {named} — a workout logged there would be "
|
||||
"invisible here, so this is 'unverified', not 'no workout'."
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StageContext:
|
||||
"""The parts of a terminal stage that outlive a single predicate.
|
||||
|
||||
Bundled into one object rather than passed as loose keywords: the trace
|
||||
and the two run-wide flags travel together through every call site, and
|
||||
threading them separately pushed ``_stage`` past the argument limit.
|
||||
"""
|
||||
|
||||
trace: list[PredicateResult]
|
||||
auto_upgrade: AutoUpgradeOpportunity
|
||||
sources_degraded: bool = False
|
||||
|
||||
|
||||
def _stage(
|
||||
*,
|
||||
fired: bool,
|
||||
stage: str,
|
||||
reason: str,
|
||||
context: StageContext,
|
||||
) -> LockExplanation:
|
||||
"""Build a terminal :class:`LockExplanation` from the trace so far."""
|
||||
return LockExplanation(
|
||||
fired=fired,
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
trace=tuple(context.trace),
|
||||
auto_upgrade=context.auto_upgrade,
|
||||
heat_skip_evaluated=False,
|
||||
sources_degraded=context.sources_degraded,
|
||||
)
|
||||
@ -4,38 +4,40 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from gatelock import default_runtime_dir
|
||||
from gatelock.log_integrity import DEFAULT_HMAC_KEY_FILE
|
||||
|
||||
# Ephemeral runtime state (self-clears on reboot, same directory gatelock's
|
||||
# own Arbiter uses) -- not repo-tracked data, so it does not belong next to
|
||||
# log.json below.
|
||||
INSTANCE_LOCK_FILE = default_runtime_dir() / "screen_locker-instance.lock"
|
||||
|
||||
# Single-sourced from gatelock so the literal key path can't drift. The key is
|
||||
# root:root 0644 ON PURPOSE, never 0600: leetcode-guard, book-guard and
|
||||
# anki-guard run as user timers and sign their ledgers with it, and this
|
||||
# locker signs log.json, rest_days.json and the workout ledger as the user.
|
||||
# Nothing in this repo may chmod it; root ownership keeps it from being
|
||||
# replaced, which is what the signatures rely on.
|
||||
# Single-sourced from gatelock so the literal key path can't drift.
|
||||
HMAC_KEY_FILE = DEFAULT_HMAC_KEY_FILE
|
||||
# The workout ledger (earned_time.WORKOUT.ledger): one signed credit row per
|
||||
# verified RunnerUp TCX credit and per rest day, resolved at call time.
|
||||
WORKOUT_LEDGER_RELATIVE = Path(".local/share/workout_locker/ledger.json")
|
||||
SICK_LOCKOUT_SECONDS = 120 # base 2 minutes wait when sick (escalates with usage)
|
||||
PHONE_PENALTY_DELAY_DEMO = 10
|
||||
PHONE_PENALTY_DELAY_PRODUCTION = 100
|
||||
# Penalty added to phone-penalty timer when ADB / phone unavailable
|
||||
# (so unplugging the phone does not become an easy path to the manual log).
|
||||
# (so unplugging phone does not become an easy escape into sick mode).
|
||||
NO_PHONE_EXTRA_LOCKOUT_SECONDS = 480 # extra 8 minutes on top of base
|
||||
# Manual (unverified) workout rate-limiting. Once either
|
||||
# Sick day rate-limiting (rolling windows). Once any window is exhausted
|
||||
# the "I'm sick" button disappears entirely.
|
||||
SICK_BUDGET_PER_7_DAYS = 1
|
||||
SICK_BUDGET_PER_30_DAYS = 3
|
||||
SICK_BUDGET_PER_90_DAYS = 10
|
||||
# Each sick day in the trailing 30 days doubles the wait countdown.
|
||||
SICK_LOCKOUT_MULTIPLIER_PER_RECENT = 2
|
||||
# Minimum chars in the freeform sick justification.
|
||||
SICK_JUSTIFICATION_MIN_CHARS = 120
|
||||
# How many past sick justifications to show on the dialog (read-only).
|
||||
SICK_HISTORY_REVIEW_COUNT = 10
|
||||
# Forced read-only delay before SUBMIT enables when a commitment was made.
|
||||
SICK_COMMITMENT_FORCED_READ_SECONDS = 5
|
||||
# Breaking a commitment counts as this many sick budget days.
|
||||
SICK_COMMITMENT_PENALTY_DAYS = 2
|
||||
# How long the commitment prompt stays visible after a workout unlock.
|
||||
COMMITMENT_PROMPT_TIMEOUT_SECONDS = 15
|
||||
# Manual (unverified) workout rate-limiting — looser than sick days since
|
||||
# activities like table tennis recur more often than illness. Once either
|
||||
# window is exhausted the "Log Manual Workout" option disappears entirely.
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS = 2
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS = 10
|
||||
# A manual workout may be logged AHEAD for a date up to this many days from
|
||||
# today (never a past date); it earns its credit on that date, not before.
|
||||
MANUAL_WORKOUT_MAX_DAYS_AHEAD = 7
|
||||
# Manual entries use the shared MIN_WORKOUT_DURATION_MINUTES bar below —
|
||||
# every workout type answers to the same minimum, whatever the sport.
|
||||
# Minimum start-to-end duration for a manual entry to be accepted.
|
||||
MANUAL_WORKOUT_MIN_DURATION_MINUTES = 20
|
||||
# Minimum chars for the "what was done" activity-details field.
|
||||
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS = 40
|
||||
# Minimum chars for each reflection field (what went well / to improve / feeling).
|
||||
@ -53,38 +55,18 @@ WORKOUT_APP_JSON_REMOTES = (
|
||||
)
|
||||
# Port the workout app's HTTP server listens on (no ADB/developer-options needed).
|
||||
WORKOUT_HTTP_PORT = 8765
|
||||
# The ONE duration bar every activity answers to — weightlifting, manual
|
||||
# entries, runs and walks (summed moving time) alike. This is the ADVERTISED
|
||||
# number: it is the only one that may ever appear in a message the user reads.
|
||||
MIN_WORKOUT_DURATION_MINUTES = 30
|
||||
# ...and this is the leeway that is deliberately INVISIBLE. A session is
|
||||
# actually accepted at MIN_WORKOUT_DURATION_MINUTES - this, so 25 minutes
|
||||
# passes while every string still says 30. That gap is intentional (the user
|
||||
# asked for it explicitly): do NOT "fix" the inconsistency by advertising the
|
||||
# real cutoff, and never interpolate WORKOUT_DURATION_ACCEPT_MINUTES into an
|
||||
# f-string.
|
||||
WORKOUT_DURATION_LEEWAY_MINUTES = 5
|
||||
# Derived so the advertised bar and the accept bar cannot drift apart.
|
||||
# Comparisons use this; messages use MIN_WORKOUT_DURATION_MINUTES. Every
|
||||
# caller compares with `>=` — one operator across all workout types, so a
|
||||
# 25.0-minute session cannot pass one gate and fail another.
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES = (
|
||||
MIN_WORKOUT_DURATION_MINUTES - WORKOUT_DURATION_LEEWAY_MINUTES
|
||||
)
|
||||
MIN_WORKOUT_DURATION_MINUTES = 60
|
||||
RUNNERUP_PACKAGES = ("org.runnerup", "org.runnerup.free")
|
||||
RUNNERUP_DB_SDCARD_TMP = "/sdcard/.runnerup_tmp_verification.db"
|
||||
# A day's activity (run or walk alike) qualifies on EITHER criterion — they are
|
||||
# an OR, not an AND. A short but long-lasting session counts, and so does a
|
||||
# fast 5 km that takes under the duration bar. Do not reinstate an AND here:
|
||||
# it would reject exactly the slow case this pair exists to allow. The
|
||||
# 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_DURATION_MINUTES = 30
|
||||
MIN_RUN_DISTANCE_KM = 5.0
|
||||
# GPS distance tracking undershoots on tight turns/tree cover/urban canyons;
|
||||
# a run within 5% of the minimum is accepted rather than rejected on
|
||||
# measurement noise. This is SEPARATE from WORKOUT_DURATION_LEEWAY_MINUTES:
|
||||
# that one is a deliberate concession to the user, this one corrects a
|
||||
# measurement error. Duration now gets a leeway too, but for the other reason.
|
||||
# measurement noise. Duration comes from the device clock, not GPS, so it
|
||||
# gets no such leeway.
|
||||
RUNNERUP_DISTANCE_TOLERANCE = 0.05
|
||||
RUNNERUP_ACCEPTED_SPORTS: frozenset[int] = frozenset({0, 3, 5})
|
||||
# 0=RUNNING, 3=ORIENTEERING, 5=TREADMILL
|
||||
MAX_CLOCK_SKEW_SECONDS = 300 # 5 minutes max time skew from NTP
|
||||
EARLY_BIRD_START_HOUR = 5
|
||||
EARLY_BIRD_END_HOUR = 8
|
||||
@ -94,62 +76,35 @@ HEAT_SKIP_CITY: str = "Warsaw"
|
||||
SHUTDOWN_CONFIG_FILE = Path("/etc/shutdown-schedule.conf")
|
||||
# Helper script path (relative to this file)
|
||||
ADJUST_SHUTDOWN_SCRIPT = Path(__file__).resolve().parent / "adjust_shutdown_schedule.sh"
|
||||
# State file to track sick day usage and original config values
|
||||
SICK_DAY_STATE_FILE = Path(__file__).resolve().parent / "sick_day_state.json"
|
||||
# Persistent sick-day history (rate-limit, debt, commitments, justifications).
|
||||
# Distinct from SICK_DAY_STATE_FILE which is a one-day shutdown-config snapshot.
|
||||
SICK_HISTORY_FILE = Path(__file__).resolve().parent / "sick_history.json"
|
||||
# JSON list of ISO date strings ("YYYY-MM-DD") for which the screen lock is skipped.
|
||||
SCHEDULED_SKIPS_FILE = Path(__file__).resolve().parent / "scheduled_skips.json"
|
||||
# State file tracking streak, skip credits, and early-bird extension weeks.
|
||||
EXTRA_BENEFITS_FILE = Path(__file__).resolve().parent / "extra_benefits_state.json"
|
||||
# State file storing the base (pre-bonus) shutdown hours and last reset date.
|
||||
SHUTDOWN_BASE_FILE = Path(__file__).resolve().parent / "shutdown_base.json"
|
||||
# HMAC-signed rest days, declared ahead (see _rest_day), and how far the grace
|
||||
# floor has lifted today's shutdown above the earned time (see _grace_floor).
|
||||
REST_DAY_FILE = Path(__file__).resolve().parent / "rest_days.json"
|
||||
REST_DAYS_PER_ISO_WEEK = 2
|
||||
GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json"
|
||||
# Every GPS activity (run or walk, whatever its TCX sport) is judged the same
|
||||
# way: a day's activities count as the workout once their summed distance
|
||||
# reaches MIN_RUN_DISTANCE_KM OR their summed MOVING time reaches
|
||||
# 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
|
||||
# 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
|
||||
# tombstones on every tick (see _sync_tombstones for why once is not enough).
|
||||
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"
|
||||
# Future-dated manual workouts logged on THIS PC, re-published on every push
|
||||
# until their date (see _manual_pending for why a one-shot publish is erased).
|
||||
MANUAL_PENDING_FILE = Path(__file__).resolve().parent / "manual_pending.json"
|
||||
# Self-expiring marker: "logged in during today's early-bird window, still
|
||||
# waiting to see if a real workout shows up." Not a log.json entry —
|
||||
# waiting to see if a real workout shows up." Not a workout_log.json entry —
|
||||
# it's a same-day pending flag, checked against its own "date" field.
|
||||
EARLY_BIRD_PENDING_FILE = Path(__file__).resolve().parent / "early_bird_pending.json"
|
||||
|
||||
# The PC's copy of the phone's morning session, written HMAC-signed by
|
||||
# wake-alarm (`python -m wake_alarm._session --refresh`, every 2 min through
|
||||
# the morning). Read here, never fetched: wake-alarm is the only Firebase
|
||||
# reader. XDG state rather than a sibling checkout, because the previous
|
||||
# reader pointed at "../wake_alarm/wake_state.json" -- a path that stopped
|
||||
# existing when the repos split -- and returned "no skip" for a year without
|
||||
# a single error. Keep the path in step with wake_alarm/_constants.py.
|
||||
MORNING_SESSION_FILE = (
|
||||
Path.home() / ".local" / "state" / "wake_alarm" / "morning_session.json"
|
||||
)
|
||||
|
||||
# A separate file from MORNING_SESSION_FILE: that one always describes
|
||||
# *today* and is overwritten at the date rollover, so it cannot carry a
|
||||
# marker forward to tomorrow. wake-alarm writes this one when a Tue/Wed/Thu
|
||||
# ring goes unanswered; today == penalty_date means today's relaxed-day
|
||||
# leniency is off. Keep the path in step with wake_alarm/_constants.py.
|
||||
WORKDAY_PENALTY_FILE = (
|
||||
Path.home() / ".local" / "state" / "wake_alarm" / "workday_penalty.json"
|
||||
# ---------------------------------------------------------------------------
|
||||
# Wake-alarm integration (originally from wake_alarm._constants / _state).
|
||||
# These must match the values used by the companion wake_alarm service.
|
||||
# ---------------------------------------------------------------------------
|
||||
# Days on which the wake alarm fires (0=Mon … 6=Sun).
|
||||
ALARM_DAYS: frozenset[int] = frozenset({0, 4, 5, 6})
|
||||
# How many hours after midnight the alarm triggers (configurable in wake_alarm).
|
||||
WAKE_AFTER_HOURS: int = 8
|
||||
# Path to the rtcwake binary.
|
||||
RTCWAKE_BIN: str = "/usr/sbin/rtcwake"
|
||||
# State file written by wake_alarm; read here to check for workout skip.
|
||||
WAKE_STATE_FILE = (
|
||||
Path(__file__).resolve().parent.parent / "wake_alarm" / "wake_state.json"
|
||||
)
|
||||
|
||||
# Directories where RunnerUp writes per-activity TCX exports (File Synchronizer).
|
||||
@ -159,55 +114,24 @@ RUNNERUP_EXPORT_DIRS: tuple[str, ...] = (
|
||||
"/storage/emulated/0/Documents/RunnerUp",
|
||||
)
|
||||
|
||||
# Where RunnerUp's WebDAV synchroniser drops the same exports on this machine
|
||||
# (dufs, see ~/src/dufs-cloud), and where endurain-import moves them once
|
||||
# Endurain has them. Read straight off the disk, so a run is credited without
|
||||
# the phone being adb-reachable -- on 2026-09-16 the TCX landed here at 20:08
|
||||
# and the phone was only plugged in at 20:25. Same filenames as the phone
|
||||
# export, optionally prefixed with the device name (RunnerUp_Pixel_6a_...).
|
||||
RUNNERUP_WEBDAV_DIRS: tuple[Path, ...] = (
|
||||
Path.home() / "data" / "cloud" / "RunnerUp",
|
||||
Path.home() / "data" / "cloud" / "RunnerUp" / "processed",
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync (phone workout data) — built on the shared crdt-sync library, Firebase
|
||||
# RTDB only since 2026-10-09 (the shared ~/.config/crdt-sync/ credential). The
|
||||
# old GitHub repo kuhyx/syncs/screen-locker-sync is a frozen archive: nothing
|
||||
# reads or writes it. Every device pushes to devices/<device id>/log.json; the
|
||||
# PC reads every device's log and pushes its OWN workouts (see _manual_push).
|
||||
# Sync (phone workout data) — Workstream C, built on the shared crdt-sync
|
||||
# library. GitHub is used purely as dumb file storage via the REST Contents
|
||||
# API (not a git clone), same pattern as diet_guard's cross-device sync. The
|
||||
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC reads
|
||||
# every device's log and pushes its OWN manual workouts to devices/pc/log.json
|
||||
# (see _manual_push) — which needs a token with contents:write, not read-only.
|
||||
# ---------------------------------------------------------------------------
|
||||
# The phone's pre-uuid device id. Still read (the phone may not have migrated
|
||||
# yet), but no longer the only path the reader knows about -- it discovers
|
||||
# every device directory.
|
||||
SYNC_REPO_OWNER: str = "kuhyx"
|
||||
SYNC_REPO_NAME: str = "syncs"
|
||||
SYNC_PHONE_DEVICE_ID: str = "phone"
|
||||
# The id this machine pushed manual workouts under before per-install uuids.
|
||||
# Kept so the sync layer still recognises devices/pc/ as its own and does not
|
||||
# re-merge its own history as a peer's; drop to None once that path is gone.
|
||||
SYNC_LEGACY_DEVICE_ID: str | None = "pc"
|
||||
# This machine's sync id, minted once and persisted. A fixed "pc" collides as
|
||||
# soon as a second machine takes the same role, and a reinstall would inherit
|
||||
# the previous install's CRDT identity.
|
||||
SYNC_DEVICE_ID_FILE: Path = (
|
||||
Path.home() / ".local" / "share" / "screen_locker" / ".device_id"
|
||||
)
|
||||
# Revision cache for cross-device sync. Without it every push re-uploads and
|
||||
# every pull re-downloads regardless of change, which is the traffic the
|
||||
# Firebase free tier's monthly budget depends on not happening.
|
||||
SYNC_STATE_FILE: Path = (
|
||||
Path.home() / ".local" / "share" / "screen_locker" / "sync_state.json"
|
||||
)
|
||||
# A fine-grained GitHub PAT, scoped to just SYNC_REPO_NAME's contents. The
|
||||
# user creates this once via github.com and saves it here, mode 600. Never
|
||||
# committed — this path is outside the repo entirely. Unlike diet_guard,
|
||||
# this file being absent is a normal, expected state (sync is optional here).
|
||||
SYNC_TOKEN_FILE: Path = Path.home() / ".config" / "screen_locker" / "sync_token"
|
||||
SYNC_TIMEOUT_SECONDS: float = 10.0
|
||||
|
||||
# Published while the locker has DECIDED to lock but is waiting for a
|
||||
# higher-ranked holder (wake_alarm) to release the screen. From outside the
|
||||
# process that state is indistinguishable from a hang: on 2026-08-30 the
|
||||
# locker sat in gatelock's queue for 2h58m and the only evidence anywhere was
|
||||
# a single INFO line at the moment it started waiting.
|
||||
QUEUE_STATE_FILE: Path = (
|
||||
Path.home() / ".local" / "share" / "screen_locker" / "queue_state.json"
|
||||
)
|
||||
|
||||
# Sync runs from the morning routine, which is started right after boot and
|
||||
# right after resume — often seconds before networking is actually up. Such a
|
||||
# run used to fail outright, and reported it as a permissions problem
|
||||
|
||||
@ -1,162 +0,0 @@
|
||||
"""Self-healing for a dead Firebase session, using credentials already here.
|
||||
|
||||
``crdt_sync`` caches a refresh token per app at
|
||||
``~/.config/<app>/firebase_auth.json`` and falls back to the shared password
|
||||
only when that cache is missing. On 2026-08-24 ``screen_locker`` had no cache
|
||||
and the shared password had gone stale, so every run failed with
|
||||
``INVALID_LOGIN_CREDENTIALS`` -- while ``diet_guard`` and ``wake_alarm`` sat
|
||||
in sibling directories holding live refresh tokens for the *same* account and
|
||||
the *same* project, refreshed minutes earlier.
|
||||
|
||||
Every app here signs in as one personal account against one project (see
|
||||
``~/.config/crdt-sync/firebase.json``), so any sibling's refresh token mints a
|
||||
valid session for us. That makes this recovery purely local: no password, no
|
||||
browser, no human. The alternative -- a person copying a JSON file between
|
||||
directories -- is a habit, not a fix, and habits are what failed twice.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import ConfigError, RemoteSyncError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_CACHE_NAME = "firebase_auth.json"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RecoveryResult:
|
||||
"""What a recovery attempt did, and why.
|
||||
|
||||
``reason`` always reads like a sentence: this runs unattended inside a
|
||||
systemd unit, so the journal line is the only thing a human will ever see.
|
||||
"""
|
||||
|
||||
recovered: bool
|
||||
reason: str
|
||||
donor: str | None = None
|
||||
|
||||
|
||||
def find_sibling_refresh_tokens(
|
||||
config_root: Path, *, skip: str
|
||||
) -> list[tuple[str, str]]:
|
||||
"""Return every ``(app_name, refresh_token)`` a sibling app has cached.
|
||||
|
||||
All of them, not just the first: the caches on this machine are of mixed
|
||||
vintages (some minted weeks apart), so the alphabetically-first donor is
|
||||
not necessarily a live one. Returning the whole list lets
|
||||
:func:`recover_session` try the next one instead of giving up on a single
|
||||
stale token -- the same "one dead source blocks the healthy ones" bug this
|
||||
module exists to fix, one level down.
|
||||
|
||||
Args:
|
||||
config_root: The directory holding per-app config dirs (``~/.config``).
|
||||
skip: Our own app name, whose cache is the thing being replaced.
|
||||
|
||||
Returns:
|
||||
Every usable sibling credential, in a stable order.
|
||||
"""
|
||||
if not config_root.is_dir():
|
||||
return []
|
||||
found: list[tuple[str, str]] = []
|
||||
for cache in sorted(config_root.glob(f"*/{_CACHE_NAME}")):
|
||||
app_name = cache.parent.name
|
||||
if app_name == skip:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(cache.read_text())
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
# One corrupt sibling must not hide the healthy ones behind it.
|
||||
_logger.warning(
|
||||
"Skipping unreadable credential cache %s: %s — continuing the "
|
||||
"search for another app's live refresh token",
|
||||
cache,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
token = data.get("refresh_token")
|
||||
if isinstance(token, str) and token:
|
||||
found.append((app_name, token))
|
||||
return found
|
||||
|
||||
|
||||
def recover_session(
|
||||
*,
|
||||
config_root: Path,
|
||||
app_name: str,
|
||||
mint: Callable[[str], None],
|
||||
) -> RecoveryResult:
|
||||
"""Rebuild our Firebase session from a sibling app's refresh token.
|
||||
|
||||
``mint`` is injected rather than imported so this module stays free of
|
||||
network code and the tests never reach Firebase.
|
||||
|
||||
Args:
|
||||
config_root: The directory holding per-app config dirs.
|
||||
app_name: Our app name, both the skip target and the cache we write.
|
||||
mint: Exchanges a refresh token for a session and persists it.
|
||||
"""
|
||||
candidates = find_sibling_refresh_tokens(config_root, skip=app_name)
|
||||
if not candidates:
|
||||
reason = (
|
||||
f"no sibling app under {config_root} holds a Firebase refresh "
|
||||
"token, so the session cannot be rebuilt locally — sign in once "
|
||||
"on this machine to seed one"
|
||||
)
|
||||
_logger.warning("Firebase recovery failed: %s", reason)
|
||||
return RecoveryResult(recovered=False, reason=reason)
|
||||
|
||||
rejections: list[str] = []
|
||||
donor = ""
|
||||
for candidate, refresh_token in candidates:
|
||||
try:
|
||||
mint(refresh_token)
|
||||
except (OSError, ValueError, RuntimeError, ConfigError, RemoteSyncError) as exc:
|
||||
# Keep going: a stale donor says nothing about the next one, and
|
||||
# stopping here is how a single expired sibling blocked a recovery
|
||||
# that several live credentials could have completed. Each
|
||||
# rejection is logged as it happens, so a donor that has quietly
|
||||
# gone stale is visible even on the runs that recover anyway.
|
||||
_logger.warning(
|
||||
"Sibling %s's refresh token was rejected (%s) — trying the "
|
||||
"next donor; %s should be reseeded",
|
||||
candidate,
|
||||
exc,
|
||||
candidate,
|
||||
)
|
||||
rejections.append(f"{candidate} ({exc})")
|
||||
continue
|
||||
donor = candidate
|
||||
break
|
||||
else:
|
||||
reason = "every sibling refresh token was rejected: " + ", ".join(rejections)
|
||||
_logger.warning("Firebase recovery failed: %s", reason)
|
||||
return RecoveryResult(recovered=False, reason=reason)
|
||||
|
||||
if rejections:
|
||||
_logger.warning(
|
||||
"Firebase recovery fell through to %s after %s was rejected — the "
|
||||
"earlier credential is stale and should be reseeded",
|
||||
donor,
|
||||
", ".join(rejections),
|
||||
)
|
||||
_logger.info(
|
||||
"Firebase session rebuilt for %s from %s's cached refresh token — no "
|
||||
"password or human step was needed",
|
||||
app_name,
|
||||
donor,
|
||||
)
|
||||
return RecoveryResult(
|
||||
recovered=True,
|
||||
reason=f"rebuilt the session from {donor}'s cached refresh token",
|
||||
donor=donor,
|
||||
)
|
||||
@ -1,35 +0,0 @@
|
||||
"""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
|
||||
@ -1,106 +0,0 @@
|
||||
"""Desktop notification the moment a workout earns its credit.
|
||||
|
||||
The reward is the point: a workout should be *felt* as paid the second the PC
|
||||
credits it, not discovered at the next look at the status window. Every path
|
||||
that credits a workout ends in
|
||||
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`,
|
||||
which calls :func:`notify_workout_credit` once per newly earned credit slot.
|
||||
|
||||
The body shows the shutdown only: the gaming budget is gone (earned_time
|
||||
0.22.0), so there is no second figure to feel.
|
||||
|
||||
A notification is a courtesy, never part of crediting: any failure (no DBus,
|
||||
no notify-send, a hang) is logged at warning and swallowed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Final
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._earned import hhmm, span
|
||||
from screen_locker._grace_floor import tonight_minutes
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
def credit_body(
|
||||
before: tuple[int, int, int] | None,
|
||||
after: tuple[int, int, int] | None,
|
||||
reward: int | None = None,
|
||||
) -> str:
|
||||
"""``⏻ 23:00 (+2h)`` -- whichever parts are known.
|
||||
|
||||
``before``/``after`` are the shutdown config around the credit. The delta
|
||||
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] = []
|
||||
if after is None:
|
||||
_logger.warning(
|
||||
"Shutdown config unreadable after a workout credit — the "
|
||||
"notification shows no shutdown time"
|
||||
)
|
||||
else:
|
||||
day = date.fromisoformat(today_str())
|
||||
tonight = tonight_minutes(after, day)
|
||||
text = f"{_SHUTDOWN} {hhmm(tonight)}"
|
||||
if before is not None:
|
||||
moved = max(0, tonight - tonight_minutes(before, day))
|
||||
if reward is not None:
|
||||
moved = min(moved, reward)
|
||||
text += f" (+{span(moved)})"
|
||||
parts.append(text)
|
||||
return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
|
||||
|
||||
|
||||
def send_notification(title: str, body: str) -> bool:
|
||||
"""Show a desktop notification via ``notify-send``; False (logged) on failure."""
|
||||
binary = shutil.which("notify-send")
|
||||
if binary is None:
|
||||
_logger.warning("notify-send not found — no desktop notification: %s", body)
|
||||
return False
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[binary, "--app-name=screen-locker", title, body],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_NOTIFY_TIMEOUT_SECONDS,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
_logger.warning("Desktop notification failed (%s): %s", exc, body)
|
||||
return False
|
||||
if result.returncode:
|
||||
_logger.warning(
|
||||
"notify-send exited %d (%s) — no desktop notification: %s",
|
||||
result.returncode,
|
||||
result.stderr.strip() or "no stderr; is a DBus session reachable?",
|
||||
body,
|
||||
)
|
||||
return False
|
||||
_logger.info("Desktop notification: %s — %s", title, body)
|
||||
return True
|
||||
|
||||
|
||||
def notify_workout_credit(
|
||||
before: tuple[int, int, int] | None,
|
||||
after: tuple[int, int, int] | None,
|
||||
reward: int | None,
|
||||
) -> bool:
|
||||
"""Notify a newly earned workout credit. Never raises."""
|
||||
body = credit_body(before, after, reward)
|
||||
return send_notification(TITLE, body)
|
||||
@ -1,86 +0,0 @@
|
||||
"""Which credit a newly written workout earns, decided by slot like the reset.
|
||||
|
||||
The live credit path used to ask "was any counted workout already logged
|
||||
today?" -- so the two StrongLifts ingestion paths of ONE session
|
||||
(``pc_workout_verified`` from the session sync, ``phone_verified`` from the
|
||||
early-bird auto-upgrade) earned the first-unit +2h and then a further-unit +1h
|
||||
(2026-10-09; also 07-17 and 07-27 in ``duplicate_credits.json``). The daily
|
||||
reset counts the same day with :func:`~screen_locker._weekly_check.count_day_credits`,
|
||||
which collapses them onto one slot. Deciding the live credit with that same
|
||||
counter makes the two agree by construction.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack, contextmanager
|
||||
import enum
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from screen_locker._bonus_lock import bonus_lock
|
||||
from screen_locker._weekly_check import count_day_credits
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
# count_day_credits only uses the date to build slot keys, and both counts
|
||||
# below are taken over the same day, so any fixed label is equivalent.
|
||||
_SAME_DAY: Final = "day"
|
||||
|
||||
|
||||
class CreditSlot(enum.Enum):
|
||||
"""What the newest entry of a day earns."""
|
||||
|
||||
NONE = "earns no credit (not a counted workout type)"
|
||||
FIRST = "first credit slot of the day"
|
||||
FURTHER = "a new, distinct credit slot after the first"
|
||||
OCCUPIED = "a slot an earlier entry of the day already credited"
|
||||
|
||||
|
||||
def credit_slot(
|
||||
prior_entries: list[dict[str, Any]], workout_data: Mapping[str, Any]
|
||||
) -> CreditSlot:
|
||||
"""Classify ``workout_data`` against the day's entries written before it.
|
||||
|
||||
Args:
|
||||
prior_entries: The day's log entries before the new one, as returned
|
||||
by the write chokepoint (snapshotted under the log lock).
|
||||
workout_data: The new entry's ``workout_data``.
|
||||
"""
|
||||
new_entry = {"workout_data": dict(workout_data)}
|
||||
day = [e for e in prior_entries if isinstance(e, dict)]
|
||||
before = count_day_credits(_SAME_DAY, day)
|
||||
with_new = count_day_credits(_SAME_DAY, [*day, new_entry])
|
||||
if with_new == before:
|
||||
# No new slot: either it earns nothing at all, or its slot is taken.
|
||||
return CreditSlot.OCCUPIED if _counts_alone(new_entry) else CreditSlot.NONE
|
||||
return CreditSlot.FURTHER if before else CreditSlot.FIRST
|
||||
|
||||
|
||||
def _counts_alone(entry: Mapping[str, Any]) -> bool:
|
||||
"""Whether ``entry`` would earn a credit on an otherwise empty day."""
|
||||
return count_day_credits(_SAME_DAY, [entry]) == 1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_shutdown_state(state_file: Path) -> Iterator[None]:
|
||||
"""Hold :func:`bonus_lock` on ``state_file``; on failure, warn and go on.
|
||||
|
||||
The reset and the flat-bonus pass hold the same lock, so a credit can no
|
||||
longer lose its minutes to their read-add-write. Never nest inside them:
|
||||
a second flock on a new fd in the same process deadlocks.
|
||||
"""
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
stack.enter_context(bonus_lock(state_file))
|
||||
except OSError as exc:
|
||||
_logger.warning(
|
||||
"Could not lock %s (%s) — applying the workout credit without "
|
||||
"it; a reset running at the same moment could overwrite it",
|
||||
state_file,
|
||||
exc,
|
||||
)
|
||||
yield
|
||||
@ -1,117 +0,0 @@
|
||||
"""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()
|
||||
@ -1,32 +0,0 @@
|
||||
"""The one definition of "what day is it" for every day-keyed file.
|
||||
|
||||
``log.json``, ``early_bird_pending.json`` and ``wake_state.json`` are all
|
||||
keyed by ``YYYY-MM-DD``.
|
||||
Until 2026-09-13 each writer and reader derived that key on its own, and
|
||||
most of them used ``datetime.now(tz=UTC)`` while the lock window, the phone
|
||||
app, RunnerUp verification and the status window used LOCAL time. In CEST
|
||||
that is a two-hour window after local midnight in which a workout logged
|
||||
"today" was filed under yesterday — the lock check then looked for today,
|
||||
found nothing, and locked the PC for a workout that was on disk.
|
||||
|
||||
The day is the **local calendar day**: it is what the user sees on the
|
||||
clock when they log, what the lock screen names when it says "no workout
|
||||
for today", and what the phone already writes. Every module goes through
|
||||
:func:`today_str` so the two can never disagree again; tests freeze the
|
||||
clock by patching ``screen_locker._day.datetime``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
def today_str(now: datetime | None = None) -> str:
|
||||
"""Return the local calendar day of *now* (default: this instant) as ``YYYY-MM-DD``.
|
||||
|
||||
*now* may be in any timezone; it is converted to the machine's local zone
|
||||
first, which is the only conversion that turns ``22:02Z`` on the 12th
|
||||
into the 13th the user actually logged on.
|
||||
"""
|
||||
instant = now if now is not None else datetime.now(tz=UTC)
|
||||
return instant.astimezone().strftime("%Y-%m-%d")
|
||||
@ -1,243 +0,0 @@
|
||||
"""One structured, durable record of every lock decision the locker makes.
|
||||
|
||||
This module exists because of a multi-day outage that produced *no evidence*.
|
||||
Between 2026-08-04 and 2026-08-17 the locker stopped enforcing, and the only
|
||||
trace in the journal was its absence: ``workout-locker.service`` started, ran
|
||||
for six seconds, exited ``0/SUCCESS``, and said nothing about why. Every
|
||||
early-exit reason was logged at ``INFO``, and ``logging.basicConfig`` was only
|
||||
ever called on the ``--sync-only`` path, so ``--production`` emitted no INFO at
|
||||
all -- zero such lines since June.
|
||||
|
||||
Two things follow from that, and this module provides both:
|
||||
|
||||
* **A single grep-able line per run.** ``DECISION lock=no reason=... weekly=0/5``
|
||||
is one line a human or an agent can find without knowing the code, and it is
|
||||
emitted at ``WARNING`` when enforcement was skipped, because per CLAUDE.md an
|
||||
``INFO``-level explanation of a non-action is a silent failure with extra
|
||||
steps.
|
||||
* **A durable JSONL trail.** The journal rotates and is per-boot; a decision
|
||||
history that outlives it is what makes "when did this last actually enforce?"
|
||||
answerable in one command instead of a forensic session.
|
||||
|
||||
The file is deliberately outside the repo (see ``DECISION_LOG_FILE``): the
|
||||
2026-07 privacy incident purged workout state JSONs from git history, and they
|
||||
must never be re-tracked.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._armed_state import locker_unit_active
|
||||
from screen_locker._decision_trail import (
|
||||
DECISION_LOG_FILE,
|
||||
DECISION_LOG_MAX_ENTRIES,
|
||||
append_record,
|
||||
)
|
||||
from screen_locker._queue_state import read_queue_wait
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"DECISION_LOG_FILE",
|
||||
"DECISION_LOG_MAX_ENTRIES",
|
||||
"LockDecision",
|
||||
"read_decisions",
|
||||
"record_decision",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Both live in _decision_trail (which owns the writer) and are re-exported
|
||||
# here, where every reader already looks for them.
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LockDecision:
|
||||
"""Why the locker did or did not enforce on one run.
|
||||
|
||||
``reason`` is a stable machine-readable slug (``early_bird_pending``,
|
||||
``weekly_minimum_met``, ``enforced``...), not prose, so it can be grepped
|
||||
and counted across runs. ``detail`` carries the human sentence.
|
||||
"""
|
||||
|
||||
locked: bool
|
||||
reason: str
|
||||
detail: str = ""
|
||||
weekly_count: int | None = None
|
||||
weekly_required: int | None = None
|
||||
extra: dict[str, object] = field(default_factory=dict)
|
||||
|
||||
def as_line(self) -> str:
|
||||
"""Render the single grep-able summary line.
|
||||
|
||||
Keys are ``key=value`` pairs so the line stays readable by eye and
|
||||
parseable by ``awk``/``grep -o`` without a JSON decoder.
|
||||
"""
|
||||
parts = [
|
||||
"DECISION",
|
||||
f"lock={'yes' if self.locked else 'no'}",
|
||||
f"reason={self.reason}",
|
||||
]
|
||||
if self.weekly_required is not None:
|
||||
parts.append(f"weekly={self.weekly_count}/{self.weekly_required}")
|
||||
for key, value in self.extra.items():
|
||||
parts.append(f"{key}={value}")
|
||||
if self.detail:
|
||||
parts.append(f"detail={self.detail!r}")
|
||||
return " ".join(parts)
|
||||
|
||||
def as_record(self) -> dict[str, object]:
|
||||
"""Render the durable JSON object written to the trail."""
|
||||
record: dict[str, object] = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"locked": self.locked,
|
||||
"reason": self.reason,
|
||||
}
|
||||
if self.detail:
|
||||
record["detail"] = self.detail
|
||||
if self.weekly_required is not None:
|
||||
record["weekly_count"] = self.weekly_count
|
||||
record["weekly_required"] = self.weekly_required
|
||||
record.update(self.extra)
|
||||
return record
|
||||
|
||||
|
||||
def record_decision(decision: LockDecision, *, log_file: Path | None = None) -> None:
|
||||
"""Log ``decision`` to the journal and append it to the durable trail.
|
||||
|
||||
Never raises: a failure to *record* why the locker acted must not stop the
|
||||
locker from acting. A write failure is reported at ``warning`` rather than
|
||||
swallowed, so the recording gap is itself visible.
|
||||
"""
|
||||
line = decision.as_line()
|
||||
# Not-enforcing is the state that hid the outage, so it is the state that
|
||||
# gets the louder level. An enforced lock is self-evident on screen.
|
||||
if decision.locked:
|
||||
_logger.info("%s", line)
|
||||
else:
|
||||
_logger.warning("%s", line)
|
||||
|
||||
append_record(decision.as_record(), log_file=log_file)
|
||||
|
||||
|
||||
def record_no_decision(mode: str, *, log_file: Path | None = None) -> None:
|
||||
"""Note that a run finished WITHOUT evaluating the lock at all.
|
||||
|
||||
``--sync-only`` and ``--status`` never reach the decision ladder. Recording
|
||||
that explicitly is what keeps the trail honest: during the outage the
|
||||
journal was full of healthy 15-minute sync runs, which made the system look
|
||||
alive while no enforcement decision had been made for days. "This run did
|
||||
not decide" and "this run decided not to lock" must never look alike.
|
||||
|
||||
Written at ``info`` because these modes run constantly and are expected;
|
||||
the durable trail is what makes them auditable, not the log level.
|
||||
"""
|
||||
# What the LOCKER was doing at this moment rides along. systemd cannot
|
||||
# start a second instance of an already-active Type=simple unit, so on
|
||||
# 2026-08-30 the 09:30-14:00 timer triggers were silent no-ops and the
|
||||
# only records in that window were these sync lines -- which said nothing
|
||||
# about the run that had decided to lock at 09:01 and was still waiting.
|
||||
# This is the every-15-minutes heartbeat that already exists, so putting
|
||||
# the observation here needs no new unit in the enforcement path.
|
||||
locker = locker_unit_active()
|
||||
waiting = read_queue_wait()
|
||||
_logger.info(
|
||||
"DECISION lock=n/a reason=mode_makes_no_decision mode=%s "
|
||||
"locker_running=%s%s — this mode never evaluates the lock",
|
||||
mode,
|
||||
"unknown" if locker is None else locker,
|
||||
(
|
||||
f" queued_behind={','.join(waiting.get('blocked_by', []))}"
|
||||
if waiting
|
||||
else ""
|
||||
),
|
||||
)
|
||||
record: dict[str, object] = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"locked": None,
|
||||
"reason": "mode_makes_no_decision",
|
||||
"mode": mode,
|
||||
"locker_running": locker,
|
||||
}
|
||||
if waiting:
|
||||
record["queued_behind"] = waiting.get("blocked_by", [])
|
||||
append_record(record, log_file=log_file)
|
||||
|
||||
|
||||
def record_run_aborted(
|
||||
reason: str, detail: str, *, log_file: Path | None = None
|
||||
) -> None:
|
||||
"""Note that a run could not reach the decision ladder at all.
|
||||
|
||||
Distinct from :func:`record_no_decision`, which covers modes that are
|
||||
*designed* never to decide. This covers a run that meant to decide and
|
||||
could not -- the case that produced the 2026-08-30 restart loop, where
|
||||
1695 runs died before recording anything and the only evidence was a
|
||||
stack trace in the journal.
|
||||
|
||||
Written at ``warning``: unlike the sync modes, this is never expected.
|
||||
|
||||
Args:
|
||||
reason: Machine-readable slug for the trail.
|
||||
detail: One human sentence about what was missing.
|
||||
log_file: Override for the trail path (for testing).
|
||||
"""
|
||||
_logger.warning(
|
||||
"DECISION lock=n/a reason=%s — %s",
|
||||
reason,
|
||||
detail,
|
||||
)
|
||||
append_record(
|
||||
{
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"locked": None,
|
||||
"reason": reason,
|
||||
"detail": detail,
|
||||
},
|
||||
log_file=log_file,
|
||||
)
|
||||
|
||||
|
||||
def read_decisions(*, log_file: Path | None = None) -> list[dict[str, object]]:
|
||||
"""Return the recorded decisions, oldest first.
|
||||
|
||||
Corrupt lines are skipped with a warning rather than aborting the read: a
|
||||
partially damaged trail is still worth far more than no trail.
|
||||
"""
|
||||
target = DECISION_LOG_FILE if log_file is None else log_file
|
||||
try:
|
||||
raw = target.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
# Genuinely benign and expected before the first run ever records a
|
||||
# decision, but still said out loud: "no history" and "history I could
|
||||
# not read" must never look the same to whoever is investigating.
|
||||
_logger.warning(
|
||||
"No decision log at %s yet — no lock decision has been recorded "
|
||||
"on this machine (this is normal before the first locker run)",
|
||||
target,
|
||||
)
|
||||
return []
|
||||
except OSError as exc:
|
||||
_logger.warning("Could not read the decision log at %s (%s)", target, exc)
|
||||
return []
|
||||
|
||||
records: list[dict[str, object]] = []
|
||||
for line in raw.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
_logger.warning("Skipping a corrupt decision-log line (%s)", exc)
|
||||
continue
|
||||
if isinstance(parsed, dict):
|
||||
records.append(parsed)
|
||||
else:
|
||||
_logger.warning("Skipping a decision-log line that is not an object")
|
||||
return records
|
||||
@ -1,74 +0,0 @@
|
||||
"""Collect *every* condition that bears on a lock decision, not just the first.
|
||||
|
||||
The decision ladders in ``_auto_upgrade`` and ``_startup_checks`` are
|
||||
first-match-wins: the branch that matches calls ``sys.exit(0)``, so every
|
||||
later condition is never evaluated and never recorded. That made a line like
|
||||
|
||||
DECISION lock=no reason=early_bird_window_active
|
||||
|
||||
ambiguous in the one way that matters: it cannot say whether the workout was
|
||||
*also* already done. A reader seeing only the early-bird reason cannot tell a
|
||||
deferred-but-compliant day from a deferred-and-idle one, which is precisely
|
||||
the question "was it right to skip?" that the decision log exists to answer.
|
||||
|
||||
So the acting reason stays exactly as it was -- it is the branch that actually
|
||||
controlled behaviour, and it stays a stable grep-able slug -- and this module
|
||||
supplies the *other* conditions that also held, as an ``also=`` extra.
|
||||
|
||||
Only side-effect-free predicates belong here. ``_try_auto_upgrade_*`` writes
|
||||
log entries and does ADB/network work, and ``_save_early_bird_pending`` writes
|
||||
state; calling any of those to produce a *log line* would turn a reporting
|
||||
change into a state mutation in the enforcer. Every predicate below is a pure
|
||||
read.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Mapping
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["collect_reasons", "reasons_extra"]
|
||||
|
||||
|
||||
def _holds(slug: str, predicate: Callable[[], bool]) -> bool:
|
||||
"""Return whether ``predicate`` holds, reporting rather than raising.
|
||||
|
||||
A predicate that fails is reported at ``warning`` and treated as not
|
||||
holding: this runs to *annotate* a decision, so a broken annotation must
|
||||
never take down the decision itself. Silence would defeat the point --
|
||||
a missing reason would otherwise read as a condition that did not hold.
|
||||
"""
|
||||
try:
|
||||
return predicate()
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not evaluate the '%s' condition while annotating a lock "
|
||||
"decision (%s) — it is omitted from this line, so treat its "
|
||||
"absence as unknown rather than false",
|
||||
slug,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def collect_reasons(predicates: Mapping[str, Callable[[], bool]]) -> list[str]:
|
||||
"""Return the slugs of every predicate that currently holds."""
|
||||
return [slug for slug, pred in predicates.items() if _holds(slug, pred)]
|
||||
|
||||
|
||||
def reasons_extra(
|
||||
acting: str, predicates: Mapping[str, Callable[[], bool]]
|
||||
) -> dict[str, object]:
|
||||
"""Build the ``also=`` extra for a decision whose acting reason is ``acting``.
|
||||
|
||||
Returns an empty mapping when nothing else applied, so a genuinely
|
||||
single-reason decision keeps rendering exactly the line it did before and
|
||||
no reader has to learn a new format for the common case.
|
||||
"""
|
||||
others = [slug for slug in collect_reasons(predicates) if slug != acting]
|
||||
return {"also": ",".join(others)} if others else {}
|
||||
@ -1,130 +0,0 @@
|
||||
"""Writing the durable decision trail, including repeat-collapsing.
|
||||
|
||||
Split out of ``_decision_log.py`` to keep every file under the 250-line cap.
|
||||
``_decision_log`` owns *what* a decision is and how it reads in the journal;
|
||||
this module owns how it lands on disk.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Outside the repo on purpose -- workout state is private and git-untracked.
|
||||
DECISION_LOG_FILE: Path = (
|
||||
Path.home() / ".local" / "share" / "screen_locker" / "decisions.jsonl"
|
||||
)
|
||||
|
||||
# Trimmed on write so the recurring timers cannot grow this without bound.
|
||||
# Writers are the 5-minute locker timer plus the 15-minute sync run (which
|
||||
# records "made no decision"). Consecutive identical records collapse into
|
||||
# one row, so a restart loop can no longer evict a month of history.
|
||||
DECISION_LOG_MAX_ENTRIES: Final[int] = 3000
|
||||
|
||||
|
||||
# Fields that differ between two recordings of the *same* event, and so must
|
||||
# not stop them collapsing into one row.
|
||||
_COLLAPSE_VOLATILE_KEYS = frozenset({"timestamp", "repeat_count", "last_timestamp"})
|
||||
|
||||
|
||||
def _is_repeat(previous_line: str, record: dict[str, object]) -> bool:
|
||||
"""Return whether ``record`` restates the event on ``previous_line``.
|
||||
|
||||
Everything but the timestamps and the repeat counter must match, so a
|
||||
change in ``weekly_count`` or ``detail`` still opens a new row -- only a
|
||||
genuinely identical event collapses.
|
||||
|
||||
Args:
|
||||
previous_line: The newest line already in the trail.
|
||||
record: The record about to be written.
|
||||
|
||||
Returns:
|
||||
True when the two describe the same event.
|
||||
"""
|
||||
try:
|
||||
previous = json.loads(previous_line)
|
||||
except json.JSONDecodeError as exc:
|
||||
# An unparsable tail is history we cannot compare against, so we keep
|
||||
# it and start a new row rather than overwrite it. Said out loud: a
|
||||
# corrupt trail is exactly the thing that must not stay quiet.
|
||||
_logger.warning(
|
||||
"Newest line of the decision trail is unparsable (%s) — starting "
|
||||
"a new row instead of collapsing into it, so nothing is lost",
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
if not isinstance(previous, dict):
|
||||
return False
|
||||
return {
|
||||
key: value
|
||||
for key, value in previous.items()
|
||||
if key not in _COLLAPSE_VOLATILE_KEYS
|
||||
} == {
|
||||
key: value
|
||||
for key, value in record.items()
|
||||
if key not in _COLLAPSE_VOLATILE_KEYS
|
||||
}
|
||||
|
||||
|
||||
def _trimmed(lines: list[str], record: dict[str, object]) -> list[str]:
|
||||
"""Return the retained history with ``record`` folded in.
|
||||
|
||||
Consecutive identical events collapse into one row carrying
|
||||
``repeat_count`` and ``last_timestamp`` instead of appending a new line.
|
||||
On 2026-08-30 a restart loop (no X server at 02:00, ``Restart=on-failure``
|
||||
every ~6s) wrote ~1693 identical ``enforced`` records in three hours and
|
||||
evicted the entire history behind them: the tool built to make blind spots
|
||||
impossible erased its own. Collapsing bounds any such storm to a single
|
||||
row, and does the same for the every-15-minutes ``--sync-only`` runs.
|
||||
|
||||
Args:
|
||||
lines: The existing trail, oldest first.
|
||||
record: The record to fold in.
|
||||
|
||||
Returns:
|
||||
The new trail, oldest first.
|
||||
"""
|
||||
if lines and _is_repeat(lines[-1], record):
|
||||
previous = json.loads(lines[-1])
|
||||
merged = {
|
||||
**record,
|
||||
# The FIRST sighting stays in `timestamp` so the row still says
|
||||
# when the streak began; readers wanting freshness use
|
||||
# `last_timestamp` (see _web_payload.decision_age_seconds).
|
||||
"timestamp": previous.get("timestamp", record["timestamp"]),
|
||||
"repeat_count": int(previous.get("repeat_count", 1)) + 1,
|
||||
"last_timestamp": record["timestamp"],
|
||||
}
|
||||
return [*lines[:-1], json.dumps(merged)]
|
||||
if len(lines) >= DECISION_LOG_MAX_ENTRIES:
|
||||
lines = lines[-(DECISION_LOG_MAX_ENTRIES - 1) :]
|
||||
return [*lines, json.dumps(record)]
|
||||
|
||||
|
||||
def append_record(record: dict[str, object], *, log_file: Path | None = None) -> None:
|
||||
"""Append one record to the durable trail, trimming old history.
|
||||
|
||||
Never raises: failing to *record* why the locker acted must not stop the
|
||||
locker from acting. A write failure is reported at ``warning`` rather than
|
||||
swallowed, so the gap in the trail is itself visible.
|
||||
"""
|
||||
target = DECISION_LOG_FILE if log_file is None else log_file
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
existing = (
|
||||
target.read_text(encoding="utf-8").splitlines() if target.exists() else []
|
||||
)
|
||||
kept = _trimmed([entry for entry in existing if entry.strip()], record)
|
||||
target.write_text("\n".join(kept) + "\n", encoding="utf-8")
|
||||
except OSError as exc:
|
||||
_logger.warning(
|
||||
"Could not append to the decision log at %s (%s) — this run's "
|
||||
"decision is in the journal only, so the durable trail now has a "
|
||||
"gap",
|
||||
target,
|
||||
exc,
|
||||
)
|
||||
@ -1,50 +0,0 @@
|
||||
"""Which workout backends could not be read on this run, and why.
|
||||
|
||||
Split out of :mod:`screen_locker._sync_client` to keep every file under the
|
||||
250-line cap. Re-exported from there, so existing importers and their patch
|
||||
targets are unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DegradedSource:
|
||||
"""A workout backend that could not be read on this run.
|
||||
|
||||
``reason`` is the backend's own error text, kept verbatim so the status
|
||||
view and the lock decision can quote something actionable rather than a
|
||||
generic "sync problem".
|
||||
"""
|
||||
|
||||
name: str
|
||||
reason: str
|
||||
|
||||
|
||||
# Process-scoped rather than persisted: it describes THIS run's ability to
|
||||
# read, and a stale marker from an earlier run would be worse than none. The
|
||||
# lock chain and the pull both happen in one process, so this survives exactly
|
||||
# as long as it is true.
|
||||
_degraded: list[DegradedSource] = []
|
||||
|
||||
|
||||
def degraded_sources() -> list[DegradedSource]:
|
||||
"""Return the backends that failed to answer during this run."""
|
||||
return list(_degraded)
|
||||
|
||||
|
||||
def clear_degraded_sources() -> None:
|
||||
"""Forget recorded failures (called at the start of a fresh check)."""
|
||||
_degraded.clear()
|
||||
|
||||
|
||||
def _record_degraded(name: str, reason: str) -> None:
|
||||
"""Note that *name* could not be read, so callers can stop guessing.
|
||||
|
||||
Logging alone was not enough: on 2026-08-24 the warning was emitted, the
|
||||
Firebase read was skipped, and the lock decision still reported
|
||||
"0 workouts this week" as though the source had answered "none".
|
||||
"""
|
||||
_degraded.append(DegradedSource(name, reason))
|
||||
@ -1,22 +0,0 @@
|
||||
"""This machine's persisted sync identity.
|
||||
|
||||
Its own module so both the manual-push writer (:mod:`screen_locker._manual_push`)
|
||||
and the workout reader (:mod:`screen_locker._workout_sync`) can resolve the id
|
||||
without importing each other.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from crdt_sync import DeviceIdentity, load_device_identity
|
||||
|
||||
from screen_locker._constants import SYNC_DEVICE_ID_FILE, SYNC_LEGACY_DEVICE_ID
|
||||
|
||||
|
||||
def device_identity() -> DeviceIdentity:
|
||||
"""Return this machine's sync identity, minting it on first use.
|
||||
|
||||
Deliberately not cached at import time: the id file is redirected
|
||||
per-test, and a module-level constant would freeze whichever value the
|
||||
first import happened to see.
|
||||
"""
|
||||
return load_device_identity(SYNC_DEVICE_ID_FILE, legacy_id=SYNC_LEGACY_DEVICE_ID)
|
||||
@ -2,55 +2,59 @@
|
||||
|
||||
The early-bird "still waiting to see if a real workout shows up" flag is a
|
||||
same-day pending marker, not a workout — it is intentionally kept out of
|
||||
log.json (which is reserved for real outcomes) and instead lives in
|
||||
workout_log.json (which is reserved for real outcomes) and instead lives in
|
||||
its own self-expiring, HMAC-signed state file, mirroring the pattern used by
|
||||
``wake_alarm._state`` in the companion wake-alarm service. It is written when
|
||||
the wake-alarm carrot defers the lock, so that when the carrot ends the next
|
||||
run tries a phone/RunnerUp workout before locking.
|
||||
``_wake_state.py`` for the companion wake_alarm service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
|
||||
from gatelock.log_integrity import compute_entry_hmac
|
||||
|
||||
from screen_locker._compliance_state import is_early_bird_pending
|
||||
from screen_locker._constants import EARLY_BIRD_PENDING_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._morning_session import MorningSkip, morning_skip_today
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_END_HOUR,
|
||||
EARLY_BIRD_END_MINUTE,
|
||||
EARLY_BIRD_PENDING_FILE,
|
||||
EARLY_BIRD_START_HOUR,
|
||||
EXTRA_BENEFITS_FILE,
|
||||
)
|
||||
from screen_locker._extra_benefits import has_extended_early_bird
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _today_str() -> str:
|
||||
"""Return today's LOCAL date as YYYY-MM-DD (see ``screen_locker._day``)."""
|
||||
return today_str()
|
||||
"""Return today's date as YYYY-MM-DD in UTC."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
class EarlyBirdMixin:
|
||||
"""Mixin providing the early-bird window check and pending-state helpers.
|
||||
"""Mixin providing early-bird time window checks and pending-state helpers."""
|
||||
|
||||
Since 2026-09-20 the window is not a wall clock but the wake-alarm
|
||||
morning-session carrot: open exactly while wake-alarm's signed
|
||||
``morning_session.json`` says the morning is being earned (before the
|
||||
alarm, during the session, and until 11:00 once it completed in time).
|
||||
The old 05:00-08:30 clock locked someone who got up at 07:00 -- the
|
||||
opposite of the goal -- and it was a second mechanism next to the one
|
||||
that actually knows whether the user is up.
|
||||
"""
|
||||
|
||||
_morning_skip: MorningSkip | None = None
|
||||
def _get_local_time_minutes(self) -> int:
|
||||
"""Return current local time as minutes from midnight."""
|
||||
now = datetime.now(tz=timezone.utc).astimezone()
|
||||
return now.hour * 60 + now.minute
|
||||
|
||||
def _is_early_bird_time(self) -> bool:
|
||||
"""Whether the wake-alarm carrot is in force right now.
|
||||
"""Return True if current local time is in the early bird window.
|
||||
|
||||
Waits (bounded) for a freshly booted PC's refresher; the verdict is
|
||||
kept on the instance so the skip detail can quote its ``exempt_until``.
|
||||
Normally the window closes at 08:30. When the current ISO week has an
|
||||
extended early-bird reward (earned by 5+ workouts the prior week) the
|
||||
window extends to 09:00.
|
||||
"""
|
||||
self._morning_skip = morning_skip_today(wait=True)
|
||||
return self._morning_skip is not None
|
||||
minutes = self._get_local_time_minutes()
|
||||
start = EARLY_BIRD_START_HOUR * 60
|
||||
if has_extended_early_bird(EXTRA_BENEFITS_FILE):
|
||||
end = 9 * 60 # 09:00
|
||||
else:
|
||||
end = EARLY_BIRD_END_HOUR * 60 + EARLY_BIRD_END_MINUTE
|
||||
return start <= minutes < end
|
||||
|
||||
def _is_early_bird_pending(self) -> bool:
|
||||
"""Check if today has an unresolved early-bird pending marker."""
|
||||
|
||||
@ -1,241 +0,0 @@
|
||||
"""Shutdown hours from the shared earner registry (``earned_time``, kuhyx/utils).
|
||||
|
||||
Every gate's reward -- the workout, the LeetCode hour, the reading hour and
|
||||
whatever is registered next -- is defined once in ``earned_time``, which
|
||||
steam-backlog-enforcer reads for gaming time too. This module is the
|
||||
screen-locker side of it: where the ledgers live, and how minutes are shown.
|
||||
|
||||
The gates publish facts only; none writes the shutdown config. Their ledgers
|
||||
are HMAC-verified against :data:`HMAC_KEY_FILE` and *fail closed* -- an
|
||||
unreadable ledger or key earns nothing, and says so.
|
||||
|
||||
Minutes end to end: the registry, ``/etc/shutdown-schedule.conf`` (its
|
||||
``*_MINUTES`` keys) and every shutdown time in this package are minutes after
|
||||
midnight, so a 30-minute earner is applied exactly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
import functools
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import earned_time
|
||||
|
||||
from screen_locker._constants import HMAC_KEY_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._gate_off import gate_off
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
# Every earner's ``ledger`` is relative to this. Read-only from here; resolved
|
||||
# at call time so the test suite's redirect (tests/_isolated_state.py) applies.
|
||||
LEDGER_HOME: Final = Path.home()
|
||||
|
||||
_MINUTES_PER_HOUR: Final = 60
|
||||
|
||||
|
||||
def hhmm(minutes: int) -> str:
|
||||
"""A time of day, given in minutes after midnight, as ``HH:MM``."""
|
||||
hours, rest = divmod(minutes, _MINUTES_PER_HOUR)
|
||||
return f"{hours:02d}:{rest:02d}"
|
||||
|
||||
|
||||
def span(minutes: int) -> str:
|
||||
"""A duration in minutes as ``2h``, ``30m`` or ``1h30m``."""
|
||||
hours, rest = divmod(minutes, _MINUTES_PER_HOUR)
|
||||
if not rest:
|
||||
return f"{hours}h"
|
||||
if not hours:
|
||||
return f"{rest}m"
|
||||
return f"{hours}h{rest:02d}m"
|
||||
|
||||
|
||||
def ledger_file(earner: earned_time.Earner) -> Path:
|
||||
"""Where ``earner``'s gate keeps its ledger."""
|
||||
if earner.ledger is None:
|
||||
msg = f"earner {earner.name!r} has no ledger"
|
||||
raise ValueError(msg)
|
||||
return LEDGER_HOME / earner.ledger
|
||||
|
||||
|
||||
def registry(day: date | None = None) -> tuple[earned_time.Earner, ...]:
|
||||
"""The earners in force on ``day`` (default today).
|
||||
|
||||
``earners_for`` (earned_time >= 0.5) switches the registry on
|
||||
``TUTOR_FROM``; an older earned_time has one static registry.
|
||||
"""
|
||||
fn = getattr(earned_time, "earners_for", None)
|
||||
return tuple(earned_time.EARNERS if fn is None else fn(day))
|
||||
|
||||
|
||||
def is_gate(earner: earned_time.Earner) -> bool:
|
||||
"""A ledger-backed earner whose gate publishes credits (not the workout).
|
||||
|
||||
The workout has a ledger too, but screen-locker writes it and
|
||||
``WorkoutCreditMixin`` applies it.
|
||||
"""
|
||||
return earner.ledger is not None and earner.name != earned_time.WORKOUT.name
|
||||
|
||||
|
||||
def flat_earners(day: date | None = None) -> tuple[earned_time.Earner, ...]:
|
||||
"""The once-per-day, ledger-backed earners in force on ``day``."""
|
||||
return tuple(e for e in registry(day) if e.kind == "flat" and is_gate(e))
|
||||
|
||||
|
||||
def gate_earners(day: date | None = None) -> tuple[earned_time.Earner, ...]:
|
||||
"""Every gate earner in force on ``day``, flat and counted, in registry order."""
|
||||
return tuple(e for e in registry(day) if is_gate(e))
|
||||
|
||||
|
||||
def counted_gate_earners(day: date | None = None) -> tuple[earned_time.Earner, ...]:
|
||||
"""Gate earners paid per unit on ``day`` (the Automation tutor's blocks)."""
|
||||
return tuple(e for e in registry(day) if e.kind == "counted" and is_gate(e))
|
||||
|
||||
|
||||
def watched_earners() -> tuple[earned_time.Earner, ...]:
|
||||
"""Every gate earner of every registry, so a cutover misses no ledger."""
|
||||
fn = getattr(earned_time, "all_earners", None)
|
||||
pool = earned_time.EARNERS if fn is None else fn()
|
||||
return tuple(e for e in pool if is_gate(e))
|
||||
|
||||
|
||||
def earned_today(
|
||||
earner: earned_time.Earner, now: datetime | None = None
|
||||
) -> bool | None:
|
||||
"""Whether ``earner``'s gate recorded today's credit; ``None`` if unknown."""
|
||||
day = (now or datetime.now(tz=UTC)).astimezone().date()
|
||||
return earned_time.done_today(
|
||||
earner,
|
||||
ledger_file(earner),
|
||||
HMAC_KEY_FILE,
|
||||
now=now,
|
||||
gate_off=gate_off(earner, day),
|
||||
)
|
||||
|
||||
|
||||
def earned_units(earner: earned_time.Earner, day: date) -> int | None:
|
||||
"""How many of a counted earner's units count for ``day``; ``None`` if unknown."""
|
||||
return earned_time.credit_units(
|
||||
earner,
|
||||
ledger_file(earner),
|
||||
HMAC_KEY_FILE,
|
||||
day,
|
||||
gate_off=gate_off(earner, day),
|
||||
)
|
||||
|
||||
|
||||
def gate_answers(day: date | None = None) -> dict[str, int | bool | None]:
|
||||
"""Every gate earner's answer for ``day`` (default today), unknown logged.
|
||||
|
||||
Flat earners answer "done today"; counted ones (the tutor) their units.
|
||||
On an earned_time without counted gates this is exactly
|
||||
:func:`flat_answers`.
|
||||
"""
|
||||
target = day or datetime.now().astimezone().date()
|
||||
answers: dict[str, int | bool | None] = dict(flat_answers())
|
||||
for earner in counted_gate_earners(target):
|
||||
units = earned_units(earner, target)
|
||||
if units is None:
|
||||
_warn_unknown(earner)
|
||||
answers[earner.name] = units
|
||||
return answers
|
||||
|
||||
|
||||
def flat_answers() -> dict[str, bool | None]:
|
||||
"""Today's answer from every flat earner, an unknown one logged."""
|
||||
answers: dict[str, bool | None] = {}
|
||||
for earner in flat_earners():
|
||||
answer = earned_today(earner)
|
||||
if answer is None:
|
||||
_warn_unknown(earner)
|
||||
answers[earner.name] = answer
|
||||
return answers
|
||||
|
||||
|
||||
def _warn_unknown(earner: earned_time.Earner) -> None:
|
||||
_logger.warning(
|
||||
"%s state could not be checked; no shutdown time for it", earner.label
|
||||
)
|
||||
|
||||
|
||||
# The day-aware ladder API (earned_time >= 0.4, from 2026-10-10). Looked up at
|
||||
# call time so the installed 0.3.0 -- which has none of it -- still runs, on
|
||||
# the raw fields it always used.
|
||||
def first_minutes(earner: earned_time.Earner, day: date) -> int:
|
||||
"""What ``earner``'s first unit pushes shutdown later by on ``day``."""
|
||||
fn = getattr(earned_time, "shutdown_minutes_for", None)
|
||||
return earner.shutdown_minutes if fn is None else int(fn(earner, day))
|
||||
|
||||
|
||||
def extra_minutes(earner: earned_time.Earner, day: date) -> int:
|
||||
"""What each further unit of a counted earner earns on ``day``."""
|
||||
fn = getattr(earned_time, "extra_shutdown_minutes_for", None)
|
||||
return earner.extra_shutdown_minutes if fn is None else int(fn(earner, day))
|
||||
|
||||
|
||||
def first_credit_time(earner: earned_time.Earner, day: date) -> float | None:
|
||||
"""Unix time of ``earner``'s first verified credit counting for ``day``.
|
||||
|
||||
``None`` when there is none, when it cannot be checked, and on an
|
||||
``earned_time`` without ``first_credit_at`` (0.3.0) -- logged, because
|
||||
then a late ledger credit counts from now, not from its row.
|
||||
"""
|
||||
fn = getattr(earned_time, "first_credit_at", None)
|
||||
if fn is None:
|
||||
_warn_no_first_credit()
|
||||
return None
|
||||
stamp: float | None = fn(
|
||||
earner, ledger_file(earner), HMAC_KEY_FILE, day, gate_off=gate_off(earner, day)
|
||||
)
|
||||
return stamp
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _warn_no_first_credit() -> None:
|
||||
"""Once per process: the installed earned_time predates first_credit_at."""
|
||||
_logger.warning(
|
||||
"earned_time has no first_credit_at (needs >= 0.4); a late ledger "
|
||||
"credit counts from now, not from its own time"
|
||||
)
|
||||
|
||||
|
||||
def first_credits(
|
||||
earners: tuple[earned_time.Earner, ...], day: date
|
||||
) -> dict[str, date | None] | None:
|
||||
"""Each penalised ledger earner's first real credit up to ``day``, for resolve.
|
||||
|
||||
``earned_time.resolve`` / ``base_for`` take it as ``first_credits=`` (>= 0.6)
|
||||
and then start a penalty no earlier than the day after the gate first
|
||||
paid out. Keyed by name over ``earners`` -- the registry the answers came
|
||||
from, so the two ``automation`` earners (either side of ``TUTOR_FROM``)
|
||||
never collide. An earner without ``penalty_from``, a ledger or a matcher
|
||||
is left out (``resolve`` falls back to its ``confirmed_on``).
|
||||
|
||||
Returns:
|
||||
The map; ``None`` for a day before today -- history keeps the shutdown
|
||||
it was enforced at, never re-resolved -- and on an earned_time
|
||||
without ``maturity`` (< 0.6, logged), where callers resolve as before.
|
||||
"""
|
||||
if day < date.fromisoformat(today_str()):
|
||||
return None
|
||||
fn = getattr(earned_time, "maturity", None)
|
||||
if fn is None:
|
||||
_warn_no_maturity()
|
||||
return None
|
||||
return {
|
||||
e.name: fn(e, ledger_file(e), HMAC_KEY_FILE, day).first_credit
|
||||
for e in earners
|
||||
if e.penalty_from is not None and e.ledger is not None and e.match is not None
|
||||
}
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _warn_no_maturity() -> None:
|
||||
"""Once per process: the installed earned_time predates maturity."""
|
||||
_logger.warning(
|
||||
"earned_time has no maturity (needs >= 0.6); every penalty starts on "
|
||||
"its penalty_from, even for a gate that never paid out"
|
||||
)
|
||||
@ -1,87 +0,0 @@
|
||||
"""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)
|
||||
@ -1,106 +0,0 @@
|
||||
"""The ``earner-bonus.path`` unit: apply a flat bonus the moment it is earned.
|
||||
|
||||
The live bonus pass used to run only on the 15-minute ``workout-sync`` timer,
|
||||
so a LeetCode solve could wait a quarter of an hour for its shutdown hour
|
||||
while the gaming hour landed in seconds (2026-10-06). The path unit watches
|
||||
every flat earner's ledger and starts ``earner-bonus.service``
|
||||
(``--apply-bonuses``) when a gate writes one.
|
||||
|
||||
The watch list is rendered from the ``earned_time`` registry, not kept by
|
||||
hand. Re-pinning the registry is a pip install that never re-runs the
|
||||
installer, so :func:`sync_path_unit` -- called from every ``--sync-only``
|
||||
pass -- rewrites an installed unit that has drifted from the registry. A new
|
||||
earner is watched within 15 minutes with no step to remember.
|
||||
|
||||
``PathChanged=`` and not ``PathModified=``: the gates write a temp file and
|
||||
rename it into place, which ``PathChanged`` sees, including the first write
|
||||
into a directory that does not exist yet. ``PathModified`` would also fire
|
||||
mid-write on a gate that writes in place, and a half-written ledger reads as
|
||||
"could not check".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Final
|
||||
|
||||
from screen_locker._earned import ledger_file, watched_earners
|
||||
|
||||
__all__ = ["PATH_UNIT_NAME", "USER_UNIT_DIR", "render_path_unit", "sync_path_unit"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
PATH_UNIT_NAME: Final = "earner-bonus.path"
|
||||
USER_UNIT_DIR: Final = Path.home() / ".config" / "systemd" / "user"
|
||||
|
||||
_HEADER: Final = """\
|
||||
# Generated by screen_locker._earner_units from the earned_time registry.
|
||||
# Do not edit: the next --sync-only pass rewrites a unit that has drifted.
|
||||
[Unit]
|
||||
Description=Apply a flat earner's shutdown bonus as soon as its ledger changes
|
||||
|
||||
[Path]
|
||||
"""
|
||||
_FOOTER: Final = """
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
"""
|
||||
|
||||
|
||||
def render_path_unit() -> str:
|
||||
"""The unit text: one ``PathChanged=`` per gate earner's ledger.
|
||||
|
||||
Every registry's gates, not just today's (``watched_earners``), so a
|
||||
dated cutover (the Automation tutor's ``TUTOR_FROM``) needs no re-render
|
||||
on the day. The header keeps saying "flat": changing it would rewrite the
|
||||
installed unit for no behavioural change.
|
||||
"""
|
||||
ledgers = dict.fromkeys(ledger_file(e) for e in watched_earners())
|
||||
watches = "".join(f"PathChanged={path}\n" for path in ledgers)
|
||||
return _HEADER + watches + _FOOTER
|
||||
|
||||
|
||||
def sync_path_unit(unit_dir: Path | None = None) -> bool:
|
||||
"""Rewrite an installed path unit that no longer matches the registry.
|
||||
|
||||
An absent unit is left absent: it was never installed, or it was removed
|
||||
on purpose, and installing units is the installer's job. *unit_dir*
|
||||
defaults to :data:`USER_UNIT_DIR`, read at call time.
|
||||
|
||||
Returns True if the unit was rewritten.
|
||||
"""
|
||||
unit = (unit_dir or USER_UNIT_DIR) / PATH_UNIT_NAME
|
||||
if not unit.is_file():
|
||||
return False
|
||||
wanted = render_path_unit()
|
||||
try:
|
||||
if unit.read_text(encoding="utf-8") == wanted:
|
||||
return False
|
||||
unit.write_text(wanted, encoding="utf-8")
|
||||
subprocess.run(
|
||||
["/usr/bin/systemctl", "--user", "daemon-reload"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
except (OSError, subprocess.CalledProcessError) as exc:
|
||||
_logger.warning(
|
||||
"%s differs from the earner registry and could not be refreshed: %s"
|
||||
" -- a newly registered earner waits for the 15-minute sync",
|
||||
unit,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
_logger.warning(
|
||||
"%s was out of date with the earner registry; rewritten and reloaded",
|
||||
unit,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# install_systemd.sh / arm.sh: write the unit into the given directory.
|
||||
target = Path(sys.argv[1]) / PATH_UNIT_NAME
|
||||
target.write_text(render_path_unit(), encoding="utf-8")
|
||||
@ -1,33 +0,0 @@
|
||||
"""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
|
||||
@ -2,23 +2,18 @@
|
||||
|
||||
Tracks:
|
||||
- Consecutive weeks with 5+ workouts (streak counter).
|
||||
- ISO weeks in which the early-bird window is extended to 09:00. Display-only
|
||||
bookkeeping: nothing reads it to decide a lock (early bird is wake-alarm's
|
||||
signed exemption since 2026-09-20).
|
||||
- The week-transition reward messages, for the status window.
|
||||
|
||||
There is no weekly shutdown-time bonus (dropped entirely 2026-10-10, hours
|
||||
already banked for 2026-W41 included): every shutdown minute comes from the
|
||||
``earned_time`` ladder and stops at its daily ceiling. A legacy
|
||||
``weekly_shutdown_bonus_hours`` map in an old state file is ignored, and
|
||||
dropped at the next week transition's write.
|
||||
- Banked shutdown-time bonus hours earned from extra workouts, applied
|
||||
every day of the following week. This never reduces enforcement (unlike
|
||||
a banked "skip a workout" credit would) — it only grants extra comfort
|
||||
time on top of a floor you still have to earn each day.
|
||||
- ISO weeks in which the early-bird window is extended to 09:00.
|
||||
|
||||
State is persisted in ``extra_benefits_state.json`` next to this file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@ -30,9 +25,8 @@ if TYPE_CHECKING:
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_BONUS_THRESHOLD = 5 # workouts/week required to extend the streak + early-bird
|
||||
# The removed weekly shutdown bonus's map; ignored on read, dropped on write.
|
||||
_LEGACY_BONUS_KEY = "weekly_shutdown_bonus_hours"
|
||||
_MILESTONE_INTERVAL = 4 # every 4-week streak → +1h extra shutdown bonus
|
||||
_BONUS_THRESHOLD = 5 # workouts/week required to earn extra rewards
|
||||
|
||||
|
||||
def _load_state(state_file: Path) -> dict[str, Any]:
|
||||
@ -45,7 +39,7 @@ def _load_state(state_file: Path) -> dict[str, Any]:
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Could not read extra-benefits state from %s: %s — starting from "
|
||||
"empty state, so the workout streak and early-bird extension are "
|
||||
"empty state, so the workout streak and any banked bonus hours are "
|
||||
"lost for this run",
|
||||
state_file,
|
||||
exc,
|
||||
@ -62,23 +56,42 @@ def _save_state(state_file: Path, state: dict[str, Any]) -> None:
|
||||
_logger.warning("Failed to save extra benefits state: %s", exc)
|
||||
|
||||
|
||||
def _current_iso_week(now: date) -> str:
|
||||
def _current_iso_week(now: datetime) -> str:
|
||||
"""Return *now*'s ISO week as ``YYYY-Www``."""
|
||||
year, week, _ = now.isocalendar()
|
||||
return f"{year}-W{week:02d}"
|
||||
|
||||
|
||||
def preview_bonus_if_week_ended_now(
|
||||
current_week_count: int, current_streak: int
|
||||
) -> tuple[int, int]:
|
||||
"""(would_be_new_streak, would_be_bonus_hours) if the ISO week ended now.
|
||||
|
||||
Pure extraction of ``process_week_transition``'s threshold math — no file
|
||||
I/O, safe to call from a read-only status view for a "next week preview."
|
||||
"""
|
||||
if current_week_count < _BONUS_THRESHOLD:
|
||||
return 0, 0
|
||||
streak = current_streak + 1
|
||||
bonus_hours = current_week_count - 4
|
||||
if streak % _MILESTONE_INTERVAL == 0:
|
||||
bonus_hours += 1
|
||||
return streak, bonus_hours
|
||||
|
||||
|
||||
def process_week_transition(log_file: Path, state_file: Path) -> list[str]:
|
||||
"""Process last week's results if we've entered a new ISO week.
|
||||
|
||||
Counts workouts from the previous ISO week. If count >= 5:
|
||||
- Increments the consecutive-streak counter.
|
||||
- Banks (count - 4) hours of shutdown-time bonus for the current week,
|
||||
applied once per day on top of the daily base reset.
|
||||
- Marks the *current* ISO week as having extended early-bird (09:00).
|
||||
Otherwise the streak resets to 0. No shutdown-time hours are banked.
|
||||
- Adds +1h more bonus every ``_MILESTONE_INTERVAL`` streak weeks.
|
||||
|
||||
Returns a list of human-readable reward strings (empty if no transition).
|
||||
"""
|
||||
now = datetime.now(tz=UTC).astimezone()
|
||||
now = datetime.now(tz=timezone.utc).astimezone()
|
||||
current_week_str = _current_iso_week(now)
|
||||
|
||||
state = _load_state(state_file)
|
||||
@ -95,46 +108,46 @@ def process_week_transition(log_file: Path, state_file: Path) -> list[str]:
|
||||
23,
|
||||
59,
|
||||
59,
|
||||
tzinfo=UTC,
|
||||
tzinfo=timezone.utc,
|
||||
)
|
||||
prev_week_count = count_weekly_workouts(log_file, today=prev_week_dt)
|
||||
|
||||
streak = int(state.get("consecutive_5plus_weeks", 0))
|
||||
weekly_bonus_hours: dict[str, int] = dict(
|
||||
state.get("weekly_shutdown_bonus_hours", {})
|
||||
)
|
||||
eb_weeks: list[str] = list(state.get("extended_early_bird_iso_weeks", []))
|
||||
|
||||
rewards: list[str] = []
|
||||
prev_week_str = _current_iso_week(sunday_prev_week)
|
||||
prev_year, prev_week, _ = sunday_prev_week.isocalendar()
|
||||
prev_week_str = f"{prev_year}-W{prev_week:02d}"
|
||||
|
||||
if prev_week_count >= _BONUS_THRESHOLD:
|
||||
streak += 1
|
||||
extra = prev_week_count - 4
|
||||
streak, bonus_hours = preview_bonus_if_week_ended_now(prev_week_count, streak)
|
||||
if current_week_str not in eb_weeks:
|
||||
eb_weeks.append(current_week_str)
|
||||
rewards.append(
|
||||
f"{prev_week_count} workouts in {prev_week_str}! {streak}-week streak"
|
||||
f"{prev_week_count} workouts in {prev_week_str}! "
|
||||
f"+{extra}h shutdown bonus this week, early-bird extended to 09:00"
|
||||
)
|
||||
if streak % _MILESTONE_INTERVAL == 0:
|
||||
rewards.append(f"{streak}-week streak milestone! +1h extra shutdown bonus")
|
||||
weekly_bonus_hours[current_week_str] = bonus_hours
|
||||
else:
|
||||
if streak > 0:
|
||||
rewards.append(f"Streak reset (was {streak} weeks of 5+ workouts)")
|
||||
streak = 0
|
||||
|
||||
# Merge onto the loaded state rather than rebuilding it from these three
|
||||
# keys: sibling fields written by the recovery scripts (e.g.
|
||||
# ``shutdown_bonus_granted_for``) live in this file too, and rebuilding
|
||||
# would drop them at the next weekly rollover. Only the dead weekly-bonus
|
||||
# map is dropped, so no reader can mistake it for live state.
|
||||
updated = dict(state)
|
||||
updated.pop(_LEGACY_BONUS_KEY, None)
|
||||
updated.update(
|
||||
_save_state(
|
||||
state_file,
|
||||
{
|
||||
"consecutive_5plus_weeks": streak,
|
||||
"last_processed_iso_week": current_week_str,
|
||||
"weekly_shutdown_bonus_hours": weekly_bonus_hours,
|
||||
"extended_early_bird_iso_weeks": eb_weeks,
|
||||
# Kept for the status window (display only): the strings above
|
||||
# used to go to the log and nowhere else.
|
||||
"week_rewards": {"iso_week": current_week_str, "messages": rewards},
|
||||
}
|
||||
},
|
||||
)
|
||||
_save_state(state_file, updated)
|
||||
return rewards
|
||||
|
||||
|
||||
@ -143,23 +156,23 @@ def current_streak(state_file: Path) -> int:
|
||||
return int(_load_state(state_file).get("consecutive_5plus_weeks", 0))
|
||||
|
||||
|
||||
def weekly_shutdown_bonus_hours(
|
||||
state_file: Path, *, today: datetime | None = None
|
||||
) -> int:
|
||||
"""Return the banked shutdown-time bonus (hours) for the current ISO week."""
|
||||
now = today if today is not None else datetime.now(tz=timezone.utc).astimezone()
|
||||
current_week_str = _current_iso_week(now)
|
||||
bonus_hours: dict[str, int] = _load_state(state_file).get(
|
||||
"weekly_shutdown_bonus_hours", {}
|
||||
)
|
||||
return int(bonus_hours.get(current_week_str, 0))
|
||||
|
||||
|
||||
def has_extended_early_bird(state_file: Path, *, today: datetime | None = None) -> bool:
|
||||
"""Return True if the current ISO week has an extended early-bird window (09:00)."""
|
||||
now = today if today is not None else datetime.now(tz=UTC).astimezone()
|
||||
now = today if today is not None else datetime.now(tz=timezone.utc).astimezone()
|
||||
current_week_str = _current_iso_week(now)
|
||||
eb_weeks: list[str] = _load_state(state_file).get(
|
||||
"extended_early_bird_iso_weeks", []
|
||||
)
|
||||
return current_week_str in eb_weeks
|
||||
|
||||
|
||||
def week_rewards(state_file: Path, *, today: datetime | None = None) -> tuple[str, ...]:
|
||||
"""The reward messages this ISO week's transition produced, for display.
|
||||
|
||||
Empty once the week has passed, or when nothing was stored.
|
||||
"""
|
||||
now = today if today is not None else datetime.now(tz=UTC).astimezone()
|
||||
stored = _load_state(state_file).get("week_rewards", {})
|
||||
if not isinstance(stored, dict) or stored.get("iso_week") != _current_iso_week(now):
|
||||
return ()
|
||||
return tuple(str(m) for m in stored.get("messages", []))
|
||||
|
||||
@ -1,130 +0,0 @@
|
||||
"""Live shutdown credit for counted gate earners: paid per unit, as it lands.
|
||||
|
||||
A flat earner (LeetCode, reading) pays by its signed progress (a credited
|
||||
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
|
||||
is ``<name>_bonus_units``: the day, and how many units the config already
|
||||
holds. The live pass pays only the difference, priced by
|
||||
``Earner.shutdown_for`` so the rung's per-unit split (15 per tutor block) and the
|
||||
``max_units`` cap come from the registry, never from here.
|
||||
|
||||
The workout is counted too, but screen-locker owns its log and
|
||||
``WorkoutCreditMixin`` applies it; it is never in this pass.
|
||||
|
||||
State I/O stays in :mod:`screen_locker._shutdown_base`; these functions read
|
||||
and update the state dict it hands over.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from screen_locker._earned import earned_units, is_gate, span
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
import earned_time
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def date_stamp(earner: earned_time.Earner) -> str:
|
||||
"""The legacy key: a flat earner's full bonus applied on that 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:
|
||||
"""The per-day key of ``earner``'s applied units in the state file."""
|
||||
return f"{earner.name}_bonus_units"
|
||||
|
||||
|
||||
def applied_units(state: dict[str, Any], earner: earned_time.Earner, today: str) -> int:
|
||||
"""Units of ``earner`` the config already holds today (0 if none stamped)."""
|
||||
raw = state.get(units_stamp(earner))
|
||||
if not isinstance(raw, dict) or raw.get("date") != today:
|
||||
return 0
|
||||
units = raw.get("units")
|
||||
return units if isinstance(units, int) and units > 0 else 0
|
||||
|
||||
|
||||
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.
|
||||
|
||||
A flat earner that paid is stamped with the minutes it paid (a partial
|
||||
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] = {}
|
||||
for t in terms:
|
||||
if t.earner.kind == "flat" and t.shutdown_minutes:
|
||||
stamps[minutes_stamp(t.earner)] = {
|
||||
"date": today,
|
||||
"minutes": t.shutdown_minutes,
|
||||
}
|
||||
elif t.earner.kind == "counted" and is_gate(t.earner) and t.answer:
|
||||
stamps[units_stamp(t.earner)] = {"date": today, "units": t.answer}
|
||||
return stamps
|
||||
|
||||
|
||||
def apply_counted_bonus(
|
||||
state: dict[str, Any],
|
||||
adjust: Callable[[int], bool],
|
||||
earner: earned_time.Earner,
|
||||
today: str,
|
||||
) -> bool:
|
||||
"""Push shutdown later by ``earner``'s units credited since the last pass.
|
||||
|
||||
``adjust`` is the mixin's ``_adjust_shutdown_time_by``. Updates ``state``
|
||||
(the caller saves it) and returns True when it changed. An unreadable
|
||||
ledger or key earns nothing and is logged.
|
||||
"""
|
||||
day = date.fromisoformat(today)
|
||||
units = earned_units(earner, day)
|
||||
if units is None:
|
||||
_logger.warning(
|
||||
"%s state could not be checked; no shutdown time for it", earner.label
|
||||
)
|
||||
return False
|
||||
done = applied_units(state, earner, today)
|
||||
if units <= done:
|
||||
return False
|
||||
minutes = earner.shutdown_for(units, day) - earner.shutdown_for(done, day)
|
||||
if minutes > 0 and not adjust(minutes):
|
||||
_logger.warning("%s bonus: failed to write shutdown config.", earner.label)
|
||||
return False
|
||||
state[units_stamp(earner)] = {"date": today, "units": units}
|
||||
_logger.info(
|
||||
"%s bonus: %d unit(s) today, +%s shutdown time.",
|
||||
earner.label,
|
||||
units,
|
||||
span(minutes),
|
||||
)
|
||||
return True
|
||||
@ -1,28 +0,0 @@
|
||||
"""Whether an earner's gate stands down today, asked live (earned_time 0.18.0).
|
||||
|
||||
Only LeetCode has a price: while its gate is on, earned_time pays only the
|
||||
signed charge that covers the whole day, never one solve of five (kuhy,
|
||||
2026-10-24). A free day or a sick day not keeping ``leetcode`` has no price,
|
||||
so one verified solve earns. Never stored: clearing the sick day takes the
|
||||
exception back on the next read.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import earned_time
|
||||
import freedays
|
||||
import sickdays
|
||||
|
||||
from screen_locker._sick import stands_down
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
|
||||
def gate_off(earner: earned_time.Earner, day: date) -> bool:
|
||||
"""Whether ``earner``'s gate is off on ``day`` (always False but LeetCode)."""
|
||||
if earner.name != earned_time.LEETCODE.name:
|
||||
return False
|
||||
return freedays.is_free_day(day) or stands_down(sickdays.LOCKER_LEETCODE, day)
|
||||
@ -1,113 +0,0 @@
|
||||
"""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)
|
||||
@ -1,126 +0,0 @@
|
||||
"""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. The
|
||||
late-credit rule that replaced it (a credit after tonight's shutdown counted
|
||||
from its own time) went on 2026-11-18: every credit adds to tonight's
|
||||
shutdown, and unpaid gates hold the PC behind the evening chain until 23:00.
|
||||
|
||||
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
|
||||
config above the earned sum), but ``plan_absorb`` still spends a stale one
|
||||
recorded before the change, once.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import earned_time
|
||||
|
||||
from screen_locker._constants import GRACE_STATE_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._earned import first_credit_time, gate_earners
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._weekly_check import credit_key, day_workout_index
|
||||
from screen_locker._workout_ledger import entry_done_at
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_MON_WED = frozenset({0, 1, 2})
|
||||
|
||||
|
||||
def workout_done_at(log_file: Path, day: date) -> float | None:
|
||||
"""The completion time of ``day``'s first counted workout, if any."""
|
||||
iso = day.isoformat()
|
||||
entries = [
|
||||
e for e in load_workout_log(log_file).get(iso, []) if isinstance(e, dict)
|
||||
]
|
||||
siblings = day_workout_index(entries)
|
||||
times = [
|
||||
stamp
|
||||
for index, entry in enumerate(entries)
|
||||
if credit_key(iso, index, entry, siblings) is not None
|
||||
and (stamp := entry_done_at(entry, day)) is not None
|
||||
]
|
||||
return min(times, default=None)
|
||||
|
||||
|
||||
def _workout_time(day: date, log_file: Path | None, *, rest_day: bool) -> float | None:
|
||||
"""When ``day``'s first workout was done: the ledger's and the log's view.
|
||||
|
||||
The workout ledger (``earned_time`` >= 0.4) holds only RunnerUp and rest
|
||||
days, so the log still answers for manual and StrongLifts workouts. On a
|
||||
rest day the ledger is skipped: its rest row is stamped at the day's
|
||||
midnight, which is not a completion and would otherwise erase the floor.
|
||||
"""
|
||||
times: list[float | None] = []
|
||||
if log_file is not None:
|
||||
times.append(workout_done_at(log_file, day))
|
||||
if not rest_day and earned_time.WORKOUT.ledger is not None:
|
||||
times.append(first_credit_time(earned_time.WORKOUT, day))
|
||||
return min((t for t in times if t is not None), default=None)
|
||||
|
||||
|
||||
def first_done_at(
|
||||
day: date, log_file: Path | None, *, rest_day: bool = False
|
||||
) -> float | None:
|
||||
"""The earliest moment any earner was done on ``day``; ``None`` if none.
|
||||
|
||||
Every gate in force on ``day`` counts, flat or counted: the Automation
|
||||
tutor's first verified block starts the floor like a LeetCode solve does.
|
||||
"""
|
||||
times = [first_credit_time(e, day) for e in gate_earners(day)]
|
||||
times.append(_workout_time(day, log_file, rest_day=rest_day))
|
||||
on_day = [
|
||||
t
|
||||
for t in times
|
||||
if t is not None and datetime.fromtimestamp(t).astimezone().date() == day
|
||||
]
|
||||
return min(on_day, default=None)
|
||||
|
||||
|
||||
def load_lift(state_file: Path, today: str) -> int:
|
||||
"""Today's recorded floor lift (grace or sick), 0 when none or unreadable."""
|
||||
if not state_file.exists():
|
||||
return 0 # no lift recorded yet: nothing to absorb
|
||||
try:
|
||||
raw = json.loads(state_file.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Grace state %s unreadable (%s); lift taken as 0", state_file, exc
|
||||
)
|
||||
return 0
|
||||
if not isinstance(raw, dict) or raw.get("date") != today:
|
||||
return 0
|
||||
return max(0, int(raw.get("lift", 0)))
|
||||
|
||||
|
||||
def save_lift(lift: int, state_file: Path | None = None) -> None:
|
||||
"""Record how far the floor lifts today's shutdown above the earned time."""
|
||||
state_file = state_file or GRACE_STATE_FILE
|
||||
payload = {"date": today_str(), "lift": max(0, lift)}
|
||||
try:
|
||||
state_file.write_text(json.dumps(payload), encoding="utf-8")
|
||||
except OSError as exc:
|
||||
_logger.warning("Could not record the grace lift in %s (%s)", state_file, exc)
|
||||
|
||||
|
||||
def plan_absorb(minutes: int, state_file: Path | None = None) -> tuple[int, int]:
|
||||
"""How much of an ``minutes`` addition moves the config, and the lift left.
|
||||
|
||||
Commit the lift with :func:`save_lift` only once the write succeeded.
|
||||
"""
|
||||
lift = load_lift(state_file or GRACE_STATE_FILE, today_str())
|
||||
return max(0, minutes - lift), max(0, lift - minutes)
|
||||
|
||||
|
||||
def tonight_minutes(config: tuple[int, int, int], day: date) -> int:
|
||||
"""``day``'s shutdown from a (mon_wed, thu_sun, morning_end) config."""
|
||||
mon_wed, thu_sun, _ = config
|
||||
return mon_wed if day.weekday() in _MON_WED else thu_sun
|
||||
@ -9,8 +9,6 @@ from typing import TYPE_CHECKING
|
||||
from gatelock import LockConfig, bind_activate, bind_cancel
|
||||
|
||||
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:
|
||||
from collections.abc import Callable
|
||||
@ -41,42 +39,46 @@ def build_heat_skip_content(
|
||||
*both* edges if it ever outgrows the display -- and it has to be in the
|
||||
fit check for that reason.
|
||||
"""
|
||||
outer = tk.Frame(parent, bg=_COLORS.palette.bg)
|
||||
outer = tk.Frame(parent, bg=_COLORS.bg)
|
||||
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(
|
||||
outer,
|
||||
text="\u25b2",
|
||||
font=_COLORS.font("display", bold=True, family=_FONT),
|
||||
bg=_COLORS.palette.bg,
|
||||
fg=_COLORS.palette.warning,
|
||||
text="\u2600 Too hot to workout?",
|
||||
font=_COLORS.font("body", bold=True, family=_FONT),
|
||||
bg=_COLORS.bg,
|
||||
fg=_COLORS.warning,
|
||||
).pack(pady=(0, _COLORS.space("sm")))
|
||||
|
||||
tk.Label(
|
||||
outer,
|
||||
# The city name was dropped too: the reading is what matters.
|
||||
text=f"{temp:.0f}\u00b0C \u2265 {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C",
|
||||
text=(
|
||||
f"{HEAT_SKIP_CITY}: {temp:.0f}\u00b0C"
|
||||
f" (threshold: {HEAT_SKIP_TEMP_THRESHOLD}\u00b0C)"
|
||||
),
|
||||
font=_COLORS.font("body", family=_FONT),
|
||||
bg=_COLORS.palette.bg,
|
||||
fg=_COLORS.palette.warning,
|
||||
bg=_COLORS.bg,
|
||||
fg=_COLORS.muted,
|
||||
).pack(pady=_COLORS.space("xs"))
|
||||
|
||||
btn_frame = tk.Frame(outer, bg=_COLORS.palette.bg)
|
||||
tk.Label(
|
||||
outer,
|
||||
text="Skip today's workout due to extreme heat?",
|
||||
font=_COLORS.font("body", family=_FONT),
|
||||
bg=_COLORS.bg,
|
||||
fg=_COLORS.muted,
|
||||
).pack(pady=(_COLORS.space("xs"), 0))
|
||||
|
||||
btn_frame = tk.Frame(outer, bg=_COLORS.bg)
|
||||
btn_frame.pack(pady=_COLORS.space("lg"))
|
||||
|
||||
# Was "Skip workout" (warning fill) / "No, I'll workout" (neutral fill).
|
||||
skip_button = tk.Button(
|
||||
btn_frame,
|
||||
name="skip",
|
||||
text="\u21b7",
|
||||
text="Skip workout",
|
||||
command=on_skip,
|
||||
bg=_COLORS.palette.warning,
|
||||
fg=_COLORS.palette.on_fill,
|
||||
activebackground=_COLORS.palette.warning,
|
||||
bg=_COLORS.warning,
|
||||
fg=_COLORS.on_fill,
|
||||
activebackground=_COLORS.warning,
|
||||
font=_COLORS.font("label", family=_FONT),
|
||||
padx=_COLORS.space("md"),
|
||||
pady=_COLORS.space("sm"),
|
||||
@ -84,16 +86,14 @@ def build_heat_skip_content(
|
||||
**_COLORS.focus_kwargs(),
|
||||
)
|
||||
skip_button.pack(side="left", padx=_COLORS.space("sm"))
|
||||
attach_tooltip(skip_button, "Skip")
|
||||
|
||||
decline_button = tk.Button(
|
||||
btn_frame,
|
||||
name="decline",
|
||||
text="▶",
|
||||
text="No, I'll workout",
|
||||
command=on_decline,
|
||||
bg=_COLORS.palette.field_bg,
|
||||
fg=_COLORS.palette.fg,
|
||||
activebackground=_COLORS.palette.field_bg,
|
||||
bg=_COLORS.field_bg,
|
||||
fg=_COLORS.fg,
|
||||
activebackground=_COLORS.field_bg,
|
||||
font=_COLORS.font("label", family=_FONT),
|
||||
padx=_COLORS.space("md"),
|
||||
pady=_COLORS.space("sm"),
|
||||
@ -101,7 +101,6 @@ def build_heat_skip_content(
|
||||
**_COLORS.focus_kwargs(),
|
||||
)
|
||||
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
|
||||
# the keyboard is the only way out for a pointerless user. It used to
|
||||
@ -131,8 +130,8 @@ class HeatSkipMixin:
|
||||
# Use the root itself (not a Toplevel) so we can go fullscreen.
|
||||
# This window is destroyed before the main GateRoot is created.
|
||||
root = tk.Tk()
|
||||
root.title("")
|
||||
root.configure(bg=_COLORS.palette.bg)
|
||||
root.title("Extreme Heat")
|
||||
root.configure(bg=_COLORS.bg)
|
||||
root.attributes("-fullscreen", True)
|
||||
root.attributes("-topmost", True)
|
||||
root.grab_set()
|
||||
@ -147,7 +146,6 @@ class HeatSkipMixin:
|
||||
root.destroy()
|
||||
|
||||
build_heat_skip_content(root, temp, on_skip=_on_skip, on_decline=_on_no)
|
||||
place_credit(root, _COLORS)
|
||||
bind_cancel(root, _on_no)
|
||||
|
||||
root.mainloop()
|
||||
@ -155,7 +153,7 @@ class HeatSkipMixin:
|
||||
return result[0]
|
||||
|
||||
def _save_heat_skip_log(self, temp: float) -> None:
|
||||
"""Append a heat_skip entry to log.json."""
|
||||
"""Append a heat_skip entry to workout_log.json."""
|
||||
self.workout_data = {
|
||||
"type": "heat_skip",
|
||||
"temperature_celsius": str(round(temp)),
|
||||
|
||||
@ -1,86 +0,0 @@
|
||||
"""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)
|
||||
@ -1,94 +0,0 @@
|
||||
"""HTTP fallback for phone verification: find the app's server, fetch JSON.
|
||||
|
||||
Split out of :mod:`screen_locker._phone_verification` to keep every file under
|
||||
the 250-line cap. Composed back into ``PhoneVerificationMixin`` there, so
|
||||
callers see no change.
|
||||
|
||||
Used when adb cannot reach the phone but it is on the same wifi: the workout
|
||||
app serves the same JSON over ``WORKOUT_HTTP_PORT``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import (
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
from http import client as _http_client
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
|
||||
from screen_locker._constants import WORKOUT_HTTP_PORT
|
||||
|
||||
_HTTPConnection = _http_client.HTTPConnection
|
||||
_HTTPException = _http_client.HTTPException
|
||||
_HTTP_OK = _http_client.OK
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HttpWorkoutFetchMixin:
|
||||
"""Scans the local subnet for the workout app's HTTP server."""
|
||||
|
||||
def _scan_for_http_server(self) -> str | None:
|
||||
"""Scan local /24 subnet for the workout app HTTP server on port 8765.
|
||||
|
||||
Returns the first reachable URL or None.
|
||||
"""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
return None
|
||||
|
||||
def probe(i: int) -> str | None:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, WORKOUT_HTTP_PORT), timeout=0.3),
|
||||
):
|
||||
return f"http://{ip}:{WORKOUT_HTTP_PORT}/workout"
|
||||
return None
|
||||
|
||||
_logger.info(
|
||||
"Scanning %s.1-254:%d for workout app...", prefix, WORKOUT_HTTP_PORT
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _fetch_http_workout(self) -> dict | None:
|
||||
"""Fetch workout JSON from the app's HTTP server on the local network.
|
||||
|
||||
Uses http.client directly to avoid urllib URL-open security lint rules.
|
||||
The URL is always http://<local-ip>:8765/workout — no user input involved.
|
||||
"""
|
||||
url = self._scan_for_http_server()
|
||||
if url is None:
|
||||
return None
|
||||
# url is always "http://<ip>:<port>/workout" — constructed internally.
|
||||
try:
|
||||
_, _, hostport = url.partition("://")
|
||||
host, _, path = hostport.partition("/")
|
||||
hostname, _, port_str = host.partition(":")
|
||||
conn = _HTTPConnection(hostname, int(port_str), timeout=5)
|
||||
conn.request("GET", f"/{path}")
|
||||
resp = conn.getresponse()
|
||||
if resp.status != _HTTP_OK:
|
||||
return None
|
||||
return json.loads(resp.read().decode())
|
||||
except (_HTTPException, OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"HTTP fetch of today's workout from %s failed (%s) — no data "
|
||||
"from the phone's HTTP server, so verification falls through",
|
||||
url,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
# ── Main verification entry point ─────────────────────────────────────────
|
||||
@ -1,68 +0,0 @@
|
||||
"""One workout-locker process at a time.
|
||||
|
||||
A stray re-arm (a delayed ``workout-locker.timer`` catch-up landing right on
|
||||
top of a session that just unlocked, a direct spawn outside the tracked
|
||||
systemd unit, or any other double-start) used to mean two Tk processes
|
||||
racing to build a lock window and grab the display. Copied in shape from
|
||||
``leetcode_guard._instance`` / ``diet_guard._gatelock.acquire_gate_lock``.
|
||||
|
||||
Liveness is the kernel's ``flock``, held for the process lifetime: it is
|
||||
released on *any* death, including SIGKILL and a crashed X server. No PID
|
||||
files, no staleness heuristics, no timeouts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import fcntl
|
||||
import logging
|
||||
import os
|
||||
from typing import IO, TYPE_CHECKING, Final
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstanceLock:
|
||||
"""A held single-instance lock."""
|
||||
|
||||
handle: IO[str]
|
||||
path: Path
|
||||
|
||||
def release(self) -> None:
|
||||
"""Drop the lock. Idempotent, and safe on a closed handle."""
|
||||
try:
|
||||
self.handle.close()
|
||||
except OSError as exc:
|
||||
_logger.warning("could not close the instance lock %s: %s", self.path, exc)
|
||||
|
||||
|
||||
def acquire(path: Path) -> InstanceLock | None:
|
||||
"""Take the single-instance lock, or ``None`` if another run holds it.
|
||||
|
||||
Opened ``"a+"`` rather than ``"w"``: ``"w"`` truncates at ``open()`` time,
|
||||
which happens *before* the lock attempt, so a losing contender would erase
|
||||
the incumbent's record on its way out.
|
||||
"""
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = path.open("a+", encoding="utf-8")
|
||||
except OSError:
|
||||
_logger.exception("cannot open the instance lock %s", path)
|
||||
return None
|
||||
try:
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
_logger.warning(
|
||||
"another workout-locker run already holds %s -- standing down", path
|
||||
)
|
||||
handle.close()
|
||||
return None
|
||||
handle.seek(0)
|
||||
handle.truncate()
|
||||
handle.write(str(os.getpid()))
|
||||
handle.flush()
|
||||
return InstanceLock(handle=handle, path=path)
|
||||
@ -1,59 +0,0 @@
|
||||
"""The one thing the enforce path must never do: lock over a logged workout.
|
||||
|
||||
Every skip in ``_startup_checks._check_non_verify_exits`` is a rung of a
|
||||
first-match-wins ladder, and the ladder's ORDER is what decides whether a
|
||||
logged workout counts. That order has been wrong before: on 2026-09-18 an
|
||||
expired early-bird marker sat one rung above ``workout_logged_today``, so a
|
||||
walk logged on the lock screen at 09:32 closed the lock and the 09:35 tick
|
||||
locked again -- and would have every five minutes for the rest of the day.
|
||||
The DECISION line even printed ``also=workout_logged_today``; the evidence
|
||||
was there, only the gate was missing.
|
||||
|
||||
This module is that gate. It runs right before the ``enforced`` decision is
|
||||
recorded and refuses to build a lock screen when a counted workout for today
|
||||
is already in the log, whatever the ladder above it concluded. Reaching it
|
||||
with a workout logged is a bug in the ladder, so it is reported at ERROR --
|
||||
the locker must fail safe (no lock) and say so, not fail closed on the user.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
GUARD_REASON = "workout_logged_today_guard"
|
||||
GUARD_DETAIL = (
|
||||
"A counted workout is already logged today but the exemption ladder fell "
|
||||
"through to enforcement — refusing to lock (ladder bug, see journal ERROR)."
|
||||
)
|
||||
|
||||
|
||||
def refuse_to_lock_over_logged_workout(
|
||||
has_logged_today: Callable[[], bool],
|
||||
record_skip: Callable[[str, str], None],
|
||||
) -> bool:
|
||||
"""Skip enforcement if today already holds a counted workout.
|
||||
|
||||
Takes the locker's two relevant methods rather than the locker itself so
|
||||
the guard stays a pure function of "is there a workout?" and "how do I
|
||||
skip?". Returns True when the guard fired (the skip was recorded through
|
||||
*record_skip*, which exits the process), False when the lock may go
|
||||
ahead. The ERROR is deliberate: a fired guard means a rung above it is
|
||||
misordered, and that has to be visible in the journal rather than quietly
|
||||
absorbed as one more skip.
|
||||
"""
|
||||
if not has_logged_today():
|
||||
return False
|
||||
_logger.error(
|
||||
"Enforcement reached with a workout already logged today — the "
|
||||
"early-exit ladder in _startup_checks/_auto_upgrade is misordered. "
|
||||
"Refusing to lock; fix the ladder so workout_logged_today is reached."
|
||||
)
|
||||
record_skip(GUARD_REASON, GUARD_DETAIL)
|
||||
return True
|
||||
@ -1,4 +1,4 @@
|
||||
"""Single normalization point for reading ``log.json``.
|
||||
"""Single normalization point for reading ``workout_log.json``.
|
||||
|
||||
The log is day-keyed and now holds MULTIPLE workouts per day. This module is
|
||||
the one place that reads the raw file and normalizes both shapes into a
|
||||
@ -27,7 +27,7 @@ _logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def read_raw_log(log_file: Path) -> dict:
|
||||
"""Load ``log.json`` verbatim (values may be dict or list), or ``{}``.
|
||||
"""Load ``workout_log.json`` verbatim (values may be dict or list), or ``{}``.
|
||||
|
||||
Returns the on-disk shape unchanged. Prefer :func:`load_workout_log` for
|
||||
reading; this raw form exists for the writer, which rewrites the file, and
|
||||
@ -58,7 +58,7 @@ def read_raw_log(log_file: Path) -> dict:
|
||||
|
||||
|
||||
def load_workout_log(log_file: Path) -> dict[str, list[dict]]:
|
||||
"""Load ``log.json`` normalized to ``{date: [entry, ...]}``.
|
||||
"""Load ``workout_log.json`` normalized to ``{date: [entry, ...]}``.
|
||||
|
||||
Accepts BOTH the legacy day-keyed shape (``{date: entry}``) and the new
|
||||
multi-entry shape so old files, rolled-back writers, and mid-migration
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
"""Mixin: workout log persistence (read/write log.json)."""
|
||||
"""Mixin: workout log persistence (read/write workout_log.json)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
@ -12,11 +11,9 @@ from typing import TYPE_CHECKING
|
||||
from gatelock.log_integrity import compute_entry_hmac
|
||||
|
||||
from screen_locker import _compliance_state
|
||||
from screen_locker._bonus_lock import bonus_lock
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._constants import SCHEDULED_SKIPS_FILE
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE, manual_sync_record_id
|
||||
from screen_locker._workout_ledger import record_log_entry
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
@ -82,22 +79,6 @@ def _entry_workout_id(date: str, entry: Mapping[str, object]) -> str | None:
|
||||
return _derive_workout_id(date, workout_data)
|
||||
|
||||
|
||||
def _is_logged_anywhere(logs: dict[str, list[dict]], workout_id: str) -> bool:
|
||||
"""True if any day already holds an entry with this ``workout_id``.
|
||||
|
||||
Searched across ALL days, not just the one being written: a workout id is
|
||||
globally unique (it embeds its own date), and a copy of the same workout
|
||||
can arrive keyed on a different day — e.g. an entry moved to the local day
|
||||
it was really logged on, then its synced twin coming back stamped with
|
||||
the old UTC day. Per-day dedup would append that twin as a duplicate.
|
||||
"""
|
||||
return any(
|
||||
_entry_workout_id(day, e) == workout_id
|
||||
for day, entries in logs.items()
|
||||
for e in entries
|
||||
)
|
||||
|
||||
|
||||
def write_signed_entry(
|
||||
log_file: Path, date: str, workout_data: Mapping[str, object]
|
||||
) -> RecordResult:
|
||||
@ -107,47 +88,26 @@ def write_signed_entry(
|
||||
workout) and manual-sync ingestion, which files a synced workout under its
|
||||
OWN date so the weekly count places it in the right ISO week. The log is
|
||||
day-keyed but now holds MULTIPLE entries per day: this APPENDS rather than
|
||||
overwrites. If an entry with the same ``workout_id`` already exists on ANY
|
||||
overwrites. If an entry with the same ``workout_id`` already exists for the
|
||||
day, it is a no-op — the log itself is the idempotency store, so
|
||||
re-verifying the same workout never double-records. Every write normalizes
|
||||
the whole file to the list shape, progressively migrating legacy entries.
|
||||
|
||||
Returns a :class:`RecordResult` so the credit path can tell an appended
|
||||
workout from a duplicate and a first-of-day workout from an additional one.
|
||||
|
||||
The read-dedup-write runs under an exclusive lock beside the log: the
|
||||
5-minute locker pass, the 15-minute sync and the RunnerUp upload watcher
|
||||
all backfill the same run, and two of them reading before either wrote
|
||||
would both see it missing -- two entries and, since only an appended
|
||||
result is credited, two shutdown rewards.
|
||||
"""
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
stack.enter_context(bonus_lock(log_file))
|
||||
except OSError as e:
|
||||
_logger.warning(
|
||||
"Could not lock workout log %s (%s) — writing without the lock; "
|
||||
"a pass running at the same moment could record this twice",
|
||||
log_file,
|
||||
e,
|
||||
)
|
||||
return _write_signed_entry_locked(log_file, date, workout_data)
|
||||
|
||||
|
||||
def _write_signed_entry_locked(
|
||||
log_file: Path, date: str, workout_data: Mapping[str, object]
|
||||
) -> RecordResult:
|
||||
"""Body of :func:`write_signed_entry`; the caller holds the log lock."""
|
||||
logs = load_workout_log(log_file)
|
||||
entries = logs.setdefault(date, [])
|
||||
prior = list(entries)
|
||||
|
||||
workout_id = _derive_workout_id(date, workout_data)
|
||||
if workout_id is not None and _is_logged_anywhere(logs, workout_id):
|
||||
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)
|
||||
|
||||
entry: dict[str, object] = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"timestamp": datetime.now(tz=timezone.utc).isoformat(),
|
||||
"workout_data": workout_data,
|
||||
}
|
||||
if workout_id is not None:
|
||||
@ -163,15 +123,11 @@ def _write_signed_entry_locked(
|
||||
json.dump(logs, f, indent=2)
|
||||
except OSError as e:
|
||||
_logger.warning("Could not save workout log: %s", e)
|
||||
else:
|
||||
# The one chokepoint every credit passes, so the signed workout
|
||||
# ledger (earned_time's view of the workout) can never miss one.
|
||||
record_log_entry(date, entries)
|
||||
return RecordResult(appended=True, prior_entries=prior)
|
||||
|
||||
|
||||
class LogMixin:
|
||||
"""Handles reading and writing log.json for the ScreenLocker.
|
||||
"""Handles reading and writing workout_log.json for the ScreenLocker.
|
||||
|
||||
``log_file``/``workout_data`` are declared here (not assigned) so mypy
|
||||
knows their types on any composing class without needing
|
||||
@ -188,7 +144,7 @@ class LogMixin:
|
||||
|
||||
def _is_scheduled_skip_today(self) -> bool:
|
||||
"""Return True if today's date is listed in the scheduled skips file."""
|
||||
return _compliance_state.is_scheduled_skip_today()
|
||||
return _compliance_state.is_scheduled_skip_today(SCHEDULED_SKIPS_FILE)
|
||||
|
||||
def save_workout_log(self) -> RecordResult:
|
||||
"""Append today's workout to the log (HMAC-signed) and report the result.
|
||||
@ -198,5 +154,5 @@ class LogMixin:
|
||||
credit only for a genuinely new workout and scale it by whether today
|
||||
already had one.
|
||||
"""
|
||||
today = today_str()
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
return write_signed_entry(self.log_file, today, self.workout_data)
|
||||
|
||||
@ -1,211 +0,0 @@
|
||||
"""Headless manual-workout logging: same evidence rules, no UI.
|
||||
|
||||
The phone form was the only way to log a manual workout, which made logging
|
||||
one depend on the phone's foreground: another app stealing focus mid-entry
|
||||
could interleave or drop a field. That is a bad property for a record that
|
||||
consumes budget, so this offers the same thing as a command.
|
||||
|
||||
What it deliberately is NOT: a way to log a workout without evidence. Every
|
||||
field the form demands is demanded here, checked by the SAME
|
||||
``validate_manual_workout``, and a missing or too-short field refuses the
|
||||
whole run and writes nothing. ``log_manual_workout.py`` was deleted because
|
||||
it bypassed those checks; this routes through the ordinary sync-ingest path
|
||||
(``ingest_manual_records``), so validation, the rolling budget, HMAC signing
|
||||
and workout_id dedup are the shared implementation rather than a second copy
|
||||
that can drift.
|
||||
|
||||
``--date`` may name a FUTURE day (up to 7 days ahead; past dates are refused).
|
||||
Such an entry is not ingested: it is held and published by
|
||||
``_manual_schedule`` and ingested -- and credited -- on its date by the
|
||||
ordinary sync pass.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_future import is_future_date, validate_workout_date
|
||||
from screen_locker._manual_schedule import budget_error, schedule_future_workout
|
||||
from screen_locker._manual_sync import ingest_manual_records
|
||||
from screen_locker._manual_workout import (
|
||||
SPORT_CHOICES,
|
||||
SPORT_OTHER,
|
||||
ManualWorkoutDraft,
|
||||
build_sync_payload,
|
||||
manual_sync_record_id,
|
||||
validate_manual_workout,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["add_manual_arguments", "run_manual_log"]
|
||||
|
||||
# (flag, payload key, default). Defaults mirror ManualWorkoutDraft's own, so
|
||||
# "not supplied" means the same thing headlessly as it does on the form --
|
||||
# pain_or_injury is "none" (an answer) rather than "" (never asked).
|
||||
_OPTIONAL_TEXT = (
|
||||
("reservation_phone", "reservation_phone", ""),
|
||||
("techniques", "techniques_practiced", ""),
|
||||
("warm_up", "warm_up_minutes", ""),
|
||||
("pain_or_injury", "pain_or_injury", "none"),
|
||||
("racket", "racket", ""),
|
||||
("balls", "balls", ""),
|
||||
("equipment", "equipment", ""),
|
||||
)
|
||||
_OPTIONAL_INT = (
|
||||
("matches_won", "matches_won"),
|
||||
("matches_lost", "matches_lost"),
|
||||
("sets_won", "sets_won"),
|
||||
("sets_lost", "sets_lost"),
|
||||
)
|
||||
|
||||
|
||||
def add_manual_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
"""Register every manual-workout field as a flag on ``parser``.
|
||||
|
||||
No flag carries a substantive default: the point is that the caller
|
||||
supplies the evidence, so an omitted field must fail validation rather
|
||||
than be quietly filled in with something plausible.
|
||||
"""
|
||||
parser.add_argument("--sport", choices=sorted(SPORT_CHOICES), required=True)
|
||||
parser.add_argument(
|
||||
"--activity",
|
||||
default="",
|
||||
help=f"what the activity was; required when --sport {SPORT_OTHER}",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--date",
|
||||
default="",
|
||||
help=(
|
||||
"ISO date, today up to 7 days ahead (no past dates); defaults to "
|
||||
"today. A future date is held and credited automatically on it."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--start", required=True, help="HH:MM")
|
||||
parser.add_argument("--end", required=True, help="HH:MM")
|
||||
parser.add_argument("--location", required=True)
|
||||
parser.add_argument("--transport", required=True, help="how you got there")
|
||||
parser.add_argument("--cost", required=True, help='e.g. "60 PLN" or "none"')
|
||||
parser.add_argument("--rpe", required=True, type=int, help="1-10")
|
||||
parser.add_argument("--details", required=True, help="what was done")
|
||||
parser.add_argument("--went-well", required=True)
|
||||
parser.add_argument("--to-improve", required=True)
|
||||
parser.add_argument("--feeling", required=True, help="overall feeling")
|
||||
for flag, _key, default in _OPTIONAL_TEXT:
|
||||
parser.add_argument(f"--{flag.replace('_', '-')}", default=default)
|
||||
for flag, _key in _OPTIONAL_INT:
|
||||
parser.add_argument(f"--{flag.replace('_', '-')}", default=0, type=int)
|
||||
|
||||
|
||||
def _draft(args: argparse.Namespace) -> ManualWorkoutDraft:
|
||||
"""Build the draft from parsed flags, with no substantive defaults.
|
||||
|
||||
Optional fields fall back to the dataclass's own defaults so the headless
|
||||
path and the form agree on what "not supplied" means.
|
||||
"""
|
||||
return ManualWorkoutDraft(
|
||||
sport=args.sport,
|
||||
start_time=args.start,
|
||||
end_time=args.end,
|
||||
location_name=args.location,
|
||||
transport_method=args.transport,
|
||||
cost=args.cost,
|
||||
rpe=args.rpe,
|
||||
went_well=args.went_well,
|
||||
to_improve=args.to_improve,
|
||||
overall_feeling=args.feeling,
|
||||
activity_type_other=args.activity if args.sport == SPORT_OTHER else "",
|
||||
activity_details=args.details,
|
||||
**{key: getattr(args, flag) for flag, key, _default in _OPTIONAL_TEXT},
|
||||
**{key: getattr(args, flag) for flag, key in _OPTIONAL_INT},
|
||||
)
|
||||
|
||||
|
||||
def _schedule(log_file: Path, draft: ManualWorkoutDraft, date: str) -> int:
|
||||
"""Hold a FUTURE-dated workout and publish it; exit code for the CLI.
|
||||
|
||||
Never written to log.json or signed here: it is ingested by the ordinary
|
||||
sync pass on its date.
|
||||
"""
|
||||
scheduled = schedule_future_workout(log_file, draft, date)
|
||||
if not scheduled.scheduled:
|
||||
_logger.error(
|
||||
"Manual workout %s was NOT scheduled — %s",
|
||||
scheduled.record_id,
|
||||
scheduled.reason,
|
||||
)
|
||||
return 1
|
||||
_logger.info("Manual workout %s: %s", scheduled.record_id, scheduled.reason)
|
||||
return 0
|
||||
|
||||
|
||||
def _log_today(log_file: Path, draft: ManualWorkoutDraft, date: str, start: str) -> int:
|
||||
"""Log today's workout through the ordinary ingest; exit code for the CLI."""
|
||||
record_id = manual_sync_record_id(date, start)
|
||||
payload = build_sync_payload(draft, date)
|
||||
# Today's entry takes the ordinary path, but its budget now also counts
|
||||
# pending future entries (a window containing today contains tomorrow too).
|
||||
over_budget = budget_error(log_file, date)
|
||||
if over_budget is not None:
|
||||
_logger.error("Manual workout %s was NOT logged — %s", record_id, over_budget)
|
||||
return 1
|
||||
|
||||
ingested = ingest_manual_records(log_file, [(record_id, payload)], today=date)
|
||||
if not ingested:
|
||||
_logger.error(
|
||||
"Manual workout %s was NOT logged — see the reason logged above "
|
||||
"(invalid field, exhausted budget, or already logged)",
|
||||
record_id,
|
||||
)
|
||||
return 1
|
||||
_logger.info(
|
||||
"Logged manual workout %s. It publishes to the other devices on the "
|
||||
"next sync pass (workout-sync.timer, every 15 minutes); run "
|
||||
"--sync-only to push it now.",
|
||||
record_id,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def run_manual_log(log_file: Path, argv: Sequence[str]) -> int:
|
||||
"""Log one manual workout headlessly. Returns a process exit code.
|
||||
|
||||
Non-zero means nothing was written: ``ingest_manual_records`` refuses a
|
||||
draft that fails validation or that the rolling budget has no room for,
|
||||
and it already logs the concrete reason, so a caller never has to guess
|
||||
between "rejected" and "already logged".
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="screen-locker --log-manual-workout",
|
||||
description="Log a manual workout without opening any app.",
|
||||
)
|
||||
add_manual_arguments(parser)
|
||||
args = parser.parse_args(list(argv))
|
||||
|
||||
# The LOCAL day, like every other day-key (screen_locker._day): the old
|
||||
# UTC default filed a workout logged at 00:02 CEST under yesterday, and the
|
||||
# lock check then could not find it "today".
|
||||
date = args.date or today_str()
|
||||
draft = _draft(args)
|
||||
# Validated here as well as inside the ingest, purely so a person running
|
||||
# this by hand gets the concrete field error on stderr and a non-zero exit
|
||||
# instead of only a log line. The ingest re-checks it regardless.
|
||||
error = validate_manual_workout(draft)
|
||||
if error is not None:
|
||||
_logger.error("Manual workout REFUSED — %s. Nothing was written.", error)
|
||||
return 1
|
||||
|
||||
date_error = validate_workout_date(date)
|
||||
if date_error is not None:
|
||||
_logger.error("Manual workout REFUSED — %s. Nothing was written.", date_error)
|
||||
return 1
|
||||
if is_future_date(date):
|
||||
return _schedule(log_file, draft, date)
|
||||
return _log_today(log_file, draft, date, args.start)
|
||||
@ -1,222 +0,0 @@
|
||||
"""Future-dated manual workouts: the date rule and the per-date budget rule.
|
||||
|
||||
A manual workout may be logged AHEAD of time (``today .. today + 7 days``, never
|
||||
a past date) and earns its normal credit on that date, not before. Two pure
|
||||
rules live here, shared by every entry point (Tk dialog, CLI, sync ingest):
|
||||
|
||||
* :func:`validate_workout_date` -- the one 0..7-days-ahead check;
|
||||
* :func:`budget_error_for_date` -- the rolling budget (2 per 7 days, 10 per 30)
|
||||
counted against the WORKOUT's date, over logged credits AND pending future
|
||||
entries, so a future entry holds its slot from the moment it is logged.
|
||||
|
||||
No I/O beyond reading ``log.json``; the pending ledger and the Firebase pull
|
||||
are in ``_manual_pending`` / ``_manual_schedule``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
MANUAL_WORKOUT_MAX_DAYS_AHEAD,
|
||||
)
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_workout_types import manual_credit_dates
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"BudgetUsage",
|
||||
"budget_closed_for_all_days",
|
||||
"budget_error_for_date",
|
||||
"budget_usage_for_date",
|
||||
"is_future_date",
|
||||
"parse_workout_date",
|
||||
"validate_workout_date",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# (window length in days, cap) -- a window of N days is [start, start + N - 1].
|
||||
_WINDOWS: tuple[tuple[int, int], ...] = (
|
||||
(7, MANUAL_WORKOUT_BUDGET_PER_7_DAYS),
|
||||
(30, MANUAL_WORKOUT_BUDGET_PER_30_DAYS),
|
||||
)
|
||||
|
||||
|
||||
def parse_workout_date(value: str) -> date | None:
|
||||
"""Parse a strict ``YYYY-MM-DD`` string, or return None (and warn)."""
|
||||
try:
|
||||
return datetime.strptime(value.strip(), "%Y-%m-%d").replace(tzinfo=UTC).date()
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Date %r is not YYYY-MM-DD (%s) — treated as invalid", value, exc
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def is_future_date(value: str, *, today: str | None = None) -> bool:
|
||||
"""True if ``value`` is a valid date strictly after today (local day)."""
|
||||
parsed = parse_workout_date(value)
|
||||
reference = parse_workout_date(today or today_str())
|
||||
return parsed is not None and reference is not None and parsed > reference
|
||||
|
||||
|
||||
def validate_workout_date(value: str, *, today: str | None = None) -> str | None:
|
||||
"""Return an error message if ``value`` is not today..today+7 days, else None.
|
||||
|
||||
THE date rule for manual workouts: no past dates (a back-dated entry is the
|
||||
easiest way to fake a missed week) and no more than
|
||||
``MANUAL_WORKOUT_MAX_DAYS_AHEAD`` days ahead.
|
||||
"""
|
||||
parsed = parse_workout_date(value)
|
||||
if parsed is None:
|
||||
return "Workout date must be YYYY-MM-DD"
|
||||
reference = parse_workout_date(today or today_str())
|
||||
if reference is None:
|
||||
return f"Today's date {today!r} is not YYYY-MM-DD"
|
||||
ahead = (parsed - reference).days
|
||||
if ahead < 0:
|
||||
return (
|
||||
f"Workout date {value.strip()} is in the past -- only today or up "
|
||||
f"to {MANUAL_WORKOUT_MAX_DAYS_AHEAD} days ahead"
|
||||
)
|
||||
if ahead > MANUAL_WORKOUT_MAX_DAYS_AHEAD:
|
||||
return (
|
||||
f"Workout date {value.strip()} is {ahead} days ahead -- at most "
|
||||
f"{MANUAL_WORKOUT_MAX_DAYS_AHEAD} days"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _ordinals(dates: Iterable[str]) -> list[int]:
|
||||
"""Day ordinals of every parsable date; unparsable ones are skipped."""
|
||||
days: list[int] = []
|
||||
for value in dates:
|
||||
parsed = parse_workout_date(value)
|
||||
if parsed is not None:
|
||||
days.append(parsed.toordinal())
|
||||
return days
|
||||
|
||||
|
||||
def _fullest_window(days: list[int], ordinal: int, length: int) -> tuple[int, int]:
|
||||
"""Return ``(count, start)`` of the fullest ``length``-day window holding D.
|
||||
|
||||
Counts the entries in ``days`` only (the new entry is not among them), over
|
||||
every window ``[start, start + length - 1]`` that contains ``ordinal``.
|
||||
"""
|
||||
return max(
|
||||
(
|
||||
(sum(1 for day in days if start <= day < start + length), start)
|
||||
for start in range(ordinal - length + 1, ordinal + 1)
|
||||
),
|
||||
key=lambda found: found[0],
|
||||
)
|
||||
|
||||
|
||||
def _existing_days(log_file: Path, pending_dates: Iterable[str]) -> list[int]:
|
||||
"""Ordinals of every logged credit and every pending future entry."""
|
||||
return [*_ordinals(manual_credit_dates(log_file)), *_ordinals(pending_dates)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BudgetUsage:
|
||||
"""How full the fullest windows around one workout date already are."""
|
||||
|
||||
week: int
|
||||
month: int
|
||||
|
||||
@property
|
||||
def exhausted(self) -> bool:
|
||||
"""True if one more entry on that date would break either cap."""
|
||||
return (
|
||||
self.week >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or self.month >= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_usage_for_date(
|
||||
log_file: Path,
|
||||
workout_date: str,
|
||||
pending_dates: Iterable[str] = (),
|
||||
) -> BudgetUsage | None:
|
||||
"""Return the fullest 7- and 30-day windows containing ``workout_date``.
|
||||
|
||||
The PC's admission rule as numbers: the shared cross-language fixture
|
||||
(``fixtures/manual_budget_merge.json``, ``planned.expected_by_date``) pins
|
||||
these to what the phone computes. None if the date does not parse.
|
||||
"""
|
||||
target = parse_workout_date(workout_date)
|
||||
if target is None:
|
||||
return None
|
||||
days = _existing_days(log_file, pending_dates)
|
||||
ordinal = target.toordinal()
|
||||
return BudgetUsage(
|
||||
week=_fullest_window(days, ordinal, 7)[0],
|
||||
month=_fullest_window(days, ordinal, 30)[0],
|
||||
)
|
||||
|
||||
|
||||
def budget_error_for_date(
|
||||
log_file: Path,
|
||||
workout_date: str,
|
||||
pending_dates: Iterable[str] = (),
|
||||
) -> str | None:
|
||||
"""Return why a manual workout dated ``workout_date`` does not fit, else None.
|
||||
|
||||
Adding an entry dated D is allowed only if EVERY rolling window containing
|
||||
D -- each 7-day window and each 30-day window -- stays within its cap
|
||||
counting the credits already in ``log_file``, the pending future entries
|
||||
in ``pending_dates``, and the new entry itself. Counting against D rather
|
||||
than against today is what lets a full week still schedule next week, and
|
||||
what keeps tomorrow's entry from being free of the cap.
|
||||
|
||||
``pending_dates`` must already exclude the entry being checked (an entry
|
||||
that holds its slot would otherwise reject itself on its own date).
|
||||
"""
|
||||
target = parse_workout_date(workout_date)
|
||||
if target is None:
|
||||
return f"Workout date {workout_date!r} must be YYYY-MM-DD"
|
||||
days = _existing_days(log_file, pending_dates)
|
||||
for length, cap in _WINDOWS:
|
||||
used, start = _fullest_window(days, target.toordinal(), length)
|
||||
if used >= cap:
|
||||
first = date.fromordinal(start)
|
||||
last = first + timedelta(days=length - 1)
|
||||
return (
|
||||
f"Manual-workout budget: {used} already counted/scheduled "
|
||||
f"between {first} and {last}, max {cap} per {length} days"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def budget_closed_for_all_days(
|
||||
log_file: Path,
|
||||
pending_dates: Iterable[str] = (),
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""True if no date in today..today+7 could take another manual workout.
|
||||
|
||||
The "Log Manual Workout" button hides only then; "today's window is full"
|
||||
no longer closes it, since a later day may still have room.
|
||||
"""
|
||||
reference = parse_workout_date(today or today_str())
|
||||
if reference is None:
|
||||
_logger.warning("Today %r is not YYYY-MM-DD -- budget treated as closed", today)
|
||||
return True
|
||||
pending = list(pending_dates)
|
||||
return all(
|
||||
budget_error_for_date(
|
||||
log_file, (reference + timedelta(days=offset)).isoformat(), pending
|
||||
)
|
||||
is not None
|
||||
for offset in range(MANUAL_WORKOUT_MAX_DAYS_AHEAD + 1)
|
||||
)
|
||||
@ -1,217 +0,0 @@
|
||||
"""Durable ledger of future-dated manual workouts logged on THIS PC.
|
||||
|
||||
A manual workout logged for a later day must not enter ``log.json`` until that
|
||||
day (the weekly check, the budget, the status view and the shutdown derivation
|
||||
all read the log, and would count it early). It has to live somewhere else, and
|
||||
be visible to the phone for budget and deletion -- so it is published to this
|
||||
device's sync log.
|
||||
|
||||
Publishing once is not enough, for the reason ``_sync_tombstones`` documents:
|
||||
``_manual_push`` re-derives this device's log from ``log.json`` on every tick
|
||||
and ``crdt_sync.sync_log`` never reads the device's OWN remote log back, so
|
||||
anything published only once is overwritten by the next push. This ledger is
|
||||
what every push re-publishes (``records_from_workout_log`` merges it in), and
|
||||
ingestion on the workout's date reads the record back through the ordinary
|
||||
pull -- the PC does ingest its own device log -- or from here if Firebase is
|
||||
unreachable that day.
|
||||
|
||||
``{record_id: {payload, hlc, scheduled_at}}`` in ``MANUAL_PENDING_FILE``. The HLC
|
||||
is minted once and stored, so re-pushing the same entry does not churn the
|
||||
store. An entry leaves the ledger once it is in ``log.json`` (its own copy is
|
||||
then published from there) or once it is tombstoned.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from crdt_sync import Hlc, Record
|
||||
|
||||
from screen_locker._constants import MANUAL_PENDING_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _entry_workout_id
|
||||
from screen_locker._manual_future import parse_workout_date
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
|
||||
from screen_locker._sync_tombstones import tombstone_records
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"add_pending",
|
||||
"local_pending_records",
|
||||
"pending_future_dates",
|
||||
"pending_ledger_records",
|
||||
"settle_pending",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_PAYLOAD_FIELD = "payload"
|
||||
|
||||
|
||||
def _ledger_path(path: Path | None) -> Path:
|
||||
"""Resolve the ledger path at call time, so a patched module global applies."""
|
||||
return MANUAL_PENDING_FILE if path is None else path
|
||||
|
||||
|
||||
def _load(path: Path) -> dict[str, dict[str, Any]]:
|
||||
"""Read the ledger; a missing file is empty, a corrupt one is loud."""
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(path.read_text())
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Pending manual-workout ledger %s is unreadable (%s) -- treating it "
|
||||
"as EMPTY, so future-dated workouts logged on this PC will not be "
|
||||
"re-published or credited from here",
|
||||
path,
|
||||
exc,
|
||||
)
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
_logger.warning(
|
||||
"Pending manual-workout ledger %s is not a JSON object -- ignoring it",
|
||||
path,
|
||||
)
|
||||
return {}
|
||||
return {str(rid): entry for rid, entry in raw.items() if isinstance(entry, dict)}
|
||||
|
||||
|
||||
def _save(path: Path, ledger: dict[str, dict[str, Any]]) -> None:
|
||||
"""Write the ledger as sorted, indented JSON."""
|
||||
path.write_text(json.dumps(ledger, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def add_pending(
|
||||
record_id: str,
|
||||
payload: dict[str, object],
|
||||
device_id: str,
|
||||
path: Path | None = None,
|
||||
) -> bool:
|
||||
"""Record a future-dated manual workout. Returns False if already held."""
|
||||
path = _ledger_path(path)
|
||||
ledger = _load(path)
|
||||
if record_id in ledger:
|
||||
return False
|
||||
ledger[record_id] = {
|
||||
"payload": payload,
|
||||
"hlc": Hlc.new_tick(device_id).to_str(),
|
||||
"scheduled_at": datetime.now(tz=UTC).isoformat(),
|
||||
}
|
||||
_save(path, ledger)
|
||||
return True
|
||||
|
||||
|
||||
def local_pending_records(path: Path | None = None) -> list[tuple[str, dict]]:
|
||||
"""Return ``(record_id, payload)`` for every ledgered entry not tombstoned.
|
||||
|
||||
The shape ``ingest_manual_records`` takes, so this PC's own future entries
|
||||
can be ingested on their date even when the Firebase pull is empty or down.
|
||||
"""
|
||||
dead = tombstone_records().keys()
|
||||
return [
|
||||
(rid, entry["payload"])
|
||||
for rid, entry in _load(_ledger_path(path)).items()
|
||||
if rid not in dead and isinstance(entry.get("payload"), dict)
|
||||
]
|
||||
|
||||
|
||||
def pending_ledger_records(path: Path | None = None) -> dict[str, Record]:
|
||||
"""Return the ledger as crdt_sync records, for ``_manual_push`` to publish.
|
||||
|
||||
An entry without a parsable ``hlc`` is skipped with a warning: publishing
|
||||
it clockless would churn the store (or lose to a stale copy).
|
||||
"""
|
||||
records: dict[str, Record] = {}
|
||||
for record_id, entry in _load(_ledger_path(path)).items():
|
||||
payload = entry.get("payload")
|
||||
try:
|
||||
hlc = Hlc.from_str(str(entry.get("hlc")))
|
||||
except (ValueError, TypeError) as exc:
|
||||
_logger.warning(
|
||||
"Pending manual workout %s has no usable hlc (%r: %s) -- NOT "
|
||||
"published, so the phone will not see it",
|
||||
record_id,
|
||||
entry.get("hlc"),
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
if isinstance(payload, dict):
|
||||
records[record_id] = Record(
|
||||
id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)}
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _logged_ids(log_file: Path) -> set[str]:
|
||||
"""Every workout id already in ``log.json`` (stored, derived or synced)."""
|
||||
ids: set[str] = set()
|
||||
for day, entries in load_workout_log(log_file).items():
|
||||
for entry in entries:
|
||||
if (own := _entry_workout_id(day, entry)) is not None:
|
||||
ids.add(own)
|
||||
data = entry.get("workout_data", {})
|
||||
if isinstance(data, dict) and data.get("sync_record_id"):
|
||||
ids.add(str(data["sync_record_id"]))
|
||||
return ids
|
||||
|
||||
|
||||
def settle_pending(
|
||||
log_file: Path,
|
||||
deleted_ids: Iterable[str] = (),
|
||||
path: Path | None = None,
|
||||
) -> list[str]:
|
||||
"""Drop ledger entries that are in ``log.json`` or deleted; return their ids.
|
||||
|
||||
``deleted_ids`` come from the merged sync log (a tombstone written on the
|
||||
phone reaches it) and the local tombstone ledger is consulted too.
|
||||
"""
|
||||
path = _ledger_path(path)
|
||||
ledger = _load(path)
|
||||
if not ledger:
|
||||
return []
|
||||
gone = {*deleted_ids, *tombstone_records().keys(), *_logged_ids(log_file)}
|
||||
settled = [rid for rid in ledger if rid in gone]
|
||||
for rid in settled:
|
||||
del ledger[rid]
|
||||
if settled:
|
||||
_save(path, ledger)
|
||||
_logger.info("Pending manual workout(s) settled and dropped: %s", settled)
|
||||
return settled
|
||||
|
||||
|
||||
def pending_future_dates(
|
||||
log_file: Path,
|
||||
records: Iterable[tuple[str, Mapping[str, object]]],
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Return ``{record_id: date}`` of manual records dated AFTER today.
|
||||
|
||||
``records`` is the merged Firebase manual pull and/or the local ledger
|
||||
(the same record id in both counts once). Ids already in ``log.json`` are
|
||||
not pending. Records dated today or earlier are not pending either: they
|
||||
were ingested or rejected, and a budget-skipped old record must not keep
|
||||
occupying a slot for everyone else.
|
||||
"""
|
||||
reference = today or today_str()
|
||||
logged = _logged_ids(log_file)
|
||||
pending: dict[str, str] = {}
|
||||
for record_id, payload in records:
|
||||
day = payload.get("date")
|
||||
if (
|
||||
payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
|
||||
and isinstance(day, str)
|
||||
and parse_workout_date(day) is not None
|
||||
and day > reference
|
||||
and record_id not in logged
|
||||
):
|
||||
pending[record_id] = day
|
||||
return pending
|
||||
@ -1,7 +1,7 @@
|
||||
"""Push the PC's workouts to the shared Firebase sync store.
|
||||
"""Push the PC's workouts to the shared sync repo.
|
||||
|
||||
``log.json`` is the single source of truth: this module derives the
|
||||
crdt-sync log directly from it and pushes to this device's log, so the
|
||||
``workout_log.json`` is the single source of truth: this module derives the
|
||||
crdt-sync log directly from it and pushes to ``devices/pc/log.json``, so the
|
||||
phone converges on the SAME history the PC has — manual workouts *and*
|
||||
machine-verified ones (StrongLifts sessions, RunnerUp runs).
|
||||
|
||||
@ -10,11 +10,11 @@ workout is published automatically no matter when or how it was recorded,
|
||||
including entries logged before this module existed. Idempotence comes from two
|
||||
properties: the record id is the workout's own stable ``workout_id``, and its
|
||||
HLC is derived deterministically from the entry's own timestamp — so re-pushing
|
||||
an unchanged log produces a byte-identical record set and no store churn.
|
||||
an unchanged log produces a byte-identical record set and no repo churn.
|
||||
|
||||
This reverses the old "the PC only ever reads, never pushes" invariant (it had
|
||||
no data of its own to contribute). Firebase is the only transport since
|
||||
2026-10-09; the old GitHub mirror is a frozen archive. Nothing here fails
|
||||
no data of its own to contribute). Pushing needs a sync token with
|
||||
**contents:write** on the repo — a read-only token 403s. Nothing here fails
|
||||
silently: every path returns a :class:`PushResult` whose ``reason`` says exactly
|
||||
what happened, and logs it.
|
||||
"""
|
||||
@ -22,31 +22,31 @@ what happened, and logs it.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import (
|
||||
FileSyncStateStore,
|
||||
GitHubSyncClient,
|
||||
GitHubSyncError,
|
||||
Hlc,
|
||||
LogCodec,
|
||||
Record,
|
||||
RemoteSyncError,
|
||||
RevisionTracking,
|
||||
SyncTarget,
|
||||
RepoNotFoundError,
|
||||
sync_log,
|
||||
)
|
||||
|
||||
from screen_locker._constants import SYNC_STATE_FILE
|
||||
from screen_locker._device import device_identity
|
||||
from screen_locker._constants import (
|
||||
SYNC_REPO_NAME,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_TIMEOUT_SECONDS,
|
||||
SYNC_TOKEN_FILE,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _derive_workout_id
|
||||
from screen_locker._manual_pending import pending_ledger_records, settle_pending
|
||||
from screen_locker._sync_retry import with_sync_retry
|
||||
from screen_locker._sync_tombstones import tombstone_records
|
||||
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES
|
||||
from screen_locker._workout_sync import _DEVICES_PREFIX, sync_client_or_reason
|
||||
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@ -55,6 +55,7 @@ if TYPE_CHECKING:
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_PC_DEVICE_ID = "pc"
|
||||
_PAYLOAD_FIELD = "payload"
|
||||
|
||||
|
||||
@ -109,12 +110,12 @@ def _entry_wall_ms(entry: dict, date: str) -> int:
|
||||
"for its sync clock",
|
||||
date,
|
||||
)
|
||||
midnight = datetime.fromisoformat(date).replace(tzinfo=UTC)
|
||||
midnight = datetime.fromisoformat(date).replace(tzinfo=timezone.utc)
|
||||
return int(midnight.timestamp() * 1000)
|
||||
|
||||
|
||||
def records_from_workout_log(log_file: Path) -> dict[str, Record]:
|
||||
"""Derive the crdt-sync log from ``log.json``.
|
||||
"""Derive the crdt-sync log from ``workout_log.json``.
|
||||
|
||||
Every counted workout becomes one record keyed by its ``workout_id`` — the
|
||||
same id the phone mints for its own records, so the two sides dedup to one
|
||||
@ -123,7 +124,6 @@ def records_from_workout_log(log_file: Path) -> dict[str, Record]:
|
||||
The payload is the workout's own data plus the ``kind``/``date`` the wire
|
||||
contract requires.
|
||||
"""
|
||||
identity = device_identity()
|
||||
log: dict[str, Record] = {}
|
||||
for date, entries in load_workout_log(log_file).items():
|
||||
for entry in entries:
|
||||
@ -143,76 +143,82 @@ def records_from_workout_log(log_file: Path) -> dict[str, Record]:
|
||||
)
|
||||
continue
|
||||
payload = {**workout_data, "kind": workout_data["type"], "date": date}
|
||||
hlc = Hlc.new_tick(
|
||||
identity.device_id, wall_time_ms=_entry_wall_ms(entry, date)
|
||||
)
|
||||
hlc = Hlc.new_tick(_PC_DEVICE_ID, wall_time_ms=_entry_wall_ms(entry, date))
|
||||
log[str(record_id)] = Record(
|
||||
id=str(record_id), fields={_PAYLOAD_FIELD: (payload, hlc)}
|
||||
)
|
||||
# Future-dated manual workouts logged here are not in log.json until their
|
||||
# day; the ledger is what keeps them published (and visible to the phone's
|
||||
# budget and delete button). The log's own copy wins once ingested.
|
||||
for record_id, record in pending_ledger_records().items():
|
||||
log.setdefault(record_id, record)
|
||||
# Re-pushed every tick: sync_log never reads this device's own remote
|
||||
# log, so a tombstone written once is overwritten by the next push.
|
||||
log.update(tombstone_records())
|
||||
return log
|
||||
|
||||
|
||||
def push_pc_workouts(log_file: Path) -> PushResult:
|
||||
"""Publish every counted workout in ``log_file`` to this device's log.
|
||||
"""Publish every counted workout in ``log_file`` to ``devices/pc/log.json``.
|
||||
|
||||
Runs one full sync tick, so it also retries anything a previous push failed
|
||||
to publish. It never raises into the caller — but it is never silent either:
|
||||
the returned :class:`PushResult` and a WARNING say why a push did not happen.
|
||||
"""
|
||||
identity = device_identity()
|
||||
token = read_sync_token()
|
||||
if token is None:
|
||||
reason = f"no sync token at {SYNC_TOKEN_FILE}"
|
||||
_logger.warning(
|
||||
"Workouts NOT synced: %s — create a fine-grained GitHub PAT with "
|
||||
"contents:write on %s/%s and save it there (chmod 600)",
|
||||
reason,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_REPO_NAME,
|
||||
)
|
||||
return PushResult(pushed=False, record_count=0, reason=reason)
|
||||
|
||||
log = records_from_workout_log(log_file)
|
||||
if not log:
|
||||
reason = f"no counted workouts in {log_file}"
|
||||
_logger.warning("Workouts NOT synced: %s", reason)
|
||||
return PushResult(pushed=False, record_count=0, reason=reason)
|
||||
|
||||
client, reason = sync_client_or_reason()
|
||||
if client is None:
|
||||
# sync_client_or_reason has already said why, in full; this line
|
||||
# ties that cause to the records it just stranded.
|
||||
_logger.warning(
|
||||
"Workouts NOT synced: %d workout(s) stay local — %s", len(log), reason
|
||||
)
|
||||
return PushResult(pushed=False, record_count=len(log), reason=reason)
|
||||
client = GitHubSyncClient(
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_REPO_NAME,
|
||||
token,
|
||||
timeout_seconds=SYNC_TIMEOUT_SECONDS,
|
||||
)
|
||||
try:
|
||||
merged = with_sync_retry(
|
||||
with_sync_retry(
|
||||
lambda: sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
device_id=identity.device_id,
|
||||
legacy_device_id=identity.legacy_id,
|
||||
path_prefix=_DEVICES_PREFIX,
|
||||
),
|
||||
log,
|
||||
LogCodec(
|
||||
decode=_decode_log,
|
||||
encode=_encode_log,
|
||||
),
|
||||
RevisionTracking(
|
||||
state_store=FileSyncStateStore(SYNC_STATE_FILE),
|
||||
),
|
||||
client=client,
|
||||
device_id=_PC_DEVICE_ID,
|
||||
path_prefix=_DEVICES_PREFIX,
|
||||
local_log=log,
|
||||
encode=_encode_log,
|
||||
decode=_decode_log,
|
||||
),
|
||||
description="push PC workouts",
|
||||
)
|
||||
except RemoteSyncError as exc:
|
||||
# Report what actually happened, nothing more: this used to assert
|
||||
# "a 403 means the token lacks contents:write" for every failure,
|
||||
# including a plain network error, which sent a 2026-07-20
|
||||
# investigation chasing a permissions bug that did not exist.
|
||||
except GitHubSyncError as exc:
|
||||
reason = f"sync error: {exc}"
|
||||
_logger.warning("Workout sync push FAILED for %d workout(s): %s", len(log), exc)
|
||||
# Report what actually happened. This used to assert "a 403 here means
|
||||
# the token lacks contents:write" for *every* failure, including a
|
||||
# plain network error — which sent a 2026-07-20 investigation chasing a
|
||||
# permissions bug that did not exist (the token could write fine; the
|
||||
# network was simply not up yet). Only RepoNotFoundError actually
|
||||
# implicates the repo or the token.
|
||||
if isinstance(exc, RepoNotFoundError):
|
||||
_logger.warning(
|
||||
"Workout sync push FAILED for %d workout(s): %s — check the "
|
||||
"token has contents:write on %s/%s",
|
||||
len(log),
|
||||
exc,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_REPO_NAME,
|
||||
)
|
||||
else:
|
||||
_logger.warning(
|
||||
"Workout sync push FAILED for %d workout(s): %s",
|
||||
len(log),
|
||||
exc,
|
||||
)
|
||||
return PushResult(pushed=False, record_count=len(log), reason=reason)
|
||||
|
||||
# A future entry deleted on the phone arrives as a tombstone in the merge;
|
||||
# one already ingested is in log.json. Either way it leaves the ledger.
|
||||
settle_pending(log_file, [rid for rid, record in merged.items() if record.deleted])
|
||||
_logger.info("Synced %d workout(s) to Firebase", len(log))
|
||||
_logger.info(
|
||||
"Synced %d workout(s) to %s/%s", len(log), SYNC_REPO_OWNER, SYNC_REPO_NAME
|
||||
)
|
||||
return PushResult(pushed=True, record_count=len(log), reason="pushed")
|
||||
|
||||
@ -1,115 +0,0 @@
|
||||
"""Log a manual workout for a FUTURE day from this PC (Tk dialog and CLI).
|
||||
|
||||
A future-dated entry never touches ``log.json`` or ``write_signed_entry`` and
|
||||
earns nothing today. It is held in the pending ledger (``_manual_pending``),
|
||||
published to this device's sync log so the phone sees it (budget, delete), and
|
||||
ingested on its date by the ordinary sync pass, which pays exactly what a
|
||||
workout logged that day would.
|
||||
|
||||
This module is the one place that decides whether such an entry may be logged:
|
||||
the date window and the per-date budget, over the credits in ``log.json`` plus
|
||||
every pending future entry -- this PC's ledger AND the merged Firebase manual
|
||||
records (a phone-logged one holds a slot too).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._device import device_identity
|
||||
from screen_locker._manual_future import (
|
||||
budget_error_for_date,
|
||||
is_future_date,
|
||||
validate_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import (
|
||||
add_pending,
|
||||
local_pending_records,
|
||||
pending_future_dates,
|
||||
)
|
||||
from screen_locker._manual_push import push_pc_workouts
|
||||
from screen_locker._manual_workout import build_sync_payload, manual_sync_record_id
|
||||
from screen_locker._workout_sync import pull_all_manual_records
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._manual_workout import ManualWorkoutDraft
|
||||
|
||||
__all__ = ["ScheduleResult", "budget_error", "schedule_future_workout"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleResult:
|
||||
"""Outcome of :func:`schedule_future_workout`; ``reason`` is for a human."""
|
||||
|
||||
scheduled: bool
|
||||
record_id: str
|
||||
reason: str
|
||||
|
||||
|
||||
def budget_error(
|
||||
log_file: Path, workout_date: str, *, exclude_id: str | None = None
|
||||
) -> str | None:
|
||||
"""Why a manual workout on ``workout_date`` does not fit the budget, else None.
|
||||
|
||||
Reads the pending future entries from this PC's ledger and from the merged
|
||||
Firebase pull. The pull is best-effort (``pull_all_manual_records`` warns
|
||||
and returns nothing when Firebase is unreachable), so offline this still
|
||||
sees the ledger -- only a phone-logged pending entry can be missed, and the
|
||||
ingest on that day re-checks.
|
||||
"""
|
||||
records = [*pull_all_manual_records(), *local_pending_records()]
|
||||
pending = pending_future_dates(log_file, records)
|
||||
if exclude_id is not None:
|
||||
pending.pop(exclude_id, None)
|
||||
return budget_error_for_date(log_file, workout_date, pending.values())
|
||||
|
||||
|
||||
def schedule_future_workout(
|
||||
log_file: Path, draft: ManualWorkoutDraft, workout_date: str
|
||||
) -> ScheduleResult:
|
||||
"""Hold a validated draft for ``workout_date`` and publish it.
|
||||
|
||||
The caller has run ``validate_manual_workout`` on ``draft``. Refuses (and
|
||||
says why) a date outside today+1..today+7, an exhausted budget, or an
|
||||
entry already scheduled under the same id; otherwise stores it in the
|
||||
pending ledger and pushes immediately, so the phone sees it now rather
|
||||
than on the next 15-minute tick.
|
||||
"""
|
||||
record_id = manual_sync_record_id(workout_date, draft.start_time)
|
||||
date_error = validate_workout_date(workout_date)
|
||||
if date_error is None and not is_future_date(workout_date):
|
||||
date_error = f"{workout_date} is today, not a future date"
|
||||
if date_error is not None:
|
||||
return ScheduleResult(scheduled=False, record_id=record_id, reason=date_error)
|
||||
over_budget = budget_error(log_file, workout_date)
|
||||
if over_budget is not None:
|
||||
return ScheduleResult(scheduled=False, record_id=record_id, reason=over_budget)
|
||||
payload = build_sync_payload(draft, workout_date)
|
||||
if not add_pending(record_id, payload, device_identity().device_id):
|
||||
return ScheduleResult(
|
||||
scheduled=False,
|
||||
record_id=record_id,
|
||||
reason=f"{record_id} is already scheduled",
|
||||
)
|
||||
pushed = push_pc_workouts(log_file)
|
||||
_logger.info(
|
||||
"Scheduled manual workout %s for %s (published=%s: %s)",
|
||||
record_id,
|
||||
workout_date,
|
||||
pushed.pushed,
|
||||
pushed.reason,
|
||||
)
|
||||
if pushed.pushed:
|
||||
reason = f"scheduled for {workout_date}; counts automatically that day"
|
||||
else:
|
||||
reason = (
|
||||
f"scheduled for {workout_date} on this PC (not yet published: "
|
||||
f"{pushed.reason}); it counts automatically that day"
|
||||
)
|
||||
return ScheduleResult(scheduled=True, record_id=record_id, reason=reason)
|
||||
@ -1,11 +1,11 @@
|
||||
"""Ingest phone-/PC-synced manual workouts into ``log.json``.
|
||||
"""Ingest phone-/PC-synced manual workouts into ``workout_log.json``.
|
||||
|
||||
A manual workout logged on another device (phone form, or the PC form pushed
|
||||
from elsewhere) arrives via crdt-sync as a ``kind="manual_workout"`` payload
|
||||
(see :func:`screen_locker._manual_workout.build_sync_payload`). This module
|
||||
turns those synced payloads into ordinary signed ``manual_workout`` entries in
|
||||
``log.json`` so they count toward the weekly minimum and — via the
|
||||
optional ``on_ingested`` callback — earn the same shutdown reward a
|
||||
``workout_log.json`` so they count toward the weekly minimum and — via the
|
||||
optional ``on_ingested`` callback — earn the same shutdown/debt reward a
|
||||
live-logged workout would.
|
||||
|
||||
Trust model: the PC never trusts the phone's derived fields. Every synced
|
||||
@ -21,23 +21,14 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _entry_workout_id, write_signed_entry
|
||||
from screen_locker._manual_future import (
|
||||
budget_error_for_date,
|
||||
is_future_date,
|
||||
parse_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import pending_future_dates
|
||||
from screen_locker._manual_sync_draft import (
|
||||
_draft_or_report,
|
||||
is_empty_stub,
|
||||
reconstruct_draft,
|
||||
)
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._manual_workout import (
|
||||
MANUAL_WORKOUT_SYNC_KIND,
|
||||
SPORT_OTHER,
|
||||
ManualWorkoutDraft,
|
||||
build_entry,
|
||||
is_budget_exhausted,
|
||||
validate_manual_workout,
|
||||
)
|
||||
|
||||
@ -45,13 +36,8 @@ if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._log_mixin import RecordResult
|
||||
from screen_locker._manual_workout import ManualWorkoutDraft
|
||||
|
||||
OnIngestedCallback = Callable[[dict, "list[dict]"], None]
|
||||
|
||||
__all__ = ["ingest_manual_records", "is_empty_stub", "reconstruct_draft"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Key under which the source sync record id is stored in the ingested
|
||||
@ -59,22 +45,70 @@ _logger = logging.getLogger(__name__)
|
||||
_SYNC_ID_FIELD = "sync_record_id"
|
||||
|
||||
|
||||
def _already_ingested(logs: dict[str, list[dict]], record_id: str) -> bool:
|
||||
"""True if any logged entry already IS this sync record.
|
||||
def _coerce_int(value: object) -> int:
|
||||
"""Coerce a JSON scalar to int; raise for a non-numeric (skips the record)."""
|
||||
if isinstance(value, (int, str)):
|
||||
return int(value)
|
||||
raise TypeError(value)
|
||||
|
||||
Matches either way a record can already be here: an entry ingested from
|
||||
sync carries the id in ``sync_record_id``; an entry logged on this PC
|
||||
(form or CLI) and then published carries it as its own ``workout_id``,
|
||||
since the publisher keys records on exactly that. Checking only the first
|
||||
is how the 2026-09-13 football was re-ingested: it had been logged locally
|
||||
(no ``sync_record_id``), pushed as ``manual:2026-09-12T14:30``, and pulled
|
||||
back as a "new" record. A cheap early-out before reconstructing the draft;
|
||||
the write chokepoint dedups by ``workout_id`` as a second guard.
|
||||
|
||||
def reconstruct_draft(payload: Mapping[str, object]) -> ManualWorkoutDraft | None:
|
||||
"""Rebuild a :class:`ManualWorkoutDraft` from a synced manual payload.
|
||||
|
||||
Returns None if a required raw field is missing or mistyped, so a malformed
|
||||
record is skipped rather than crashing ingestion. Only the raw user inputs
|
||||
are read back — the derived fields (``source``, ``duration_minutes``,
|
||||
``type``) are recomputed by :func:`build_entry` on the PC.
|
||||
"""
|
||||
for day, entries in logs.items():
|
||||
try:
|
||||
sport = str(payload["sport"])
|
||||
activity_type_other = (
|
||||
str(payload.get("activity_type", "")) if sport == SPORT_OTHER else ""
|
||||
)
|
||||
return ManualWorkoutDraft(
|
||||
sport=sport,
|
||||
start_time=str(payload["start_time"]),
|
||||
end_time=str(payload["end_time"]),
|
||||
location_name=str(payload["location_name"]),
|
||||
transport_method=str(payload["transport_method"]),
|
||||
cost=str(payload["cost"]),
|
||||
rpe=_coerce_int(payload["rpe"]),
|
||||
went_well=str(payload["went_well"]),
|
||||
to_improve=str(payload["to_improve"]),
|
||||
overall_feeling=str(payload["overall_feeling"]),
|
||||
reservation_phone=str(payload.get("reservation_phone", "")),
|
||||
techniques_practiced=str(payload.get("techniques_practiced", "")),
|
||||
warm_up_minutes=str(payload.get("warm_up_minutes", "")),
|
||||
pain_or_injury=str(payload.get("pain_or_injury", "none")),
|
||||
matches_won=_coerce_int(payload.get("matches_won", 0)),
|
||||
matches_lost=_coerce_int(payload.get("matches_lost", 0)),
|
||||
sets_won=_coerce_int(payload.get("sets_won", 0)),
|
||||
sets_lost=_coerce_int(payload.get("sets_lost", 0)),
|
||||
racket=str(payload.get("racket", "")),
|
||||
balls=str(payload.get("balls", "")),
|
||||
activity_type_other=activity_type_other,
|
||||
activity_details=str(payload.get("activity_details", "")),
|
||||
equipment=str(payload.get("equipment", "")),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Synced manual workout payload is malformed (%s: %s) — SKIPPING "
|
||||
"this record, so it will not be logged or counted on the PC",
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _already_ingested(logs: dict[str, list[dict]], record_id: str) -> bool:
|
||||
"""True if any logged entry already carries this sync record id.
|
||||
|
||||
Iterates the per-day lists (a day may hold several workouts); a cheap
|
||||
early-out before reconstructing the draft. The write chokepoint also dedups
|
||||
by ``workout_id``, so this and that are two guards on the same idempotency.
|
||||
"""
|
||||
for entries in logs.values():
|
||||
for entry in entries:
|
||||
if _entry_workout_id(day, entry) == record_id:
|
||||
return True
|
||||
workout_data = entry.get("workout_data", {})
|
||||
if (
|
||||
isinstance(workout_data, dict)
|
||||
@ -84,108 +118,6 @@ def _already_ingested(logs: dict[str, list[dict]], record_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _due_date(
|
||||
record_id: str, payload: Mapping[str, object], reference: str
|
||||
) -> str | None:
|
||||
"""Return the record's date if it is a manual record due for ingest, else None.
|
||||
|
||||
None covers every reason to leave it alone this pass: not a manual record,
|
||||
no/unparsable date (warned), or dated after ``reference`` -- deferred, and
|
||||
retried on every later pass so it lands on its date.
|
||||
"""
|
||||
if payload.get("kind") != MANUAL_WORKOUT_SYNC_KIND:
|
||||
return None
|
||||
date = payload.get("date")
|
||||
if not isinstance(date, str):
|
||||
_logger.warning("Manual record %s has no date — skipped", record_id)
|
||||
return None
|
||||
if parse_workout_date(date) is None:
|
||||
_logger.warning(
|
||||
"Manual record %s has an unparsable date %r — skipped", record_id, date
|
||||
)
|
||||
return None
|
||||
if is_future_date(date, today=reference):
|
||||
_logger.info(
|
||||
"Manual record %s is dated %s, after today (%s) — deferred; it "
|
||||
"is ingested and credited on its date",
|
||||
record_id,
|
||||
date,
|
||||
reference,
|
||||
)
|
||||
return None
|
||||
return date
|
||||
|
||||
|
||||
def _new_valid_draft(
|
||||
log_file: Path,
|
||||
record_id: str,
|
||||
payload: Mapping[str, object],
|
||||
reference: str,
|
||||
) -> tuple[str, ManualWorkoutDraft] | None:
|
||||
"""The due date and valid draft of a not-yet-ingested record, else ``None``."""
|
||||
date = _due_date(record_id, payload, reference)
|
||||
if date is None:
|
||||
return None
|
||||
if _already_ingested(load_workout_log(log_file), record_id):
|
||||
return None
|
||||
draft = _draft_or_report(record_id, payload)
|
||||
if draft is None:
|
||||
return None
|
||||
error = validate_manual_workout(draft)
|
||||
if error is not None:
|
||||
_logger.warning("Manual record %s invalid: %s", record_id, error)
|
||||
return None
|
||||
return date, draft
|
||||
|
||||
|
||||
def _ingest_one(
|
||||
log_file: Path,
|
||||
record_id: str,
|
||||
payload: Mapping[str, object],
|
||||
reference: str,
|
||||
pending: Mapping[str, str],
|
||||
) -> tuple[dict[str, object], RecordResult] | None:
|
||||
"""Validate, budget-check and append one record; ``None`` when skipped."""
|
||||
ready = _new_valid_draft(log_file, record_id, payload, reference)
|
||||
if ready is None:
|
||||
return None
|
||||
date, draft = ready
|
||||
over_budget = budget_error_for_date(
|
||||
log_file,
|
||||
date,
|
||||
[day for rid, day in pending.items() if rid != record_id],
|
||||
)
|
||||
if over_budget is not None:
|
||||
_logger.info(
|
||||
"Manual-workout budget exhausted — %s not ingested (%s)",
|
||||
record_id,
|
||||
over_budget,
|
||||
)
|
||||
return None
|
||||
entry = build_entry(draft)
|
||||
entry[_SYNC_ID_FIELD] = record_id
|
||||
# The wire id IS the workout's id: the device that logged it minted
|
||||
# ``manual:<date>T<start>`` once, and the publisher keys on the same
|
||||
# id. Without this the chokepoint re-derived one from ``date`` +
|
||||
# start, and when the two dates disagreed (a record whose day key was
|
||||
# later corrected to the local day) the same workout landed twice
|
||||
# under two ids -- and then consumed two manual-budget slots.
|
||||
entry["workout_id"] = record_id
|
||||
result = write_signed_entry(log_file, date, entry)
|
||||
if not result.appended:
|
||||
# This is dedup working, not credit being lost: the workout is
|
||||
# already in the log under this same workout_id. It was logged at
|
||||
# warning and re-reported on every 15-minute cycle, which read like
|
||||
# a recurring fault and buried the lines that did need attention.
|
||||
_logger.info(
|
||||
"Manual record %s is already logged under the same workout_id "
|
||||
"— skipped as a duplicate (its credit is already counted)",
|
||||
record_id,
|
||||
)
|
||||
return None
|
||||
return entry, result
|
||||
|
||||
|
||||
def ingest_manual_records(
|
||||
log_file: Path,
|
||||
records: Iterable[tuple[str, Mapping[str, object]]],
|
||||
@ -193,7 +125,7 @@ def ingest_manual_records(
|
||||
today: str | None = None,
|
||||
on_ingested: OnIngestedCallback | None = None,
|
||||
) -> list[str]:
|
||||
"""Ingest synced manual workouts into ``log.json``.
|
||||
"""Ingest synced manual workouts into ``workout_log.json``.
|
||||
|
||||
For each ``(record_id, payload)`` tagged ``kind="manual_workout"``:
|
||||
reconstruct + re-validate the draft on the PC, enforce the rate budget, then
|
||||
@ -201,39 +133,48 @@ def ingest_manual_records(
|
||||
workouts). Idempotent: dedup by ``record_id`` here and by ``workout_id`` in
|
||||
the write chokepoint, so re-syncing the same record is a no-op.
|
||||
|
||||
A record dated AFTER ``today`` (default: the local day) is DEFERRED, not
|
||||
ingested: it stays in the sync store, earns nothing and is not written to
|
||||
``log.json`` (the weekly check, the budget, the status view and the
|
||||
shutdown derivation would all count a future day key early). It is retried
|
||||
on every later pass, so it is ingested -- and credited -- on its date.
|
||||
|
||||
The budget is counted against the workout's own date: the new entry fits
|
||||
only if every rolling window containing that date stays within its cap,
|
||||
over the credits in the log and every OTHER pending future record in
|
||||
``records`` (a future entry holds its slot from the moment it is logged).
|
||||
|
||||
When ``on_ingested`` is given, it's called ``on_ingested(entry, prior_entries)``
|
||||
right after each newly-appended record — ``prior_entries`` being that
|
||||
entry's own date's entries written before it — so the caller (see
|
||||
``screen_lock.ScreenLocker._ingest_synced_manual_workouts``) can apply the
|
||||
identical live-workout shutdown reward. This applies regardless of
|
||||
identical live-workout shutdown/debt reward. This applies regardless of
|
||||
whether ``date`` is today or back-dated: there's only one current shutdown
|
||||
config, so a back-dated sync still pushes it exactly as a live workout
|
||||
would have that day.
|
||||
|
||||
Returns the record ids actually ingested.
|
||||
"""
|
||||
batch = list(records)
|
||||
if not batch:
|
||||
return []
|
||||
reference = today or today_str()
|
||||
pending = pending_future_dates(log_file, batch, today=reference)
|
||||
ingested: list[str] = []
|
||||
for record_id, payload in batch:
|
||||
outcome = _ingest_one(log_file, record_id, payload, reference, pending)
|
||||
if outcome is None:
|
||||
for record_id, payload in records:
|
||||
if payload.get("kind") != MANUAL_WORKOUT_SYNC_KIND:
|
||||
continue
|
||||
date = payload.get("date")
|
||||
if not isinstance(date, str):
|
||||
_logger.warning("Manual record %s has no date — skipped", record_id)
|
||||
continue
|
||||
if _already_ingested(load_workout_log(log_file), record_id):
|
||||
continue
|
||||
draft = reconstruct_draft(payload)
|
||||
if draft is None:
|
||||
_logger.warning("Manual record %s is malformed — skipped", record_id)
|
||||
continue
|
||||
error = validate_manual_workout(draft)
|
||||
if error is not None:
|
||||
_logger.warning("Manual record %s invalid: %s", record_id, error)
|
||||
continue
|
||||
if is_budget_exhausted(log_file, today=today):
|
||||
_logger.info("Manual-workout budget exhausted — %s not ingested", record_id)
|
||||
continue
|
||||
entry = build_entry(draft)
|
||||
entry[_SYNC_ID_FIELD] = record_id
|
||||
result = write_signed_entry(log_file, date, entry)
|
||||
if not result.appended:
|
||||
_logger.warning(
|
||||
"Manual record %s collided with an existing workout_id — "
|
||||
"skipped without credit",
|
||||
record_id,
|
||||
)
|
||||
continue
|
||||
entry, result = outcome
|
||||
ingested.append(record_id)
|
||||
if on_ingested is not None:
|
||||
on_ingested(entry, result.prior_entries)
|
||||
|
||||
@ -1,140 +0,0 @@
|
||||
"""Rebuild a :class:`ManualWorkoutDraft` from a synced manual-workout payload.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_sync` to keep every file under the
|
||||
250-line cap; that module re-exports :func:`reconstruct_draft` and
|
||||
:func:`is_empty_stub`, so callers and patch targets are unchanged.
|
||||
|
||||
Only the raw user inputs are read back — the derived fields (``source``,
|
||||
``duration_minutes``, ``type``) are recomputed on the PC by ``build_entry``,
|
||||
which is what keeps a phone from ever dictating what a workout is worth.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._manual_workout import SPORT_OTHER, ManualWorkoutDraft
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# The raw user inputs every real manual workout carries. A payload holding none
|
||||
# of them is a metadata stub, not a damaged workout: there is nothing to
|
||||
# recover and no amount of retrying will change that.
|
||||
_SUBSTANTIVE_FIELDS = frozenset(
|
||||
{
|
||||
"sport",
|
||||
"start_time",
|
||||
"end_time",
|
||||
"location_name",
|
||||
"transport_method",
|
||||
"cost",
|
||||
"rpe",
|
||||
"went_well",
|
||||
"to_improve",
|
||||
"overall_feeling",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def is_empty_stub(payload: Mapping[str, object]) -> bool:
|
||||
"""True when ``payload`` carries no workout content at all.
|
||||
|
||||
Observed in the wild as ``{"type", "kind", "date"}`` and nothing else --
|
||||
a record the phone created without ever attaching the workout. Every sync
|
||||
cycle re-reported it as malformed, so a permanent, unfixable condition
|
||||
produced an unbounded stream of identical warnings (four every 15 minutes),
|
||||
which is how the genuinely actionable lines got lost in the noise.
|
||||
"""
|
||||
return not _SUBSTANTIVE_FIELDS & set(payload)
|
||||
|
||||
|
||||
def _coerce_int(value: object) -> int:
|
||||
"""Coerce a JSON scalar to int; raise for a non-numeric (skips the record)."""
|
||||
if isinstance(value, (int, str)):
|
||||
return int(value)
|
||||
raise TypeError(value)
|
||||
|
||||
|
||||
def reconstruct_draft(payload: Mapping[str, object]) -> ManualWorkoutDraft | None:
|
||||
"""Rebuild a :class:`ManualWorkoutDraft` from a synced manual payload.
|
||||
|
||||
Returns None if a required raw field is missing or mistyped, so a malformed
|
||||
record is skipped rather than crashing ingestion. Only the raw user inputs
|
||||
are read back — the derived fields (``source``, ``duration_minutes``,
|
||||
``type``) are recomputed by :func:`build_entry` on the PC.
|
||||
"""
|
||||
try:
|
||||
sport = str(payload["sport"])
|
||||
activity_type_other = (
|
||||
str(payload.get("activity_type", "")) if sport == SPORT_OTHER else ""
|
||||
)
|
||||
return ManualWorkoutDraft(
|
||||
sport=sport,
|
||||
start_time=str(payload["start_time"]),
|
||||
end_time=str(payload["end_time"]),
|
||||
location_name=str(payload["location_name"]),
|
||||
transport_method=str(payload["transport_method"]),
|
||||
cost=str(payload["cost"]),
|
||||
rpe=_coerce_int(payload["rpe"]),
|
||||
went_well=str(payload["went_well"]),
|
||||
to_improve=str(payload["to_improve"]),
|
||||
overall_feeling=str(payload["overall_feeling"]),
|
||||
reservation_phone=str(payload.get("reservation_phone", "")),
|
||||
techniques_practiced=str(payload.get("techniques_practiced", "")),
|
||||
warm_up_minutes=str(payload.get("warm_up_minutes", "")),
|
||||
pain_or_injury=str(payload.get("pain_or_injury", "none")),
|
||||
matches_won=_coerce_int(payload.get("matches_won", 0)),
|
||||
matches_lost=_coerce_int(payload.get("matches_lost", 0)),
|
||||
sets_won=_coerce_int(payload.get("sets_won", 0)),
|
||||
sets_lost=_coerce_int(payload.get("sets_lost", 0)),
|
||||
racket=str(payload.get("racket", "")),
|
||||
balls=str(payload.get("balls", "")),
|
||||
activity_type_other=activity_type_other,
|
||||
activity_details=str(payload.get("activity_details", "")),
|
||||
equipment=str(payload.get("equipment", "")),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Synced manual workout payload is malformed (%s: %s) — SKIPPING "
|
||||
"this record, so it will not be logged or counted on the PC",
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _draft_or_report(
|
||||
record_id: str, payload: Mapping[str, object]
|
||||
) -> ManualWorkoutDraft | None:
|
||||
"""Rebuild the draft, or report why it cannot be rebuilt and return None.
|
||||
|
||||
The two failure modes are deliberately reported at different levels, because
|
||||
only one of them is actionable:
|
||||
|
||||
* an **empty stub** carries no workout at all (seen as ``{type, kind,
|
||||
date}``) -- nothing to recover, nothing to fix, so re-reporting it at
|
||||
``warning`` on every 15-minute sync cycle only teaches the reader to
|
||||
ignore this logger;
|
||||
* a **malformed** payload has real workout fields that would not parse,
|
||||
which means genuine credit may be going missing -- that stays loud.
|
||||
"""
|
||||
if is_empty_stub(payload):
|
||||
_logger.info(
|
||||
"Manual record %s is an empty stub (keys: %s) — no workout data to "
|
||||
"ingest; skipping permanently, no credit is being lost",
|
||||
record_id,
|
||||
sorted(payload),
|
||||
)
|
||||
return None
|
||||
draft = reconstruct_draft(payload)
|
||||
if draft is None:
|
||||
_logger.warning(
|
||||
"Manual record %s is malformed — it HAS workout fields but they "
|
||||
"could not be parsed, so real credit may be lost",
|
||||
record_id,
|
||||
)
|
||||
return draft
|
||||
@ -1,12 +1,12 @@
|
||||
"""Manual (unverified) workout rate-limiting, validation, and entry-building.
|
||||
|
||||
Pure logic — no Tk imports. Manual-workout entries live directly in
|
||||
``log.json`` (not a separate history file): a manual
|
||||
Pure logic — no Tk imports. Unlike sick days, manual-workout entries live
|
||||
directly in ``workout_log.json`` (not a separate history file): a manual
|
||||
entry is just another ``workout_data`` dict with ``type="manual_workout"``,
|
||||
so ``LogMixin.save_workout_log`` already HMAC-signs it for free and the
|
||||
weekly-minimum/bonus logic already counts it once wired into
|
||||
``COUNTED_WORKOUT_TYPES``. This module only adds the rate-budget check (by
|
||||
scanning ``log.json`` itself) and the evidence-form validation.
|
||||
scanning ``workout_log.json`` itself) and the evidence-form validation.
|
||||
|
||||
Each sport has its own structured fields (e.g. table tennis tracks
|
||||
matches/sets won-lost and racket/balls, rather than one free-text blob) —
|
||||
@ -15,57 +15,156 @@ see :class:`ManualWorkoutDraft` and :data:`SPORT_CHOICES`.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_MIN_DURATION_MINUTES,
|
||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_RPE_MAX,
|
||||
MANUAL_WORKOUT_RPE_MIN,
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
)
|
||||
from screen_locker._manual_workout_checks import (
|
||||
validate_reflections,
|
||||
validate_required,
|
||||
)
|
||||
from screen_locker._manual_workout_types import (
|
||||
MANUAL_WORKOUT_TYPE,
|
||||
SPORT_CHOICES,
|
||||
SPORT_GLYPHS,
|
||||
SPORT_LABELS,
|
||||
SPORT_OTHER,
|
||||
SPORT_TABLE_TENNIS,
|
||||
ManualWorkoutDraft,
|
||||
budget_summary,
|
||||
count_in_window,
|
||||
is_budget_exhausted,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
|
||||
__all__ = [
|
||||
"MANUAL_WORKOUT_TYPE",
|
||||
"SPORT_CHOICES",
|
||||
"SPORT_GLYPHS",
|
||||
"SPORT_LABELS",
|
||||
"SPORT_OTHER",
|
||||
"SPORT_TABLE_TENNIS",
|
||||
"ManualWorkoutDraft",
|
||||
"budget_summary",
|
||||
"build_entry",
|
||||
"build_sync_payload",
|
||||
"count_in_window",
|
||||
"is_budget_exhausted",
|
||||
"manual_sync_record_id",
|
||||
"validate_manual_workout",
|
||||
]
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
MANUAL_WORKOUT_TYPE = "manual_workout"
|
||||
|
||||
SPORT_TABLE_TENNIS = "table_tennis"
|
||||
SPORT_OTHER = "other"
|
||||
SPORT_CHOICES: tuple[str, ...] = (SPORT_TABLE_TENNIS, SPORT_OTHER)
|
||||
SPORT_LABELS: dict[str, str] = {
|
||||
SPORT_TABLE_TENNIS: "Table tennis",
|
||||
SPORT_OTHER: "Other",
|
||||
}
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Workout log has an unparsable date key %r (%s) — that day is "
|
||||
"IGNORED when counting the manual-workout budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def count_in_window(
|
||||
log_file: Path,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many ``manual_workout`` ENTRIES fall in the trailing window.
|
||||
|
||||
Counted per entry, not per day: each logged manual workout consumes its
|
||||
own budget slot, matching how each one also earns its own weekly-count
|
||||
and shutdown credit (see ``screen_locker._weekly_check.COUNTED_WORKOUT_TYPES``
|
||||
and ``screen_locker._workout_credit``) — the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse.
|
||||
"""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
parsed = _parse_iso(date_str)
|
||||
if parsed is None or not (cutoff < parsed <= today_dt):
|
||||
continue
|
||||
count += sum(
|
||||
1
|
||||
for entry in entries
|
||||
if entry.get("workout_data", {}).get("type") == MANUAL_WORKOUT_TYPE
|
||||
)
|
||||
return count
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if either rolling window has reached its manual-workout budget."""
|
||||
return (
|
||||
count_in_window(log_file, 7, today=today) >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or count_in_window(log_file, 30, today=today)
|
||||
>= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_summary(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""One-line UI summary string for the manual-workout budget."""
|
||||
week = count_in_window(log_file, 7, today=today)
|
||||
month = count_in_window(log_file, 30, today=today)
|
||||
return (
|
||||
f"Manual: {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS}w · "
|
||||
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}m"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ManualWorkoutDraft:
|
||||
"""User-supplied evidence fields for a manual (unverified) workout.
|
||||
|
||||
Fields shared by every sport come first (required unless noted).
|
||||
Sport-specific fields follow, grouped by which ``sport`` they apply to —
|
||||
only the group matching ``sport`` is validated/persisted.
|
||||
"""
|
||||
|
||||
sport: str
|
||||
start_time: str # "HH:MM"
|
||||
end_time: str # "HH:MM"
|
||||
location_name: str
|
||||
transport_method: str
|
||||
cost: str
|
||||
rpe: int
|
||||
went_well: str
|
||||
to_improve: str
|
||||
overall_feeling: str
|
||||
reservation_phone: str = ""
|
||||
techniques_practiced: str = ""
|
||||
warm_up_minutes: str = ""
|
||||
pain_or_injury: str = "none"
|
||||
# SPORT_TABLE_TENNIS fields
|
||||
matches_won: int = 0
|
||||
matches_lost: int = 0
|
||||
sets_won: int = 0
|
||||
sets_lost: int = 0
|
||||
racket: str = ""
|
||||
balls: str = ""
|
||||
# SPORT_OTHER fields
|
||||
activity_type_other: str = ""
|
||||
activity_details: str = ""
|
||||
equipment: str = ""
|
||||
|
||||
|
||||
def _parse_hhmm(value: str) -> datetime | None:
|
||||
"""Parse an ``HH:MM`` string into a datetime on an arbitrary fixed date."""
|
||||
try:
|
||||
return datetime.strptime(value.strip(), "%H:%M").replace(tzinfo=UTC)
|
||||
return datetime.strptime(value.strip(), "%H:%M").replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Manual workout time %r is not HH:MM (%s) — the workout's duration "
|
||||
@ -87,18 +186,26 @@ def _duration_minutes(draft: ManualWorkoutDraft) -> float | None:
|
||||
|
||||
def validate_manual_workout(draft: ManualWorkoutDraft) -> str | None:
|
||||
"""Return an error message if the draft is invalid, else None."""
|
||||
error = validate_required(draft)
|
||||
if error is not None:
|
||||
return error
|
||||
if draft.sport not in SPORT_CHOICES:
|
||||
return "Please choose a sport"
|
||||
|
||||
required = {
|
||||
"Start time": draft.start_time,
|
||||
"End time": draft.end_time,
|
||||
"Location name": draft.location_name,
|
||||
"Transport method": draft.transport_method,
|
||||
"Cost": draft.cost,
|
||||
}
|
||||
for label, value in required.items():
|
||||
if not value.strip():
|
||||
return f"{label} is required"
|
||||
|
||||
duration = _duration_minutes(draft)
|
||||
if duration is None:
|
||||
return "Start/end time must be valid HH:MM, with end after start"
|
||||
# Accept bar carries the hidden leeway; the message advertises the round
|
||||
# number only (see _constants.py).
|
||||
if duration < WORKOUT_DURATION_ACCEPT_MINUTES:
|
||||
if duration < MANUAL_WORKOUT_MIN_DURATION_MINUTES:
|
||||
return (
|
||||
f"Session must be at least {MIN_WORKOUT_DURATION_MINUTES} "
|
||||
f"Session must be at least {MANUAL_WORKOUT_MIN_DURATION_MINUTES} "
|
||||
f"minutes (currently {duration:.0f})"
|
||||
)
|
||||
|
||||
@ -114,7 +221,18 @@ def validate_manual_workout(draft: ManualWorkoutDraft) -> str | None:
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
return validate_reflections(draft)
|
||||
for label, value in (
|
||||
("What went well", draft.went_well),
|
||||
("What to improve", draft.to_improve),
|
||||
("Overall feeling", draft.overall_feeling),
|
||||
):
|
||||
if len(value.strip()) < MANUAL_WORKOUT_REFLECTION_MIN_CHARS:
|
||||
return (
|
||||
f"{label} must be at least {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} "
|
||||
f"characters (currently {len(value.strip())})"
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _validate_table_tennis(draft: ManualWorkoutDraft) -> str | None:
|
||||
@ -127,7 +245,7 @@ def _validate_table_tennis(draft: ManualWorkoutDraft) -> str | None:
|
||||
):
|
||||
if value < 0:
|
||||
return f"{label} cannot be negative"
|
||||
if not draft.matches_won + draft.matches_lost:
|
||||
if draft.matches_won + draft.matches_lost == 0:
|
||||
return "Enter at least one match played (won + lost)"
|
||||
if not draft.racket.strip():
|
||||
return "Racket is required"
|
||||
@ -222,8 +340,8 @@ def build_sync_payload(draft: ManualWorkoutDraft, date: str) -> dict[str, object
|
||||
"""Build the cross-device sync payload for a manual workout.
|
||||
|
||||
This is the wire contract shared with the phone app: the same fields as
|
||||
:func:`build_entry` (what lands in ``log.json``), plus a ``kind``
|
||||
discriminator and the workout's own ``date``. ``log.json`` is
|
||||
:func:`build_entry` (what lands in ``workout_log.json``), plus a ``kind``
|
||||
discriminator and the workout's own ``date``. ``workout_log.json`` is
|
||||
day-keyed on the PC, but the synced payload must carry its date so the
|
||||
shared budget can be windowed and the entry filed in the right ISO week on
|
||||
ingest.
|
||||
|
||||
@ -1,44 +0,0 @@
|
||||
"""Field-level checks shared by ``validate_manual_workout``.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout` to keep every file under the
|
||||
250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from screen_locker._constants import MANUAL_WORKOUT_REFLECTION_MIN_CHARS
|
||||
from screen_locker._manual_workout_types import SPORT_CHOICES, ManualWorkoutDraft
|
||||
|
||||
|
||||
def validate_required(draft: ManualWorkoutDraft) -> str | None:
|
||||
"""Return an error if the sport is unchosen or a required field is blank."""
|
||||
if draft.sport not in SPORT_CHOICES:
|
||||
return "Please choose a sport"
|
||||
|
||||
required = {
|
||||
"Start time": draft.start_time,
|
||||
"End time": draft.end_time,
|
||||
"Location name": draft.location_name,
|
||||
"Transport method": draft.transport_method,
|
||||
"Cost": draft.cost,
|
||||
}
|
||||
for label, value in required.items():
|
||||
if not value.strip():
|
||||
return f"{label} is required"
|
||||
return None
|
||||
|
||||
|
||||
def validate_reflections(draft: ManualWorkoutDraft) -> str | None:
|
||||
"""Return an error if a reflection field is shorter than the minimum."""
|
||||
for label, value in (
|
||||
("What went well", draft.went_well),
|
||||
("What to improve", draft.to_improve),
|
||||
("Overall feeling", draft.overall_feeling),
|
||||
):
|
||||
if len(value.strip()) < MANUAL_WORKOUT_REFLECTION_MIN_CHARS:
|
||||
return (
|
||||
f"{label} must be at least {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} "
|
||||
f"characters (currently {len(value.strip())})"
|
||||
)
|
||||
|
||||
return None
|
||||
@ -1,137 +0,0 @@
|
||||
"""Workout-date field of the manual-workout form, and the future-dated path.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout_dialog` to keep every file
|
||||
under the 250-line cap; composed back into ``ManualWorkoutDialogMixin`` there,
|
||||
so both hosts (``ScreenLocker`` and ``StatusWindow``) are unchanged.
|
||||
|
||||
A manual workout may be dated today up to 7 days ahead. Today's takes the
|
||||
host's ordinary save path (which, on the lock screen, unlocks). A FUTURE one
|
||||
must not: it earns nothing today, so it is handed to ``_manual_schedule`` and
|
||||
the form shows a "scheduled" screen that returns to the host's cancelled hook
|
||||
-- never ``_on_manual_workout_saved``, which would unlock today.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_future import (
|
||||
budget_closed_for_all_days,
|
||||
is_future_date,
|
||||
validate_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import local_pending_records, pending_future_dates
|
||||
from screen_locker._manual_schedule import budget_error, schedule_future_workout
|
||||
from screen_locker._ui_widgets import disable_paste
|
||||
|
||||
if TYPE_CHECKING:
|
||||
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:
|
||||
"""Date row, budget gate and future-dated submission of the manual form."""
|
||||
|
||||
def _mw_budget_closed(self) -> bool:
|
||||
"""True if no day in today..today+7 has room (local ledger, no network)."""
|
||||
pending = pending_future_dates(self.log_file, local_pending_records())
|
||||
return budget_closed_for_all_days(self.log_file, pending.values())
|
||||
|
||||
def _mw_date_in_row(self, row: tk.Frame) -> None:
|
||||
"""Pack the workout-date entry (prefilled with today) into ``row``.
|
||||
|
||||
Called from the sport row rather than given a row of its own: the
|
||||
lock cannot scroll, and the form already fills a 768px panel
|
||||
(``scripts/verify_screen_fits.py``), so the field has to cost no height.
|
||||
"""
|
||||
var = tk.StringVar(value=today_str())
|
||||
self._mw_vars["date"] = var
|
||||
entry = tk.Entry(
|
||||
row,
|
||||
textvariable=var,
|
||||
width=11,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.palette.field_bg,
|
||||
fg=self._colors.palette.fg,
|
||||
insertbackground=self._colors.palette.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
entry.pack(side="right", padx=self._colors.space("xs"))
|
||||
disable_paste(entry)
|
||||
# Was "Workout date (today to +7 days):" -- a day square + the range.
|
||||
tk.Label(
|
||||
row,
|
||||
text="□ +0…+7",
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
).pack(side="right", padx=self._colors.space("xs"))
|
||||
|
||||
def _mw_handled_by_date(self, draft: ManualWorkoutDraft) -> bool:
|
||||
"""Apply the date and budget rules; True if the submit is fully handled.
|
||||
|
||||
Handled means an error is on screen or a future entry was scheduled;
|
||||
False means the date is today and within budget, so the caller
|
||||
carries on with the host's ordinary save.
|
||||
"""
|
||||
date = self._mw_vars["date"].get().strip()
|
||||
error = validate_workout_date(date)
|
||||
future = error is None and is_future_date(date)
|
||||
if error is None and not future:
|
||||
error = budget_error(self.log_file, date)
|
||||
if error is not None:
|
||||
self._mw_reject(error)
|
||||
return True
|
||||
if not future:
|
||||
return False
|
||||
result = schedule_future_workout(self.log_file, draft, date)
|
||||
if not result.scheduled:
|
||||
self._mw_reject(result.reason)
|
||||
return True
|
||||
_logger.info("Manual workout scheduled for %s: %s", date, result.reason)
|
||||
self._show_manual_workout_scheduled(date)
|
||||
return True
|
||||
|
||||
def _mw_reject(self, reason: str) -> None:
|
||||
"""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()
|
||||
# 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(
|
||||
SCHEDULED_GLYPH,
|
||||
role="display",
|
||||
scale=1.3,
|
||||
color=self._colors.palette.success,
|
||||
pad="lg",
|
||||
)
|
||||
self._text(date, role="subtitle", color=self._colors.palette.success)
|
||||
row = self._button_row()
|
||||
self._button(
|
||||
row,
|
||||
BACK_GLYPH,
|
||||
bg=self._colors.palette.accent,
|
||||
command=self._on_manual_workout_cancelled,
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
@ -21,55 +21,39 @@ import tkinter as tk
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
|
||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||
)
|
||||
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_widgets import ManualWorkoutFormWidgetsMixin
|
||||
|
||||
_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 = {
|
||||
label: code for code, label in _manual_workout.SPORT_LABELS.items()
|
||||
}
|
||||
|
||||
|
||||
class ManualWorkoutDialogMixin(
|
||||
ManualWorkoutDateMixin,
|
||||
ManualWorkoutFormWidgetsMixin,
|
||||
ManualWorkoutSportFieldsMixin,
|
||||
):
|
||||
class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
|
||||
"""Renders the manual-workout evidence form and handles submission."""
|
||||
|
||||
def _show_manual_workout_form(self) -> None:
|
||||
"""Render the manual-workout evidence form, or a budget-exhausted note."""
|
||||
self.clear_container()
|
||||
# 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():
|
||||
self._label(EXHAUSTED_GLYPH, color=self._colors.palette.danger, pad="xs")
|
||||
self._label("Log Manual Workout", color=self._colors.accent, pad="xs")
|
||||
if _manual_workout.is_budget_exhausted(self.log_file):
|
||||
self._text(
|
||||
"Manual-workout budget exhausted for this window.",
|
||||
color=self._colors.danger,
|
||||
)
|
||||
self._text(
|
||||
_manual_workout.budget_summary(self.log_file),
|
||||
color=self._colors.palette.muted,
|
||||
color=self._colors.muted,
|
||||
)
|
||||
row = self._button_row()
|
||||
self._button(
|
||||
row,
|
||||
BACK_GLYPH,
|
||||
bg=self._colors.palette.field_bg,
|
||||
"BACK",
|
||||
bg=self._colors.field_bg,
|
||||
command=self._on_manual_workout_cancelled,
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
@ -77,11 +61,45 @@ class ManualWorkoutDialogMixin(
|
||||
self._text(
|
||||
_manual_workout.budget_summary(self.log_file),
|
||||
role="label",
|
||||
color=self._colors.palette.accent,
|
||||
color=self._colors.accent,
|
||||
pad="xs",
|
||||
)
|
||||
self._build_manual_workout_form()
|
||||
|
||||
def _mw_scrollable_form(self) -> tk.Frame:
|
||||
"""Create the two-column form frame inside the surface's viewport.
|
||||
|
||||
This used to build its *own* ``Canvas`` + ``Scrollbar`` viewport, which
|
||||
had three problems that are all gone by deletion now that the surface
|
||||
container is itself a :class:`~gatelock.ScrollableSurface`:
|
||||
|
||||
1. **Scrolling was pointer-only.** ``tk.Canvas`` has no class-level key
|
||||
bindings, so ``::tk::FocusOK`` rejected it as a focus stop, and the
|
||||
canvas bound no ``<MouseWheel>``, ``<Prior>``/``<Next>`` or arrows.
|
||||
The scrollbar thumb had to be *dragged* -- inside a lock that cannot
|
||||
be dismissed without submitting this form.
|
||||
2. **Focus walked off-screen.** Canvas clipping does not unmap a child,
|
||||
so every below-the-fold field stayed ``winfo viewable`` and stayed in
|
||||
the tab ring while Tk never scrolled to follow focus. Tab led to
|
||||
fields the user could neither see nor bring into view.
|
||||
3. **The height was a magic fraction.** ``height=0.7 * toplevel`` sat
|
||||
above ~230-290px of fixed chrome (title, budget line, error label,
|
||||
and a 24pt button row), so the constraint was ``0.3 * H >= chrome``:
|
||||
satisfied at 1080p, violated at 768p, where SUBMIT/BACK were pushed
|
||||
off the bottom of a centred, unscrollable container.
|
||||
|
||||
Still built on the primary surface only -- an independently scrolled
|
||||
copy per monitor would show two different parts of one form.
|
||||
"""
|
||||
form = tk.Frame(self.container.first, bg=self._colors.bg)
|
||||
# No outer gap: the budget line above and the first section heading
|
||||
# below already separate the grid, and on a 1024x600 panel this form
|
||||
# fits by single-digit pixels.
|
||||
form.pack(fill="both", expand=True)
|
||||
form.grid_columnconfigure(0, weight=1, uniform="mw")
|
||||
form.grid_columnconfigure(1, weight=1, uniform="mw")
|
||||
return form
|
||||
|
||||
def _build_manual_workout_form(self) -> None:
|
||||
"""Build the two-column evidence form and submit/back buttons.
|
||||
|
||||
@ -98,28 +116,29 @@ class ManualWorkoutDialogMixin(
|
||||
self._mw_rpe_var = tk.IntVar(value=5)
|
||||
self._mw_text_widgets: dict[str, tk.Text] = {}
|
||||
|
||||
# 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_section(form, "Basics")
|
||||
self._mw_sport_row(form)
|
||||
self._mw_vars["start_time"] = self._mw_entry(form, "◷▶", focus=True)
|
||||
self._mw_vars["end_time"] = self._mw_entry(form, "◷■")
|
||||
self._mw_vars["start_time"] = self._mw_entry(
|
||||
form, "Start time (HH:MM):", focus=True
|
||||
)
|
||||
self._mw_vars["end_time"] = self._mw_entry(form, "End time (HH:MM):")
|
||||
|
||||
self._mw_section(form)
|
||||
self._mw_vars["location_name"] = self._mw_entry(form, "⌖")
|
||||
self._mw_vars["transport_method"] = self._mw_entry(form, "⇄")
|
||||
self._mw_vars["cost"] = self._mw_entry(form, "¤")
|
||||
self._mw_vars["reservation_phone"] = self._mw_entry(form, "(▯#)")
|
||||
self._mw_section(form, "Location & logistics")
|
||||
self._mw_vars["location_name"] = self._mw_entry(form, "Location name:")
|
||||
self._mw_vars["transport_method"] = self._mw_entry(
|
||||
form, "How did you get there?"
|
||||
)
|
||||
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)
|
||||
self._mw_section(form, "Activity details")
|
||||
# Both sport sub-frames occupy the same full-width grid slot; only the
|
||||
# selected one is shown (see _on_mw_sport_changed).
|
||||
act_row = self._mw_next_full_row(form)
|
||||
self._mw_tt_frame = tk.Frame(form, bg=self._colors.palette.bg)
|
||||
self._mw_other_frame = tk.Frame(form, bg=self._colors.palette.bg)
|
||||
self._mw_tt_frame = tk.Frame(form, bg=self._colors.bg)
|
||||
self._mw_other_frame = tk.Frame(form, bg=self._colors.bg)
|
||||
for sport_frame in (self._mw_tt_frame, self._mw_other_frame):
|
||||
sport_frame.grid_columnconfigure(0, weight=1, uniform="mwact")
|
||||
sport_frame.grid_columnconfigure(1, weight=1, uniform="mwact")
|
||||
@ -134,42 +153,161 @@ class ManualWorkoutDialogMixin(
|
||||
self._build_table_tennis_fields(self._mw_tt_frame)
|
||||
self._build_other_sport_fields(self._mw_other_frame)
|
||||
self._mw_rpe_row(form)
|
||||
# Was "Techniques/focus areas practiced (optional):", "Warm-up
|
||||
# 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(form, "(∿)")
|
||||
self._mw_vars["pain_or_injury"] = self._mw_entry(form, "(↯)")
|
||||
self._mw_vars["techniques_practiced"] = self._mw_entry(
|
||||
form, "Techniques/focus areas practiced (optional):"
|
||||
)
|
||||
self._mw_vars["warm_up_minutes"] = self._mw_entry(
|
||||
form, "Warm-up duration (optional):"
|
||||
)
|
||||
self._mw_vars["pain_or_injury"] = self._mw_entry(
|
||||
form, "Pain or injury notes (optional, default none):"
|
||||
)
|
||||
self._on_mw_sport_changed(
|
||||
_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||
)
|
||||
|
||||
# Was "Reflection", "What went well / What to improve / Overall
|
||||
# feeling about the session (min N chars):".
|
||||
self._mw_section(form)
|
||||
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(form, f"↑ {least}")
|
||||
self._mw_text_widgets["overall_feeling"] = self._mw_textbox(form, f"~ {least}")
|
||||
self._mw_section(form, "Reflection")
|
||||
self._mw_text_widgets["went_well"] = self._mw_textbox(
|
||||
form,
|
||||
f"What went well (min {MANUAL_WORKOUT_REFLECTION_MIN_CHARS} chars):",
|
||||
)
|
||||
self._mw_text_widgets["to_improve"] = self._mw_textbox(
|
||||
form,
|
||||
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(
|
||||
"", role="label", color=self._colors.palette.danger, pad="xs"
|
||||
"", role="label", color=self._colors.danger, pad="xs"
|
||||
)
|
||||
button_row = self._button_row()
|
||||
self._button(
|
||||
button_row,
|
||||
SUBMIT_GLYPH,
|
||||
bg=self._colors.palette.accent,
|
||||
"SUBMIT",
|
||||
bg=self._colors.accent,
|
||||
command=self._submit_manual_workout_form,
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._button(
|
||||
button_row,
|
||||
BACK_GLYPH,
|
||||
bg=self._colors.palette.field_bg,
|
||||
"BACK",
|
||||
bg=self._colors.field_bg,
|
||||
command=self._on_manual_workout_cancelled,
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
|
||||
def _mw_sport_row(self, parent: tk.Widget) -> None:
|
||||
"""Add the sport-selector radio buttons; swaps the activity section.
|
||||
|
||||
CANONICAL ACCOUNT OF THE 2026-07-26 BUG -- other files point here.
|
||||
|
||||
This was a ``tk.OptionMenu``. A posted Tk menu is a separate
|
||||
override-redirect toplevel that takes the Tk grab for itself, and
|
||||
gatelock's 1 s recovery tick killed it within a second of opening:
|
||||
``_surfaces.enforce()`` lifts the lock surface over the menu, and
|
||||
``_reassert_grab()`` saw the grab sitting on the menu rather than the
|
||||
root and yanked it back. The selector stayed stuck on "Table tennis"
|
||||
while locked, and a walk got logged in the table-tennis form.
|
||||
|
||||
Radio buttons are ordinary children of the surface: they lift with it
|
||||
and live inside the root's grab tree, so neither mechanism can reach
|
||||
them. Nothing on a lock surface may open a popup window --
|
||||
``tests/test_no_popup_widgets.py`` enforces that statically and
|
||||
``scripts/verify_lock_popup_safety.py`` behaviourally.
|
||||
"""
|
||||
self._mw_sport_var = tk.StringVar(
|
||||
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||
)
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
row,
|
||||
text="Sport:",
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
for label in _manual_workout.SPORT_LABELS.values():
|
||||
tk.Radiobutton(
|
||||
row,
|
||||
text=label,
|
||||
value=label,
|
||||
variable=self._mw_sport_var,
|
||||
# Radiobutton's command takes no argument -- bind the label.
|
||||
command=lambda chosen=label: self._on_mw_sport_changed(chosen),
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
activeforeground=self._colors.fg,
|
||||
activebackground=self._colors.bg,
|
||||
# Without selectcolor the indicator is a white blob on the dark
|
||||
# overlay; the OptionMenu was the one unstyled widget in this
|
||||
# form, which likely added to it reading as dead.
|
||||
selectcolor=self._colors.field_bg,
|
||||
highlightthickness=0,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
self._mw_grid(parent, row, full=True)
|
||||
|
||||
def _on_mw_sport_changed(self, selected_label: str) -> None:
|
||||
"""Show the fields for the newly-selected sport, hide the other's.
|
||||
|
||||
Both frames share one grid slot; ``grid_remove`` hides a frame while
|
||||
remembering its cell options so ``grid`` restores it in place.
|
||||
"""
|
||||
sport = _SPORT_LABEL_TO_CODE.get(
|
||||
selected_label, _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
if sport == _manual_workout.SPORT_TABLE_TENNIS:
|
||||
self._mw_other_frame.grid_remove()
|
||||
self._mw_tt_frame.grid()
|
||||
else:
|
||||
self._mw_tt_frame.grid_remove()
|
||||
self._mw_other_frame.grid()
|
||||
|
||||
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the table-tennis-specific score/equipment fields."""
|
||||
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "Matches won:")
|
||||
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "Matches lost:")
|
||||
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "Sets won:")
|
||||
self._mw_int_vars["sets_lost"] = self._mw_int_field(parent, "Sets lost:")
|
||||
self._mw_vars["racket"] = self._mw_entry(parent, "Racket used:")
|
||||
self._mw_vars["balls"] = self._mw_entry(parent, "Balls used:")
|
||||
|
||||
def _build_other_sport_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the generic "other sport" fields."""
|
||||
self._mw_vars["activity_type_other"] = self._mw_entry(
|
||||
parent, "What sport/activity:"
|
||||
)
|
||||
self._mw_text_widgets["activity_details"] = self._mw_textbox(
|
||||
parent,
|
||||
f"What was done (min {MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS} chars):",
|
||||
)
|
||||
self._mw_vars["equipment"] = self._mw_entry(
|
||||
parent, "Equipment used (optional):"
|
||||
)
|
||||
|
||||
def _current_mw_sport(self) -> str:
|
||||
"""Return the internal sport code for the currently-selected label."""
|
||||
return _SPORT_LABEL_TO_CODE.get(
|
||||
self._mw_sport_var.get(), _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
|
||||
def _mw_int_value(self, key: str) -> int:
|
||||
"""Read an int Spinbox var, defaulting to 0 on an invalid value."""
|
||||
try:
|
||||
return int(self._mw_int_vars[key].get())
|
||||
except (tk.TclError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Manual workout field %r holds a non-integer value (%s) — "
|
||||
"recording it as 0",
|
||||
key,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
def _submit_manual_workout_form(self) -> None:
|
||||
"""Validate the form and either show an error or save + notify host."""
|
||||
try:
|
||||
@ -211,11 +349,7 @@ class ManualWorkoutDialogMixin(
|
||||
)
|
||||
error = _manual_workout.validate_manual_workout(draft)
|
||||
if error is not None:
|
||||
# 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
|
||||
if self._mw_handled_by_date(draft):
|
||||
self._mw_error_label.config(text=error)
|
||||
return
|
||||
entry = _manual_workout.build_entry(draft)
|
||||
# Record the manual for cross-device sync (published on the next lock
|
||||
|
||||
@ -1,131 +0,0 @@
|
||||
"""Sport-specific rows of the manual-workout evidence form.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout_dialog` to keep every file
|
||||
under the 250-line cap. Composed back into ``ManualWorkoutDialogMixin`` there,
|
||||
so both host classes (``ScreenLocker`` and ``StatusWindow``) are unchanged.
|
||||
|
||||
Choosing a sport swaps in that sport's fields rather than showing one generic
|
||||
free-text blob -- see ``_manual_workout.SPORT_CHOICES``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tkinter as tk
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._constants import MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_SPORT_LABEL_TO_CODE = {
|
||||
label: code for code, label in _manual_workout.SPORT_LABELS.items()
|
||||
}
|
||||
|
||||
|
||||
class ManualWorkoutSportFieldsMixin:
|
||||
"""Builds the sport picker and the per-sport detail rows."""
|
||||
|
||||
def _mw_sport_row(self, parent: tk.Widget) -> None:
|
||||
"""Add the sport-selector radio buttons; swaps the activity section.
|
||||
|
||||
CANONICAL ACCOUNT OF THE 2026-07-26 BUG -- other files point here.
|
||||
|
||||
This was a ``tk.OptionMenu``. A posted Tk menu is a separate
|
||||
override-redirect toplevel that takes the Tk grab for itself, and
|
||||
gatelock's 1 s recovery tick killed it within a second of opening:
|
||||
``_surfaces.enforce()`` lifts the lock surface over the menu, and
|
||||
``_reassert_grab()`` saw the grab sitting on the menu rather than the
|
||||
root and yanked it back. The selector stayed stuck on "Table tennis"
|
||||
while locked, and a walk got logged in the table-tennis form.
|
||||
|
||||
Radio buttons are ordinary children of the surface: they lift with it
|
||||
and live inside the root's grab tree, so neither mechanism can reach
|
||||
them. Nothing on a lock surface may open a popup window --
|
||||
``tests/test_no_popup_widgets.py`` enforces that statically and
|
||||
``scripts/verify_lock_popup_safety.py`` behaviourally.
|
||||
"""
|
||||
self._mw_sport_var = tk.StringVar(
|
||||
value=_manual_workout.SPORT_LABELS[_manual_workout.SPORT_TABLE_TENNIS]
|
||||
)
|
||||
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||
# textgate: the "Sport:" caption is gone; the radio row is the cue.
|
||||
for code, label in _manual_workout.SPORT_LABELS.items():
|
||||
tk.Radiobutton(
|
||||
row,
|
||||
text=_manual_workout.SPORT_GLYPHS[code],
|
||||
value=label,
|
||||
variable=self._mw_sport_var,
|
||||
# Radiobutton's command takes no argument -- bind the label.
|
||||
command=lambda chosen=label: self._on_mw_sport_changed(chosen),
|
||||
font=self._colors.font("body"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
activeforeground=self._colors.palette.fg,
|
||||
activebackground=self._colors.palette.bg,
|
||||
# Without selectcolor the indicator is a white blob on the dark
|
||||
# overlay; the OptionMenu was the one unstyled widget in this
|
||||
# form, which likely added to it reading as dead.
|
||||
selectcolor=self._colors.palette.field_bg,
|
||||
highlightthickness=0,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
# The workout-date field rides in this row, at no extra height.
|
||||
self._mw_date_in_row(row)
|
||||
self._mw_grid(parent, row, full=True)
|
||||
|
||||
def _on_mw_sport_changed(self, selected_label: str) -> None:
|
||||
"""Show the fields for the newly-selected sport, hide the other's.
|
||||
|
||||
Both frames share one grid slot; ``grid_remove`` hides a frame while
|
||||
remembering its cell options so ``grid`` restores it in place.
|
||||
"""
|
||||
sport = _SPORT_LABEL_TO_CODE.get(
|
||||
selected_label, _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
if sport == _manual_workout.SPORT_TABLE_TENNIS:
|
||||
self._mw_other_frame.grid_remove()
|
||||
self._mw_tt_frame.grid()
|
||||
else:
|
||||
self._mw_tt_frame.grid_remove()
|
||||
self._mw_other_frame.grid()
|
||||
|
||||
def _build_table_tennis_fields(self, parent: tk.Widget) -> None:
|
||||
"""Build the table-tennis-specific score/equipment fields."""
|
||||
# textgate: was "Matches won/lost:", "Sets won/lost:", "Racket used:",
|
||||
# "Balls used:". Match / set glyph + win / loss mark.
|
||||
self._mw_int_vars["matches_won"] = self._mw_int_field(parent, "◍✓")
|
||||
self._mw_int_vars["matches_lost"] = self._mw_int_field(parent, "◍✗")
|
||||
self._mw_int_vars["sets_won"] = self._mw_int_field(parent, "▤✓")
|
||||
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:
|
||||
"""Build the generic "other sport" fields."""
|
||||
# Was "What sport/activity:" / "What was done (min N chars):" /
|
||||
# "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(
|
||||
parent,
|
||||
f"✱≡ ≥{MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS}",
|
||||
)
|
||||
self._mw_vars["equipment"] = self._mw_entry(parent, "(⊡)")
|
||||
|
||||
def _current_mw_sport(self) -> str:
|
||||
"""Return the internal sport code for the currently-selected label."""
|
||||
return _SPORT_LABEL_TO_CODE.get(
|
||||
self._mw_sport_var.get(), _manual_workout.SPORT_TABLE_TENNIS
|
||||
)
|
||||
|
||||
def _mw_int_value(self, key: str) -> int:
|
||||
"""Read an int Spinbox var, defaulting to 0 on an invalid value."""
|
||||
try:
|
||||
return int(self._mw_int_vars[key].get())
|
||||
except (tk.TclError, ValueError) as exc:
|
||||
_logger.warning(
|
||||
"Manual workout field %r holds a non-integer value (%s) — "
|
||||
"recording it as 0",
|
||||
key,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
@ -1,188 +0,0 @@
|
||||
"""Manual-workout sports, the draft record, and rolling budget accounting.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout` to keep every file under the
|
||||
250-line cap. Everything here is re-exported from there, so callers and their
|
||||
patch targets are unchanged.
|
||||
|
||||
The budget is what stops a manual entry from being an unlimited escape hatch:
|
||||
manual workouts are self-reported, so only a few count in any rolling window.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
)
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._weekly_check import credit_key, day_workout_index
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
MANUAL_WORKOUT_TYPE = "manual_workout"
|
||||
|
||||
SPORT_TABLE_TENNIS = "table_tennis"
|
||||
SPORT_OTHER = "other"
|
||||
SPORT_CHOICES: tuple[str, ...] = (SPORT_TABLE_TENNIS, SPORT_OTHER)
|
||||
SPORT_LABELS: dict[str, str] = {
|
||||
SPORT_TABLE_TENNIS: "Table tennis",
|
||||
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:
|
||||
"""Return today's LOCAL date as ``YYYY-MM-DD`` (see ``screen_locker._day``)."""
|
||||
return today_str()
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or return None."""
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=UTC)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Workout log has an unparsable date key %r (%s) — that day is "
|
||||
"IGNORED when counting the manual-workout budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def manual_credit_dates(log_file: Path) -> list[str]:
|
||||
"""Return the ``YYYY-MM-DD`` of every manual-workout CREDIT in the log.
|
||||
|
||||
One element per workout, decided by
|
||||
:func:`screen_locker._weekly_check.credit_key` -- the single rule every
|
||||
counter shares -- so a synced copy of a workout already logged here is the
|
||||
same credit, not a second budget slot (2026-09-13: a manual rekeyed to its
|
||||
local day, then pulled back in under a fresh workout_id, consumed two
|
||||
slots while the weekly count correctly saw one). Dates that do not parse
|
||||
are warned about by :func:`_parse_iso` and left out.
|
||||
"""
|
||||
dates: list[str] = []
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
if _parse_iso(date_str) is None:
|
||||
continue
|
||||
siblings = day_workout_index(entries)
|
||||
keys = {
|
||||
key
|
||||
for index, entry in enumerate(entries)
|
||||
if (key := credit_key(date_str, index, entry, siblings)) is not None
|
||||
and key[0] == MANUAL_WORKOUT_TYPE
|
||||
}
|
||||
dates.extend([date_str] * len(keys))
|
||||
return dates
|
||||
|
||||
|
||||
def count_in_window(
|
||||
log_file: Path,
|
||||
days: int,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> int:
|
||||
"""Return how many manual-workout CREDITS fall in the trailing window.
|
||||
|
||||
Counted per workout, not per day: each logged manual workout consumes its
|
||||
own budget slot, matching how each one also earns its own weekly-count
|
||||
and shutdown credit (see ``screen_locker._weekly_check.COUNTED_WORKOUT_TYPES``
|
||||
and ``screen_locker._workout_credit``) -- the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse. See
|
||||
:func:`manual_credit_dates` for what "one workout" means.
|
||||
|
||||
The window is the ``days`` days ending at ``today`` (inclusive); entries
|
||||
dated after today are NOT in it. Whether a new entry fits is a different
|
||||
question, answered per workout date by ``_manual_future``.
|
||||
"""
|
||||
day = today or _today_iso()
|
||||
today_dt = _parse_iso(day)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
return sum(
|
||||
1
|
||||
for date_str in manual_credit_dates(log_file)
|
||||
if (parsed := _parse_iso(date_str)) is not None and cutoff < parsed <= today_dt
|
||||
)
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""Return True if either rolling window has reached its manual-workout budget."""
|
||||
return (
|
||||
count_in_window(log_file, 7, today=today) >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or count_in_window(log_file, 30, today=today)
|
||||
>= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_summary(
|
||||
log_file: Path,
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> str:
|
||||
"""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)
|
||||
month = count_in_window(log_file, 30, today=today)
|
||||
return (
|
||||
f"≡ {week}/{MANUAL_WORKOUT_BUDGET_PER_7_DAYS} · "
|
||||
f"{month}/{MANUAL_WORKOUT_BUDGET_PER_30_DAYS}"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ManualWorkoutDraft:
|
||||
"""User-supplied evidence fields for a manual (unverified) workout.
|
||||
|
||||
Fields shared by every sport come first (required unless noted).
|
||||
Sport-specific fields follow, grouped by which ``sport`` they apply to —
|
||||
only the group matching ``sport`` is validated/persisted.
|
||||
"""
|
||||
|
||||
sport: str
|
||||
start_time: str # "HH:MM"
|
||||
end_time: str # "HH:MM"
|
||||
location_name: str
|
||||
transport_method: str
|
||||
cost: str
|
||||
rpe: int
|
||||
went_well: str
|
||||
to_improve: str
|
||||
overall_feeling: str
|
||||
reservation_phone: str = ""
|
||||
techniques_practiced: str = ""
|
||||
warm_up_minutes: str = ""
|
||||
pain_or_injury: str = "none"
|
||||
# SPORT_TABLE_TENNIS fields
|
||||
matches_won: int = 0
|
||||
matches_lost: int = 0
|
||||
sets_won: int = 0
|
||||
sets_lost: int = 0
|
||||
racket: str = ""
|
||||
balls: str = ""
|
||||
# SPORT_OTHER fields
|
||||
activity_type_other: str = ""
|
||||
activity_details: str = ""
|
||||
equipment: str = ""
|
||||
@ -66,10 +66,17 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
counters[id(parent)] = idx + 2
|
||||
return idx // 2
|
||||
|
||||
def _mw_section(self, parent: tk.Widget) -> None:
|
||||
"""Add a full-width rule between form sections (was a heading)."""
|
||||
rule = tk.Frame(parent, bg=self._colors.palette.accent, height=2)
|
||||
self._mw_grid(parent, rule, full=True)
|
||||
def _mw_section(self, parent: tk.Widget, title: str) -> None:
|
||||
"""Add a full-width section heading inside the form."""
|
||||
label = tk.Label(
|
||||
parent,
|
||||
text=title,
|
||||
font=self._colors.font("body", bold=True),
|
||||
fg=self._colors.accent,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
)
|
||||
self._mw_grid(parent, label, full=True)
|
||||
|
||||
def _mw_entry(
|
||||
self, parent: tk.Widget, label: str, *, focus: bool = False
|
||||
@ -77,7 +84,7 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
"""Add a half-width label+entry cell and return its backing StringVar.
|
||||
|
||||
Builds its own cell inline (rather than reusing ``_add_label_entry``,
|
||||
which is pack-based) so it slots into
|
||||
which is pack-based and shared with the sick dialog) so it slots into
|
||||
the two-column grid. Paste stays disabled via ``disable_paste``.
|
||||
|
||||
Args:
|
||||
@ -88,7 +95,7 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
one field per form should ask.
|
||||
"""
|
||||
var = tk.StringVar()
|
||||
cell = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||
cell = tk.Frame(parent, bg=self._colors.bg)
|
||||
# Label beside the field, not above it. Stacked, each of the ten cells
|
||||
# cost two lines plus the gap between them, and the form measured
|
||||
# 1320px against a 768px panel; side-by-side each cell is one line
|
||||
@ -98,17 +105,17 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
cell,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(side="left", padx=(0, self._colors.space("xs")))
|
||||
entry = tk.Entry(
|
||||
cell,
|
||||
textvariable=var,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.palette.field_bg,
|
||||
fg=self._colors.palette.fg,
|
||||
insertbackground=self._colors.palette.fg,
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
entry.pack(side="left", fill="x", expand=True)
|
||||
@ -123,13 +130,13 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
) -> tk.IntVar:
|
||||
"""Add a half-width label + numeric Spinbox and return its IntVar."""
|
||||
var = tk.IntVar(value=0)
|
||||
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
row,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
tk.Spinbox(
|
||||
row,
|
||||
@ -150,22 +157,22 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
whole rows of a form that has to fit a 768px panel, and two of them
|
||||
sit side by side just as legibly.
|
||||
"""
|
||||
cell = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||
cell = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
cell,
|
||||
text=label,
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
anchor="w",
|
||||
).pack(fill="x")
|
||||
text_widget = tk.Text(
|
||||
cell,
|
||||
height=2,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.palette.field_bg,
|
||||
fg=self._colors.palette.fg,
|
||||
insertbackground=self._colors.palette.fg,
|
||||
bg=self._colors.field_bg,
|
||||
fg=self._colors.fg,
|
||||
insertbackground=self._colors.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
text_widget.pack(pady=self._colors.space("xs"), fill="x")
|
||||
@ -180,14 +187,16 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
|
||||
def _mw_rpe_row(self, parent: tk.Widget) -> None:
|
||||
"""Add the RPE (rate of perceived exertion) spinbox row."""
|
||||
row = tk.Frame(parent, bg=self._colors.palette.bg)
|
||||
row = tk.Frame(parent, bg=self._colors.bg)
|
||||
tk.Label(
|
||||
row,
|
||||
# Was "RPE — perceived exertion (1-10):": effort bars + range.
|
||||
text=f"▁▃▅▇ {MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}",
|
||||
text=(
|
||||
f"RPE — perceived exertion "
|
||||
f"({MANUAL_WORKOUT_RPE_MIN}-{MANUAL_WORKOUT_RPE_MAX}):"
|
||||
),
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
fg=self._colors.fg,
|
||||
bg=self._colors.bg,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
tk.Spinbox(
|
||||
row,
|
||||
@ -199,37 +208,3 @@ class ManualWorkoutFormWidgetsMixin:
|
||||
**self._colors.focus_kwargs(),
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
self._mw_grid(parent, row)
|
||||
|
||||
def _mw_scrollable_form(self) -> tk.Frame:
|
||||
"""Create the two-column form frame inside the surface's viewport.
|
||||
|
||||
This used to build its *own* ``Canvas`` + ``Scrollbar`` viewport, which
|
||||
had three problems that are all gone by deletion now that the surface
|
||||
container is itself a :class:`~gatelock.ScrollableSurface`:
|
||||
|
||||
1. **Scrolling was pointer-only.** ``tk.Canvas`` has no class-level key
|
||||
bindings, so ``::tk::FocusOK`` rejected it as a focus stop, and the
|
||||
canvas bound no ``<MouseWheel>``, ``<Prior>``/``<Next>`` or arrows.
|
||||
The scrollbar thumb had to be *dragged* -- inside a lock that cannot
|
||||
be dismissed without submitting this form.
|
||||
2. **Focus walked off-screen.** Canvas clipping does not unmap a child,
|
||||
so every below-the-fold field stayed ``winfo viewable`` and stayed in
|
||||
the tab ring while Tk never scrolled to follow focus. Tab led to
|
||||
fields the user could neither see nor bring into view.
|
||||
3. **The height was a magic fraction.** ``height=0.7 * toplevel`` sat
|
||||
above ~230-290px of fixed chrome (title, budget line, error label,
|
||||
and a 24pt button row), so the constraint was ``0.3 * H >= chrome``:
|
||||
satisfied at 1080p, violated at 768p, where SUBMIT/BACK were pushed
|
||||
off the bottom of a centred, unscrollable container.
|
||||
|
||||
Still built on the primary surface only -- an independently scrolled
|
||||
copy per monitor would show two different parts of one form.
|
||||
"""
|
||||
form = tk.Frame(self.container.first, bg=self._colors.palette.bg)
|
||||
# No outer gap: the budget line above and the first section heading
|
||||
# below already separate the grid, and on a 1024x600 panel this form
|
||||
# fits by single-digit pixels.
|
||||
form.pack(fill="both", expand=True)
|
||||
form.grid_columnconfigure(0, weight=1, uniform="mw")
|
||||
form.grid_columnconfigure(1, weight=1, uniform="mw")
|
||||
return form
|
||||
|
||||
@ -23,8 +23,8 @@ Safety invariants (do not break when adding tools):
|
||||
calls must never write to stdout. All logging is routed to STDERR below,
|
||||
and no tool calls ``screen_lock.py`` / ``status_view.main`` (which
|
||||
``print`` / open Tk windows / ``sys.exit``).
|
||||
* **No secret ever leaves.** No tool returns the Firebase session
|
||||
(``~/.config/screen_locker/firebase_auth.json``) or any HMAC key; the predicates
|
||||
* **No secret ever leaves.** No tool returns the sync token
|
||||
(``~/.config/screen_locker/sync_token``) or any HMAC key; the predicates
|
||||
load only status/state and return booleans, and the status snapshot
|
||||
carries no secret material.
|
||||
"""
|
||||
@ -48,9 +48,11 @@ from screen_locker._compliance_state import (
|
||||
)
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_PENDING_FILE,
|
||||
SCHEDULED_SKIPS_FILE,
|
||||
)
|
||||
from screen_locker._sick_tracker import load_history
|
||||
from screen_locker._status_data import format_summary_line, gather_status
|
||||
from screen_locker._status_projection import compliance_state_word
|
||||
from screen_locker.status_view import _compliance_state_word
|
||||
|
||||
# Log to STDERR only — STDOUT carries the MCP JSON-RPC protocol frames, so a
|
||||
# single stray stdout write would corrupt the stream and kill the session.
|
||||
@ -63,7 +65,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
mcp = MCPServer("screen-locker")
|
||||
|
||||
# Every tool here only reads local state: the workout log, the sickdays pool
|
||||
# Every tool here only reads local state: the workout log, the sick history
|
||||
# and the clock. Saying so lets a client run them without asking -- and the
|
||||
# day one of them stops being read-only, this annotation is the thing that
|
||||
# has to change with it. (See the section banner below: "never mutate" was
|
||||
@ -77,7 +79,7 @@ _READS_ONLY = ToolAnnotations(
|
||||
# The workout log lives beside the package, same default as
|
||||
# ``_status_data._DEFAULT_LOG_FILE``; declared here to avoid importing a
|
||||
# private name across modules.
|
||||
_LOG_FILE = Path(__file__).resolve().parent / "log.json"
|
||||
_LOG_FILE = Path(__file__).resolve().parent / "workout_log.json"
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@ -91,7 +93,7 @@ def get_status() -> dict[str, Any]:
|
||||
|
||||
A JSON-friendly projection of ``gather_status()``: today's and this week's
|
||||
workout outcomes, the shutdown-time projection, the lock-decision trace,
|
||||
and the rolling manual-workout budget. Reads on-disk state
|
||||
and the rolling sick-day / manual-workout budgets. Reads on-disk state
|
||||
only (no ADB, sudo, or network) and never mutates anything.
|
||||
"""
|
||||
return asdict(gather_status())
|
||||
@ -103,12 +105,12 @@ def get_summary() -> dict[str, Any]:
|
||||
|
||||
``summary_line`` is the same string the status bar shows
|
||||
(``format_summary_line``); ``compliance_state`` is one of ``ok`` / ``warn``
|
||||
/ ``lock`` (``compliance_state_word``).
|
||||
/ ``lock`` (``_compliance_state_word``).
|
||||
"""
|
||||
snapshot = gather_status()
|
||||
return {
|
||||
"summary_line": format_summary_line(snapshot),
|
||||
"compliance_state": compliance_state_word(snapshot),
|
||||
"compliance_state": _compliance_state_word(snapshot),
|
||||
}
|
||||
|
||||
|
||||
@ -131,21 +133,13 @@ def get_flags() -> dict[str, bool]:
|
||||
Each predicate reads its own on-disk state file and degrades to ``False``
|
||||
when that file is missing or unreadable — none of them mutate state or
|
||||
expose secrets.
|
||||
|
||||
``is_scheduled_skip_today`` keeps its name but no longer reads this app's
|
||||
``scheduled_skips.json``: it is now the shared, fleet-wide free-day pool
|
||||
(``~/src/utils/freedays``), so a true here also means diet-guard, wake-alarm,
|
||||
leetcode-guard and home-guard are standing down today.
|
||||
|
||||
``is_sick_day_today`` reads the shared ``sickdays`` pool and answers "is the
|
||||
workout lock switched off today": a sick day that keeps the ``workout``
|
||||
locker reads False. Never a screen-locker file.
|
||||
"""
|
||||
history = load_history()
|
||||
return {
|
||||
"has_logged_today": has_logged_today(_LOG_FILE),
|
||||
"is_scheduled_skip_today": is_scheduled_skip_today(),
|
||||
"is_scheduled_skip_today": is_scheduled_skip_today(SCHEDULED_SKIPS_FILE),
|
||||
"is_early_bird_pending": is_early_bird_pending(EARLY_BIRD_PENDING_FILE),
|
||||
"is_sick_day_today": is_sick_day_today(),
|
||||
"is_sick_day_today": is_sick_day_today(history),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -1,56 +0,0 @@
|
||||
"""Read the morning-session carrot the wake-alarm service signed for today.
|
||||
|
||||
The reader itself is ``gatelock.morning_session``, shared with leetcode-guard
|
||||
and book-guard; this module only binds screen-locker's path and retry budget,
|
||||
which the test suite redirects. The policy lives in wake-alarm: the only
|
||||
decision anywhere is *HMAC ok, dated today, now < exempt_until*.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock.morning_session import (
|
||||
MORNING_RETRY_SECONDS as _SHARED_RETRY_SECONDS,
|
||||
)
|
||||
from gatelock.morning_session import (
|
||||
MorningSkip,
|
||||
morning_skip,
|
||||
)
|
||||
|
||||
from screen_locker._constants import MORNING_SESSION_FILE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
|
||||
__all__ = ["MorningSkip", "has_workout_skip_today", "morning_skip_today"]
|
||||
|
||||
MORNING_RETRY_SECONDS: float = _SHARED_RETRY_SECONDS
|
||||
|
||||
|
||||
def morning_skip_today(
|
||||
now: datetime | None = None,
|
||||
*,
|
||||
wait: bool,
|
||||
sleep: Callable[[float], None] = time.sleep,
|
||||
) -> MorningSkip | None:
|
||||
"""The skip the morning session earned, or None.
|
||||
|
||||
With ``wait`` (the enforce path only), a file that is not today's during
|
||||
the morning window is retried so a freshly booted PC gives wake-alarm's
|
||||
catch-up run a chance to land.
|
||||
"""
|
||||
return morning_skip(
|
||||
MORNING_SESSION_FILE,
|
||||
now,
|
||||
wait=wait,
|
||||
retry_seconds=MORNING_RETRY_SECONDS,
|
||||
sleep=sleep,
|
||||
)
|
||||
|
||||
|
||||
def has_workout_skip_today() -> bool:
|
||||
"""Whether the morning session earned a skip right now. Never waits."""
|
||||
return morning_skip_today(wait=False) is not None
|
||||
@ -1,70 +0,0 @@
|
||||
"""The workout lock does not re-arm after tonight's evening night-lockdown.
|
||||
|
||||
The predicate itself is ``gatelock.night_lockdown``, shared with
|
||||
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
|
||||
the ladder rung that honours it.
|
||||
|
||||
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
|
||||
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
|
||||
stamp means "no lockdown": the workout lock behaves exactly as before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock.night_lockdown import (
|
||||
NIGHT_LOCKDOWN_STAMP as _SHARED_STAMP,
|
||||
)
|
||||
from gatelock.night_lockdown import (
|
||||
evening_lockdown_today,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"EVENING_LOCKDOWN_REASON",
|
||||
"NIGHT_LOCKDOWN_STAMP",
|
||||
"has_evening_lockdown_today",
|
||||
"skip_after_evening_lockdown",
|
||||
"tonights_lockdown",
|
||||
]
|
||||
|
||||
NIGHT_LOCKDOWN_STAMP: Path = _SHARED_STAMP
|
||||
|
||||
EVENING_LOCKDOWN_REASON = "evening_lockdown_today"
|
||||
|
||||
|
||||
def tonights_lockdown(now: datetime | None = None) -> datetime | None:
|
||||
"""When tonight's evening lockdown locked, or None if it has not yet."""
|
||||
return evening_lockdown_today(NIGHT_LOCKDOWN_STAMP, now)
|
||||
|
||||
|
||||
def has_evening_lockdown_today() -> bool:
|
||||
"""Whether tonight's evening lockdown already happened. Read-only."""
|
||||
return tonights_lockdown() is not None
|
||||
|
||||
|
||||
def skip_after_evening_lockdown(record_skip: Callable[..., None]) -> bool:
|
||||
"""Skip enforcement once tonight's evening lockdown has fired.
|
||||
|
||||
Takes the locker's ``_record_skip`` (which exits the process) rather than
|
||||
the locker, like ``_lock_invariant``. Returns True when the skip was
|
||||
recorded, False when the lock may go ahead.
|
||||
"""
|
||||
locked_at = tonights_lockdown()
|
||||
if locked_at is None:
|
||||
return False
|
||||
record_skip(
|
||||
EVENING_LOCKDOWN_REASON,
|
||||
f"Tonight's night lockdown already locked at {locked_at:%H:%M}; the "
|
||||
"workout lock does not re-arm after it.",
|
||||
locked_at=locked_at.isoformat(),
|
||||
)
|
||||
return True
|
||||
@ -1,22 +1,29 @@
|
||||
"""Phone workout verification: Firebase sync first, ADB/HTTP as fallback."""
|
||||
"""Phone workout verification: GitHub sync first, ADB/HTTP as fallback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from concurrent.futures import ( # pylint: disable=no-name-in-module
|
||||
ThreadPoolExecutor,
|
||||
as_completed,
|
||||
)
|
||||
import contextlib
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from http import client as _http_client
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from screen_locker._adb_transport import AdbTransportMixin
|
||||
from screen_locker._constants import (
|
||||
ADB_TIMEOUT,
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
WORKOUT_APP_JSON_REMOTES,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
WORKOUT_HTTP_PORT,
|
||||
)
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._http_workout_fetch import HttpWorkoutFetchMixin
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._time_check import check_clock_skew
|
||||
from screen_locker._workout_sync import pull_synced_workout
|
||||
@ -28,21 +35,116 @@ _HTTP_OK = _http_client.OK
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _in_current_week(date_str: str) -> bool:
|
||||
"""True if *date_str* parses and falls in this ISO week up to today."""
|
||||
today = datetime.now(tz=UTC).astimezone().date()
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
try:
|
||||
entry_date = date.fromisoformat(date_str)
|
||||
except ValueError:
|
||||
_logger.warning("StrongLifts JSON has an unparsable date: %r", date_str)
|
||||
return False
|
||||
return week_start <= entry_date <= today
|
||||
|
||||
|
||||
class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
class PhoneVerificationMixin:
|
||||
"""Mixin providing phone-based workout verification via ADB."""
|
||||
|
||||
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
|
||||
"""Run an ADB command and return success flag and stdout."""
|
||||
adb = shutil.which("adb") or "adb"
|
||||
# When multiple devices are connected (e.g. USB + wireless), pin to
|
||||
# the wireless device's serial to avoid "more than one device" errors.
|
||||
_discovery_cmds = {"devices", "connect", "disconnect", "kill-server"}
|
||||
serial = (
|
||||
self._get_wireless_serial()
|
||||
if args and args[0] not in _discovery_cmds
|
||||
else None
|
||||
)
|
||||
serial_args = ["-s", serial] if serial else []
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, *serial_args, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=ADB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
except (FileNotFoundError, OSError) as exc:
|
||||
_logger.warning("ADB not available: %s", exc)
|
||||
return False, ""
|
||||
except subprocess.TimeoutExpired:
|
||||
_logger.warning("ADB command timed out: %s", args)
|
||||
return False, ""
|
||||
return not result.returncode, result.stdout
|
||||
|
||||
def _adb_shell(self, command: str, *, root: bool = False) -> tuple[bool, str]:
|
||||
"""Run a shell command on the connected Android device."""
|
||||
if root:
|
||||
return self._run_adb(["shell", "su", "-c", command])
|
||||
return self._run_adb(["shell", command])
|
||||
|
||||
def _get_wireless_serial(self) -> str | None:
|
||||
"""Return the serial (ip:port) of the first connected wireless ADB device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return None
|
||||
for line in output.strip().split("\n")[1:]:
|
||||
parts = line.split()
|
||||
if parts and ":" in parts[0] and "device" in line and "offline" not in line:
|
||||
return parts[0]
|
||||
return None
|
||||
|
||||
def _has_adb_device(self) -> bool:
|
||||
"""Return True if adb devices shows at least one connected device."""
|
||||
success, output = self._run_adb(["devices"])
|
||||
if not success:
|
||||
return False
|
||||
lines = output.strip().split("\n")[1:]
|
||||
return any("device" in line and "offline" not in line for line in lines)
|
||||
|
||||
def _try_adb_connect(self, address: str) -> bool:
|
||||
"""Run adb connect to address. Returns True on success."""
|
||||
_, output = self._run_adb(["connect", address])
|
||||
lower = output.lower()
|
||||
return "connected" in lower and "unable" not in lower and "failed" not in lower
|
||||
|
||||
def _get_local_subnet_prefix(self) -> str | None:
|
||||
"""Detect the local /24 network prefix (e.g. '192.168.1')."""
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
|
||||
):
|
||||
sock.connect(("8.8.8.8", 80))
|
||||
return ".".join(sock.getsockname()[0].split(".")[:3])
|
||||
return None
|
||||
|
||||
def _try_wireless_reconnect(self) -> bool:
|
||||
"""Scan local /24 subnet on port 5555 and attempt ADB connect to phone."""
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
_logger.info("Could not determine local subnet for wireless scan")
|
||||
return False
|
||||
|
||||
def probe(i: int) -> bool:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, 5555), timeout=0.5),
|
||||
):
|
||||
if self._try_adb_connect(f"{ip}:5555"):
|
||||
return self._has_adb_device()
|
||||
return False
|
||||
|
||||
_logger.info("Scanning %s.1-254:5555 for phone...", prefix)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
if future.result():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_phone_connected(self) -> bool:
|
||||
"""Check if an Android device is connected via ADB.
|
||||
|
||||
If no device is visible, attempts wireless reconnection via subnet scan.
|
||||
"""
|
||||
if self._has_adb_device():
|
||||
return True
|
||||
_logger.info("No ADB device detected — attempting wireless reconnect...")
|
||||
return self._try_wireless_reconnect()
|
||||
|
||||
# ── ADB verification ──────────────────────────────────────────────────────
|
||||
|
||||
def _pull_workout_app_json(self) -> dict | None:
|
||||
"""Pull workout_result.json from the phone (ADB, no root needed).
|
||||
|
||||
@ -53,7 +155,7 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
only fall back to a stale/older payload if no candidate is from today.
|
||||
"""
|
||||
tmp = Path(tempfile.gettempdir()) / "workout_result.json"
|
||||
today = today_str()
|
||||
today = time.strftime("%Y-%m-%d")
|
||||
first_parsed: dict | None = None
|
||||
for remote in WORKOUT_APP_JSON_REMOTES:
|
||||
ok, _ = self._run_adb(["pull", remote, str(tmp)])
|
||||
@ -85,15 +187,11 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
if not data.get("exercises"):
|
||||
return "no_exercises", "No exercises found in the workout JSON"
|
||||
duration_min = data.get("duration_seconds", 0) / 60.0
|
||||
# Accept bar carries the hidden leeway; the message advertises the
|
||||
# round number only (see _constants.py).
|
||||
if duration_min < WORKOUT_DURATION_ACCEPT_MINUTES:
|
||||
if duration_min < MIN_WORKOUT_DURATION_MINUTES:
|
||||
return (
|
||||
"too_short",
|
||||
(
|
||||
f"Workout too short! {duration_min:.0f} min logged, "
|
||||
f"need at least {MIN_WORKOUT_DURATION_MINUTES} min."
|
||||
),
|
||||
f"Workout too short! {duration_min:.0f} min logged, "
|
||||
f"need at least {MIN_WORKOUT_DURATION_MINUTES} min.",
|
||||
)
|
||||
flag = "all succeeded" if data.get("succeeded") else "partial"
|
||||
return "verified", f"Workout verified! ({duration_min:.0f} min, {flag})"
|
||||
@ -105,7 +203,7 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
must reflect a workout done *right now*. For crediting a workout
|
||||
found dated earlier in the week, see ``_try_fill_stronglifts_for_week``.
|
||||
"""
|
||||
today = today_str()
|
||||
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)
|
||||
@ -131,7 +229,16 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
return 0
|
||||
data = self._pull_workout_app_json()
|
||||
date_str = data.get("date") if data else None
|
||||
if not date_str or not _in_current_week(date_str):
|
||||
if not date_str:
|
||||
return 0
|
||||
today = datetime.now(tz=timezone.utc).astimezone().date()
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
try:
|
||||
entry_date = date.fromisoformat(date_str)
|
||||
except ValueError:
|
||||
_logger.warning("StrongLifts JSON has an unparsable date: %r", date_str)
|
||||
return 0
|
||||
if not week_start <= entry_date <= today:
|
||||
return 0
|
||||
status, msg = self._validate_json_content(data)
|
||||
if status != "verified":
|
||||
@ -148,35 +255,69 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
|
||||
# ── HTTP fallback (no ADB / developer options required) ───────────────────
|
||||
|
||||
def _pull_sync_result(self) -> tuple[tuple[str, str] | None, str | None]:
|
||||
"""Firebase sync first: the validated result (if any) and sync error.
|
||||
def _scan_for_http_server(self) -> str | None:
|
||||
"""Scan local /24 subnet for the workout app HTTP server on port 8765.
|
||||
|
||||
Firebase sync is the primary channel -- it works without the phone
|
||||
being on the same network as the PC. Only a *verified* result
|
||||
short-circuits ADB/HTTP: a stale/incomplete cloud entry (e.g. the
|
||||
phone's last push predates today, or a later push failed offline)
|
||||
must not preempt a fresher ADB pull, so anything less than
|
||||
"verified" is kept by the caller as a fallback-of-last-resort
|
||||
candidate. A sync error never blocks unlocking either; `sync_failed`
|
||||
only surfaces if ADB/HTTP also come up empty.
|
||||
Returns the first reachable URL or None.
|
||||
"""
|
||||
synced_data, sync_error = pull_synced_workout()
|
||||
if synced_data is None:
|
||||
if sync_error is not None:
|
||||
_logger.info(
|
||||
"Firebase sync unavailable (%s) — trying ADB/HTTP...", sync_error
|
||||
)
|
||||
return None, sync_error
|
||||
sync_result = self._validate_json_data(synced_data)
|
||||
if sync_result[0] != "verified":
|
||||
_logger.info(
|
||||
"Synced data not fully verified (%s) — trying ADB/HTTP...",
|
||||
sync_result[0],
|
||||
prefix = self._get_local_subnet_prefix()
|
||||
if prefix is None:
|
||||
return None
|
||||
|
||||
def probe(i: int) -> str | None:
|
||||
ip = f"{prefix}.{i}"
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
socket.create_connection((ip, WORKOUT_HTTP_PORT), timeout=0.3),
|
||||
):
|
||||
return f"http://{ip}:{WORKOUT_HTTP_PORT}/workout"
|
||||
return None
|
||||
|
||||
_logger.info(
|
||||
"Scanning %s.1-254:%d for workout app...", prefix, WORKOUT_HTTP_PORT
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=64) as executor:
|
||||
for future in as_completed(
|
||||
executor.submit(probe, i) for i in range(1, 255)
|
||||
):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _fetch_http_workout(self) -> dict | None:
|
||||
"""Fetch workout JSON from the app's HTTP server on the local network.
|
||||
|
||||
Uses http.client directly to avoid urllib URL-open security lint rules.
|
||||
The URL is always http://<local-ip>:8765/workout — no user input involved.
|
||||
"""
|
||||
url = self._scan_for_http_server()
|
||||
if url is None:
|
||||
return None
|
||||
# url is always "http://<ip>:<port>/workout" — constructed internally.
|
||||
try:
|
||||
_, _, hostport = url.partition("://")
|
||||
host, _, path = hostport.partition("/")
|
||||
hostname, _, port_str = host.partition(":")
|
||||
conn = _HTTPConnection(hostname, int(port_str), timeout=5)
|
||||
conn.request("GET", f"/{path}")
|
||||
resp = conn.getresponse()
|
||||
if resp.status != _HTTP_OK:
|
||||
return None
|
||||
return json.loads(resp.read().decode())
|
||||
except (_HTTPException, OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"HTTP fetch of today's workout from %s failed (%s) — no data "
|
||||
"from the phone's HTTP server, so verification falls through",
|
||||
url,
|
||||
exc,
|
||||
)
|
||||
return sync_result, sync_error
|
||||
return None
|
||||
|
||||
# ── Main verification entry point ─────────────────────────────────────────
|
||||
|
||||
def _verify_phone_workout(self) -> tuple[str, str]:
|
||||
"""Verify today's workout: Firebase sync first, ADB/HTTP as fallback.
|
||||
"""Verify today's workout: GitHub sync first, ADB/HTTP as fallback.
|
||||
|
||||
Returns (status, message). Status values:
|
||||
verified / too_short / not_verified / no_phone / sync_failed /
|
||||
@ -186,9 +327,28 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
if not clock_ok:
|
||||
return "clock_tampered", clock_msg
|
||||
|
||||
sync_result, sync_error = self._pull_sync_result()
|
||||
if sync_result is not None and sync_result[0] == "verified":
|
||||
return sync_result
|
||||
# GitHub sync is the primary channel — it works without the phone
|
||||
# being on the same network as the PC. Only a *verified* sync result
|
||||
# short-circuits ADB/HTTP: a stale/incomplete cloud entry (e.g. the
|
||||
# phone's last push predates today, or a later push failed offline)
|
||||
# must not preempt a fresher ADB pull, so anything less than
|
||||
# "verified" is kept as a fallback-of-last-resort candidate instead
|
||||
# of being returned immediately. A sync error never blocks unlocking
|
||||
# either; `sync_failed` only surfaces if ADB/HTTP also come up empty.
|
||||
synced_data, sync_error = pull_synced_workout()
|
||||
sync_result: tuple[str, str] | None = None
|
||||
if synced_data is not None:
|
||||
sync_result = self._validate_json_data(synced_data)
|
||||
if sync_result[0] == "verified":
|
||||
return sync_result
|
||||
_logger.info(
|
||||
"Synced data not fully verified (%s) — trying ADB/HTTP...",
|
||||
sync_result[0],
|
||||
)
|
||||
elif sync_error is not None:
|
||||
_logger.info(
|
||||
"GitHub sync unavailable (%s) — trying ADB/HTTP...", sync_error
|
||||
)
|
||||
|
||||
# Prefer ADB when a device is visible, but if the pull yields no usable
|
||||
# JSON, fall through to the HTTP/WiFi scan — the app's in-memory HTTP
|
||||
@ -205,23 +365,13 @@ class PhoneVerificationMixin(AdbTransportMixin, HttpWorkoutFetchMixin):
|
||||
data = self._fetch_http_workout()
|
||||
if data is not None:
|
||||
return self._validate_json_data(data)
|
||||
return _no_data_result(sync_result, sync_error, adb_connected=adb_connected)
|
||||
|
||||
|
||||
def _no_data_result(
|
||||
sync_result: tuple[str, str] | None,
|
||||
sync_error: str | None,
|
||||
*,
|
||||
adb_connected: bool,
|
||||
) -> tuple[str, str]:
|
||||
"""The verdict when neither ADB nor HTTP produced a workout JSON."""
|
||||
if sync_result is not None:
|
||||
return sync_result
|
||||
if sync_error is not None:
|
||||
return "sync_failed", sync_error
|
||||
if adb_connected:
|
||||
return (
|
||||
"not_verified",
|
||||
"Workout app JSON not found. Complete a workout in the app first.",
|
||||
)
|
||||
return "no_phone", "Phone not reachable via ADB or HTTP on local network"
|
||||
if sync_result is not None:
|
||||
return sync_result
|
||||
if sync_error is not None:
|
||||
return "sync_failed", sync_error
|
||||
if adb_connected:
|
||||
return (
|
||||
"not_verified",
|
||||
"Workout app JSON not found. Complete a workout in the app first.",
|
||||
)
|
||||
return "no_phone", "Phone not reachable via ADB or HTTP on local network"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user