Compare commits

..

No commits in common. "main" and "v1.0.0-build.106" have entirely different histories.

432 changed files with 1915 additions and 36376 deletions

View File

@ -1,2 +0,0 @@
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
# workflow. This marker stops the fleet installer from re-adding it.

2
.fvmrc
View File

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

View File

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

View File

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

View File

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

View File

@ -3,14 +3,6 @@ name: release-apk
on: on:
push: push:
branches: [main] branches: [main]
# A publisher, not a gate: build only when something that ends up in
# the APK changed. versionCode is the commit count, so skipped pushes
# still leave it monotonic.
paths:
- 'phone_app/**'
- '.fvmrc'
- '.versioncode-offset'
- '.github/workflows/release-apk.yml'
# Lets a release be rebuilt from the current main without a dummy commit. # Lets a release be rebuilt from the current main without a dummy commit.
workflow_dispatch: workflow_dispatch:
@ -47,47 +39,18 @@ jobs:
# versionCode is the commit count; a shallow clone would report 1. # versionCode is the commit count; a shallow clone would report 1.
fetch-depth: 0 fetch-depth: 0
# `.versioncode-offset` is the recovery valve for a phone stranded - name: Derive versionCode from the commit count
# above CI by a hand-numbered local build. Android only ever compares
# versionCode upward, so a device ahead of CI locks CI out permanently
# and the only other escape is an uninstall, which wipes app data.
# ~/.claude/scripts/lib/phone_deploy_version.sh reads the SAME file, so
# raising it moves both sides together; raising either alone re-strands
# the device. Never lower it.
- name: Derive versionCode from the commit count plus the offset
id: vc id: vc
# working-directory overrides the job default of phone_app. The offset run: echo "code=$(git rev-list --count HEAD)" >> "$GITHUB_OUTPUT"
# file lives at the REPO ROOT, and reading it from the app subdirectory
# silently finds nothing and yields 0 -- git rev-list still works there
# because git searches upward, so the step goes green with the wrong
# number. That exact mistake shipped versionCode 108 instead of 209 on
# 2026-08-31; it is also the failure phone_deploy_version.sh warns
# about on its own side.
working-directory: ${{ github.workspace }}
run: |
offset=0
if [[ -r .versioncode-offset ]]; then
read -r offset < .versioncode-offset
fi
[[ "$offset" =~ ^[0-9]+$ ]] || offset=0
# Fail loudly rather than mint a too-low code: a silent 0 here is
# what leaves the phone unreachable by CI.
if [[ -r .versioncode-offset && "$offset" == 0 ]]; then
echo "::error::.versioncode-offset exists but parsed as 0" >&2
exit 1
fi
echo "code=$(( $(git rev-list --count HEAD) + offset ))" >> "$GITHUB_OUTPUT"
- uses: actions/setup-java@v4 - uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: "17" java-version: "17"
# ~/.gradle caches + wrapper, keyed on the Gradle files.
cache: gradle
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
flutter-version: 3.50.1 flutter-version: 3.47.2
channel: stable channel: stable
cache: true cache: true

View File

@ -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

3
.gitignore vendored
View File

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

View File

@ -8,7 +8,6 @@ default_language_version:
default_stages: [pre-commit] default_stages: [pre-commit]
fail_fast: false fail_fast: false
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 rev: v4.6.0
@ -24,6 +23,8 @@ repos:
- id: check-merge-conflict - id: check-merge-conflict
- id: detect-private-key - id: detect-private-key
- id: debug-statements - id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
- id: check-ast - id: check-ast
- id: mixed-line-ending - id: mixed-line-ending
args: [--fix=lf] args: [--fix=lf]
@ -31,12 +32,6 @@ repos:
- repo: local - repo: local
hooks: 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 - id: no-noqa
name: Block noqa comments name: Block noqa comments
entry: '(?i)#\s*(noqa|type:\s*ignore)' entry: '(?i)#\s*(noqa|type:\s*ignore)'
@ -57,9 +52,67 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.2 rev: v0.15.2
hooks: hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format - id: ruff-format
types_or: [python, pyi] types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint
rev: v3.3.2
hooks:
- id: pylint
args:
- --rcfile=pyproject.toml
- --fail-under=10
- --jobs=4
additional_dependencies:
- pytest
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.1#subdirectory=gatelock
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10
hooks:
- id: bandit
args:
- -c
- pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(tests/|.*test.*\.py$)
- repo: local - repo: local
hooks: hooks:
- id: ci-mirror - id: ci-mirror
@ -69,7 +122,14 @@ repos:
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: 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,.git,__pycache__,.venv
- repo: local - repo: local
hooks: hooks:
@ -81,19 +141,22 @@ repos:
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
# The Dart free-day rules are a port of ~/src/utils/freedays; this replays - id: shellcheck
# one edit sequence through both and fails on any semantic disagreement. name: shellcheck
# Only fires when either implementation's inputs change. entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
- id: free-days-interop language: system
name: free-day rules agree with the Python package types: [shell]
entry: scripts/free_days_interop/check.sh # The shared 250-line cap. This repo used to run a local script with a
# higher limit under this same hook id, so it looked gated while letting
# through files every other repo rejects.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system language: system
pass_filenames: false
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the # Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may. # 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 # Shared gate in ~/utils owns the namespaces and the exemption list, so
# one repo's idea of a valid name cannot drift from every other repo's. # one repo's idea of a valid name cannot drift from every other repo's.
- id: md-naming - id: md-naming
name: markdown naming convention name: markdown naming convention
@ -101,30 +164,6 @@ repos:
language: system language: system
files: \.(md|markdown)$ 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 # Every dependency on its ecosystem's newest STABLE release, exact-pinned
# so the question is mechanically answerable at all. # so the question is mechanically answerable at all.
# #
@ -145,17 +184,3 @@ repos:
|package\.json|package-lock\.json|pnpm-lock\.yaml |package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum) |Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version)$ |\.fvmrc|\.nvmrc|\.python-version)$
- repo: local
hooks:
# The only pre-push hook. Everything that used to run here is now
# `stages: [manual]` -- run on demand with `scripts/check_gate_stamp.sh
# full`, and by CI on every push. finish_auto.sh stamps HEAD after its
# gate; a tree without that receipt cannot leave the machine.
- id: gate-stamp
name: pushed tree passed the local gate (stamp check)
entry: scripts/check_gate_stamp.sh check
language: system
pass_filenames: false
always_run: true
stages: [pre-push]

View File

@ -1 +0,0 @@
105

279
AGENTS.md
View File

@ -4,21 +4,13 @@
**The phone is the alarm.** `phone_app/` arms and rings it and gates the **The phone is the alarm.** `phone_app/` arms and rings it and gates the
dismissal; this repo's Python half only reads the alarm time the phone dismissal; this repo's Python half only reads the alarm time the phone
published and starts the morning routine at that time. The time is an earned published and starts the morning routine at that time.
ramp, 08:00 down to 07:00, owned by the phone alone — **`DOCS-ramp.md`**.
The PC's waking role was deleted on 2026-08-30: no alarm window, no smart The PC's waking role was deleted on 2026-08-30: no alarm window, no audio
plug, no curtains, no `shutdown` wrapper, no sleep hook. On 2026-10-01 exactly escalation, no smart plug, no curtains, no `rtcwake`, no `shutdown` wrapper,
two pieces came back, because the phone **cannot** ring while powered off: a no sleep hook. Making the PC wake someone reliably cost more than it returned.
**fallback ring** when the phone is silent or no session started, and an Everything about it is in git history; do not reintroduce a piece of it
**RTC self-wake** before Tue/Wed/Thu. Plus the stacking phone lockdown and a without saying why the phone cannot do that job.
temporary escape hatch (until 2026-10-15). All of it, and the data contract
the phone, PC and focus-owner share: **`DOCS-wake-enforcement.md`**. Anything
else from the old PC alarm still needs a reason the phone can't do it.
**Bypasses** (launcher "Pause app" silenced the ring 11-20 and 11-22):
focus-owner pins the enforcement apps, WakeAlarm is a device admin, and a
pause, admin removal, revoked permission or killed ring that gets through is a
miss plus an immediate PC ring: **`DOCS-bypass.md`**.
## The dismiss sequence (phone) ## The dismiss sequence (phone)
@ -36,15 +28,11 @@ passing sent the user back to the start.
- **Two *distinct* tags.** The same id in both slots is refused at - **Two *distinct* tags.** The same id in both slots is refused at
registration — one tag satisfying both stages removes the walk, which is the registration — one tag satisfying both stages removes the walk, which is the
entire point. Stored as a JSON list under `roomProof.nfcTagIds`; a legacy entire point. Stored as a JSON list under `roomProof.nfcTagIds`; a legacy
single `roomProof.nfcTagId` migrates into slot 1. **Tags and home location single `roomProof.nfcTagId` migrates into slot 1.
sync** (`settings_sync.dart`, see `DOCS-phone-alarm.md`) — a reinstall - **Steps are unchanged** (`requiredSteps = 25`, `requiredElapsed = 2 min`),
gets them back; do not make either local-only again. and are counted from ring start, *not* re-baselined at tag 1. Consequence:
- **Steps** (`requiredSteps = 25`) are counted from ring start, *not* walking to tag 1 already banks the steps, so only the elapsed floor really
re-baselined at tag 1, so walking to tag 1 already banks them and the stage binds — which is why the steps stage auto-polls instead of offering a button.
passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`)
applies **only under bypass/away**, where no tag proved the walk and a
shaken phone would count; on the normal path it only added two minutes of
ringing (dropped 2026-09-16).
- **Answers are cumulative, not consecutive.** A wrong one costs the attempt - **Answers are cumulative, not consecutive.** A wrong one costs the attempt
and nothing else. and nothing else.
- **The bypass skips the tags, never the walk.** After - **The bypass skips the tags, never the walk.** After
@ -54,29 +42,31 @@ passing sent the user back to the start.
bed for five minutes and answer questions without standing up — weaker than bed for five minutes and answer questions without standing up — weaker than
the gate this replaced. Do not "simplify" it into that. the gate this replaced. Do not "simplify" it into that.
- **No challenge may hide its prompt.** The memorise-then-hide kind was - **No challenge may hide its prompt.** The memorise-then-hide kind was
deleted, not merely unrouted: the ring screen is reached by walking in. deleted, not merely unrouted: the ring screen is reached by walking in from
another room.
**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in **`HomeScreen.initState` must stay strictly sequential.** It runs
the same activity, to the silent **morning session**: weigh in → bathroom tag `_applyPolicy()` → `_loadSyncState()` → `_syncToPc()` through one
→ shower → bathroom tag again → wardrobe tag → desk tag. A missed window `_bootstrapSync()`, because the last reads what the first two write and
(AlarmManager, request code 1003) re-rings; silencing it is the full sequence `AlarmPublisher.publish` takes the service as a *parameter* — captured by
again; three re-rings fail the session. Leaving the app is fine: every launch value, so a later assignment can never reach it. Running them concurrently
while the morning is live lands back on the leg (`SessionNotice.kt`). State is (as they once were) meant the startup publish always passed `null`, and since
persisted after every change, on wall-clock instants: **`DOCS-morning-session.md`**. that was the only publish site, **nothing published for three weeks** while
the PC honoured a record from 2026-08-09. `_pickEarlier` must publish too, or
the one schedule edit the app offers never reaches the PC.
**`HomeScreen.initState` must stay strictly sequential** (`_applyPolicy` → Relatedly: `publish()` reports a missing *backend* and a missing *store*
`_loadSyncState` → `_syncToPc`): run concurrently, the startup publish differently on purpose. One string for both is what made the above look like a
captured a null store and **nothing published for three weeks**. Why, the configuration the user had never done, while Firebase was connected the whole
two deliberately distinct `publish()` failure strings, the ring's injectable time.
clock, and everything that is a hard crash or a silent no-ring:
`RingScreen` takes an injectable `clock`. `Stopwatch` reads the wall clock,
which `tester.pump()` does not advance, so without that seam no widget test
can reach the two-minute floor or the five-minute bypass.
More, including everything that is a hard crash or a silent no-ring:
**`DOCS-phone-alarm.md`**. **`DOCS-phone-alarm.md`**.
**Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone
does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
**`DOCS-sick-days.md`**, PC **`DOCS-sick-days-pc.md`**.
## Scheduling — a per-minute timer ## Scheduling — a per-minute timer
`wake-alarm-trigger.timer` ticks every minute (`OnCalendar=*:*:00`, `wake-alarm-trigger.timer` ticks every minute (`OnCalendar=*:*:00`,
@ -91,73 +81,66 @@ today's fire instant in **local** time, and fires iff `now` is in
`was_trigger_fired_today()`. Without it the routine restarts on every tick for `was_trigger_fired_today()`. Without it the routine restarts on every tick for
the rest of the 60-minute window: the unit is `Type=simple`, so a start while the rest of the 60-minute window: the unit is `Type=simple`, so a start while
it runs is a no-op, but the moment the workout lock finishes the next tick it runs is a no-op, but the moment the workout lock finishes the next tick
relaunches it on top of the user. The latch replaced the alarm's own dismissal relaunches it on top of the user. This latch replaced the alarm's own
record when `_alarm.py` was deleted; deleting one without adding the other is dismissal record when `_alarm.py` was deleted — deleting one without adding the
a silent regression. other is a silent regression, and that is exactly the trap.
`Persistent=true` plus the 60-minute window also replaced the deleted `Persistent=true` plus the 60-minute window is also what replaced the deleted
systemd-sleep hook: a suspended or just-booted machine still fires. systemd-sleep hook: a suspended or just-booted machine still fires.
## Reading the phone's alarm ## Reading the phone's alarm
`_sync.py` is the only reader; `_sync_transport.py` fetches, `_sync_token.py` `_sync.py` is the only reader.
holds the GitHub-token lookup (stdlib-only).
- Source of truth: a `crdt_sync` log written by `phone_app/` under - Source of truth: a `crdt_sync` log written by `phone_app/` under
`wake-alarm-sync/devices-e2e/<device-id>/alarm.json`, at `wake-alarm-sync/devices/<device-id>/alarm.json`, at
`.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. Same logical path on both `.alarm.fields.alarm_hour[0]` / `.alarm_minute[0]`. Same logical path on both
backends, so only the transport differs, never the parse. backends, so only the transport differs, never the parse.
- **End-to-end encrypted** (since 2026-11-12): fields are sealed with a key
derived from the shared passphrase (`~/.config/crdt-sync/password` on the
PC, the keystore + lock icon in Settings on the phone). Both readers go
through `open_encrypted_client`, which copies the old plaintext
`wake-alarm-sync/devices` over once per process and never deletes it. No
or wrong passphrase reads as "nothing published" (cache, then 08:00) —
never plaintext. diet_guard reads the same prefix for weigh-ins.
- **The Firebase reader discovers device directories; it is not pinned to - **The Firebase reader discovers device directories; it is not pinned to
`devices/phone/`.** The phone's device id is migrating from the constant `devices/phone/`.** The phone's device id is migrating from the fixed
`phone` to a per-install uuid; a pinned reader would silently stop seeing constant `phone` to a per-install uuid, and a pinned reader would silently
the alarm and fall back to 08:00, the wrong time. `_fetch_firebase_alarm()` stop seeing the alarm and fall back to `FALLBACK_ALARM_HOUR` — i.e. the wrong
lists `SYNC_DEVICES_PREFIX`, reads every device's `alarm.json`, and picks the time. `_fetch_firebase_alarm()` lists `SYNC_DEVICES_PREFIX`, reads every
newest by the hour field's **HLC** (`device_id` breaks exact ties). A payload device's `alarm.json`, and picks the newest by the hour field's **HLC**, with
that does not parse is skipped, never allowed to win. `SYNC_ALARM_PATH` `device_id` breaking exact ties. A payload that does not parse is skipped
stays as a last-resort read for a backend that lists nothing. rather than allowed to win. `SYNC_ALARM_PATH` remains as a last-resort read
- Payload parsing/ranking lives in `_alarm_payload.py` ("what did the phone for a backend that lists nothing.
say"); `_sync.py` owns fetching, caching and fallback. - Payload parsing/ranking lives in `_alarm_payload.py`: `_sync.py` owns
fetching, caching and fallback; `_alarm_payload.py` owns "what did the phone
actually say".
- **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is - **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is
deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`. deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
- Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh - Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config is token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config file
checked **before** anything is constructed, so an unconfigured machine never is checked **before** anything is constructed, so an unconfigured machine
touches the network. never touches the network.
- GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`, - GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`,
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker's is no else a sibling app's raw `~/.config/{diet_guard,screen_locker}/sync_token`.
longer read: Firebase-only since 2026-10-09). Needs `repo` scope; the repo is Needs `repo` scope — the repo is private, so a token without access returns
private, so a token without access returns **404, not 403**. **404, not 403**.
- `crdt_sync` is imported at module scope but **guarded by - `crdt_sync` is imported at module scope but **guarded by
`try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so `try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so
a dependency that failed to install must degrade the read to the cache a dependency that failed to install must degrade the read to the GitHub path
rather than crash the per-minute trigger. Both backends need it (the GitHub rather than crash the per-minute trigger. The GitHub path stays stdlib-only
mirror is read through `GitHubSyncClient`, encrypted too). Verify with for that reason. Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the
`/usr/bin/python3 -c "import crdt_sync"`, not the dev venv. dev venv.
- Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale - Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale
cache → 08:00. The cache bounds remote reads to ~288/day. cache → `FALLBACK_ALARM_HOUR`. The cache bounds remote reads to ~288/day
despite the per-minute tick.
- **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped - **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped
at every step, including the cache.** The check is on when the *phone at every step, including the cache.** The check is on when the *phone
stamped it*, never on when we fetched: the cache is rewritten from the same stamped it*, never on when we fetched — checking the fetch is trivially
stale record every few minutes, so `fetched_at` is always fresh. That is why defeated, because the cache is rewritten from the same stale record every few
the winning HLC's instant is carried through `_alarm_payload` → minutes, so `fetched_at` is always fresh however old the record behind it is.
That is why the winning HLC's instant is carried through `_alarm_payload` →
`_sync_transport` → the cache's `published_at`. Expiring is safe because `_sync_transport` → the cache's `published_at`. Expiring is safe because
08:00 is the latest the phone can ever arm. An **undated** record is `FALLBACK_ALARM_HOUR` *is* the phone's baseline. An **undated** record is
trusted: the GitHub mirror has no per-field HLC, so treating "cannot tell" trusted, not expired: the GitHub mirror has no per-field HLC, so treating
as "too old" would break that backend entirely. "cannot tell" as "too old" would break that backend entirely.
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute; - **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute,
a loud persistent condition is 1440 journal lines a day. `_trigger` emits the so a persistent condition logged loudly is 1440 identical journal lines a day.
one WARNING that matters: firing *now* on a non-phone time. `_trigger` emits the single WARNING that matters: it is firing *now* on a
- **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`, non-phone alarm time.
**`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the
workout and LeetCode locks to 11:00 via one signed file both consumers read.
Phone-local dates only — never `_state._today_str()` (UTC).
## The morning_routine orchestrator lives elsewhere ## The morning_routine orchestrator lives elsewhere
@ -166,10 +149,11 @@ is what `_trigger` starts, and it now runs one leg: `screen_locker.screen_lock`.
Its alarm leg was removed in the same change that deleted `_alarm.py`. Its alarm leg was removed in the same change that deleted `_alarm.py`.
**When this package's module paths change, the orchestrator must change in the **When this package's module paths change, the orchestrator must change in the
same commit.** A stale path caused a month-long silent production failure same commit.** Leaving it pointing at a module that no longer exists caused a
(2026-05-28, orchestrator still on `python_pkg.screen_locker.screen_lock` after month-long silent production failure once already (2026-05-28, orchestrator
screen-locker's extraction): the alarm fired and dismissed correctly while the still on `python_pkg.screen_locker.screen_lock` after screen-locker's
workout lock crashed with `ModuleNotFoundError` on every run. extraction): the alarm fired and dismissed correctly while the workout lock
crashed with `ModuleNotFoundError` on every run.
## Production dependency installation ## Production dependency installation
@ -181,70 +165,79 @@ site-packages:
/usr/bin/python3 -m pip install --user --break-system-packages -e . /usr/bin/python3 -m pip install --user --break-system-packages -e .
``` ```
**Run `install.sh` (or `pip install -e`) from a durable clone** **Run `install.sh` (or `pip install -e`) from a durable clone**, not a scratch
(`~/src/wake-alarm`, mirroring `~/src/screen-locker`), not a scratch directory: directory — it is editable, so a later `git pull` in that clone updates the
it is editable, so a later `git pull` there updates the running production running production code. From `/tmp` or via `pip install "wake_alarm @ git+..."`
code. From `/tmp` or via `pip install "wake_alarm @ git+..."` you get a you get a snapshot frozen at that commit, and the next push silently does not
snapshot frozen at that commit, and the next push silently does not reach the reach the running service. Convention: `~/wake-alarm`, mirroring
service. `~/screen-locker`.
A dependency installed only into a dev venv makes the service fail with If you add a dependency and only install it into a dev venv, the service fails
`ModuleNotFoundError` on its next run (this gap caused a 3-day diet_guard with `ModuleNotFoundError` on its next run — this exact gap caused a 3-day
outage). Verify against `/usr/bin/python3 -c "import <dep>"`. diet_guard outage. Verify against `/usr/bin/python3 -c "import <dep>"`.
## Uninstalling ## Uninstalling
`uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring `uninstall.sh`, never `rm -rf` on the repo. `/usr/local/bin/shutdown` is
unit, the logind power-key drop-in and an RTC alarm we armed, and retires the root-owned and shadows `/usr/bin/shutdown`; deleting the repo leaves it in
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls place, and with the alarm cache gone it falls through to
`uninstall.sh --retired-only` last, so **`uninstall.sh` is load-bearing for `sudo rtcwake … ; exec systemctl hibernate` — so `shutdown now` would silently
installing** — renaming or deleting it breaks a fresh install. That call is stop being a poweroff, every day, forever.
non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
would abort an install that had already placed the package and the timer. `install.sh` calls `uninstall.sh --retired-only` as its last step, so
**`/etc/sudoers.d/wake-alarm` stays even after a full uninstall:** the RTC **`uninstall.sh` is load-bearing for installing**, not just for removing —
self-wake's `rtcwake` and the root ring unit's `systemctl` lines live there. renaming or deleting it breaks a fresh install. That call is non-fatal and
gated on `sudo -n`: the cleanup needs root, and a hard failure there would
abort an install that had already placed the package and enabled the timer.
**`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full
uninstall: screen-locker's own `_wake_alarm.py:_schedule_rtcwake` still shells
out to `sudo rtcwake`, and removing the entry here breaks a live feature in
another repo with no error message anywhere.
## Operational gotchas ## Operational gotchas
- **`wake_state.json` is runtime state, not tracked** (the HMAC-signed - **`wake_state.json` is runtime state, not tracked.** It holds the
once-per-day latch). It was once committed in the monorepo; keep it ignored. HMAC-signed once-per-day latch. It was accidentally committed in the
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A monorepo and must stay gitignored here.
per-file redirect gets forgotten when a new writer appears (`_trigger` was - **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.**
one), and the failure is silent: a green suite that stamped the live file. `_trigger` writes it now, and the trigger tests never redirected it — a
per-file redirect is exactly the kind that gets forgotten when a new writer
appears, and the failure is silent: a green suite that quietly stamped the
live state file.
## Commands ## Commands
- run: n/a: no single entry point; systemd timers (`install.sh`) drive it, inspect with `python -m wake_alarm._sync --show`, `python -m wake_alarm._session --show`, `python -m wake_alarm._trigger --dry-run` - Run tests: `python -m pytest wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-fail-under=100`
- test: `python -m pytest -q wake_alarm/tests/ && cd phone_app && flutter test --reporter=compact` - Phone tests: `cd phone_app && flutter test && flutter analyze`
- test-changed: `scripts/test_changed.sh` - Lint: `pre-commit run --all-files`
- lint: n/a: dropped (kuhy, 2026-11-27) - Show the resolved alarm: `python -m wake_alarm._sync --show` (`--no-cache` forces a live read)
- coverage: n/a: dropped (kuhy, 2026-11-27) - Show what the next tick would do: `python -m wake_alarm._trigger --dry-run`
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27) - Watch it live: `journalctl --user -fu wake-alarm-trigger.service`
- deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`) - Install: `bash install.sh` — Uninstall: `bash uninstall.sh`
- Gate the shell/system scripts: `bash scripts/vmbox/harness.sh`
(disposable Arch VM; see **`DOCS-vmbox.md`**)
- Ring the phone for a manual test: `lib/main_ring_probe.dart` (see
`DOCS-phone-alarm.md` — it starts a **real** alarm, and the new sequence is
what stops it)
Other: full lint gate `pre-commit run --all-files`; live log The dev venv lacks `gatelock`, so anything importing `_state` (including
`journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` /
`bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh`
(disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning
`phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone
via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md`, starts a **real**
alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`. `_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.
## Do NOT ## Do NOT
- Don't add a dependency without the production install-path check above. - Don't add a dependency without the production install-path check above.
`_sync.py`'s GitHub path is stdlib-only for that reason — don't "improve" it `_sync.py`'s GitHub path is stdlib-only for that reason — don't "improve" it
to `requests`, and don't make the `crdt_sync` import unconditional. Don't to `requests`, and don't make the `crdt_sync` import unconditional.
forget the orchestrator when changing this package's module paths. - Don't forget the orchestrator when changing this package's module paths.
- Don't point the trigger at anything but `morning-routine.service` (or the - Don't point the trigger at anything but `morning-routine.service`, or the
workout lock never runs), don't remove its once-per-day latch, and don't workout lock never runs.
raise the log level of `_sync`'s degraded-read paths. - Don't remove the trigger's once-per-day latch.
- Don't let the bypass skip the walk or add a challenge that hides its prompt. - Don't raise the log level of `_sync`'s degraded-read paths.
- Don't close the ring screen on dismiss when a session should follow, don't - Don't let the bypass skip the walk, and don't add a challenge kind that
add a re-ring cancel beyond the session's own `finishSession`, and don't hides its own prompt.
restore a re-ring instant that has passed (BOOT_COMPLETED replays on launch). - Don't make `HomeScreen.initState` concurrent again, and don't collapse
- Don't make `HomeScreen.initState` concurrent again; keep `publish()`'s two failure messages. `publish()`'s two failure messages back into one.
- Don't date a record by when the PC fetched it, and don't let a consumer of - Don't date a record by when the PC fetched it.
`morning_session.json` re-derive the 09:30/11:00 cutoffs or fetch its own copy. - Don't delete `/etc/sudoers.d/wake-alarm`.
- Don't delete `/etc/sudoers.d/wake-alarm`. Don't commit `wake_state.json`. - Don't commit `wake_state.json`.

View File

@ -1,245 +0,0 @@
# Bypasses of the alarm (2026-11-22)
On 2026-11-20 and 11-22 kuhy long-pressed WakeAlarm on the home screen and
tapped "Wstrzymaj aplikację" (Digital Wellbeing's *Pause app*). The pause
suspended the app, the ring stopped, and he went back to sleep. This file
covers the three layers that now stop that, what counts as a bypass when
one gets through anyway, and what a bypass costs.
## Layer 1: the pause is refused (focus-owner, `~/src/phone-focus-mode`)
Every focus-owner pass, for the eight enforcement apps in
`focus_policy/packages.py` `ENFORCEMENT_PACKAGES` (wake_alarm_sync,
workout_app, diet_guard_app, leetcode_guard, book_guard_app, home_guard,
daily_limits, habit_stack):
- `setUserControlDisabledPackages`: Android refuses to suspend them
(`Cannot suspend package ...: protected package`), and Settings' Force stop
and Clear storage are greyed out. `am force-stop` and `pm clear` are refused
too; `adb install -r` still works, so deploys are unaffected.
- `setUninstallBlocked`.
- `setPermissionGrantState(POST_NOTIFICATIONS, GRANTED)`. The full-screen
intent is an app-op and cannot be pinned (`setPermissionGrantState`
returns false), so revoking it is a bypass instead (below).
- A suspension found anyway is lifted. Measured on the emulator: a pause
made before the pins were applied was lifted 4.3 s later, by the pass that
wake_alarm's `UNSUSPEND` signal started.
Digital Wellbeing itself is hidden in every state (`ALWAYS_BLOCKED_PACKAGES`),
so the Pause button is gone as well.
## Layer 2: WakeAlarm is a device admin
`WakeAdminReceiver` (`res/xml/wake_admin.xml`, no policies). Android refuses
to suspend an active admin. It is activated over adb, never by a tap:
adb shell dpm set-active-admin com.kuhy.wake_alarm_sync/.WakeAdminReceiver
Deactivating it in Settings cannot be prevented, so it is a bypass.
## Layer 3: what counts as a bypass (`Bypass.kt`)
A bypass counts only on a ringing day (an alarm is stored, not a free or sick
day, the ring did not stand down) while the ring or the morning session is
live. Causes (`bypass` phone event, `data.cause`):
| cause | seen by |
|---|---|
| `suspended` | `SuspendReceiver` on `MY_PACKAGE_SUSPENDED`; also sends focus-owner `UNSUSPEND` |
| `admin_removed` | `WakeAdminReceiver.onDisabled` |
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
| `fsi_revoked` | the same; uid app-op `USE_FULL_SCREEN_INTENT` denied |
| `ring_killed` | every launch and boot: today's ring fired, was never dismissed, and is not sounding |
| `uninstalled` | focus-owner, every pass, any day: `com.kuhy.wake_alarm_sync` not installed for user 0 (see below) |
`ring_killed` reads `watched_fired_date`, a stamp only builds with `Bypass`
write, so a ring fired by an older build (11-22, paused, never dismissed) does
not count the first time the new build starts. The same cause twice within
a minute is recorded once (both activities run the launch check).
## What a bypass costs
- **A miss** (`StickCheck`), on any weekday, at once, whatever the dismiss
does afterwards: a lockdown through the next day, stacking. The streak
links penalty days, stick days (Tue–Thu) plus bypass days; free and sick
days are skipped. A plain late dismiss on Fri–Mon still changes nothing.
A later check or bypass on the day already penalised sends the stored
lockdown (`locked_through`, if today or later) again, same date and
streak, so a signal focus-owner missed (not running, not yet Device
Owner) still lands.
- **The phone rings again** (`Bypass.ringAgain`). During a session it is a
re-ring: only the full dismiss sequence silences it and `re_rings` goes up
by one when it does (`SessionHandoff.afterDismiss`). It is recorded as
`bypass:<cause>` in `re_ring_reasons` (`bypass:fsi_revoked`,
`bypass:suspended`, ...): `Bypass.record` stamps the cause
(`BypassReRing`, dated) before it restarts the ring, and the session takes
it once over `takeBypassReRing`, on the screen's tick or on the dismiss. A
bypass while a deadline re-ring already sounds stamps nothing: one sound,
one re-ring, reason `deadline:<leg>`; the `bypass` event, its publish and
the lockdown still happen.
- **The PC rings** (`_fallback_policy`, reason `bypass`). The phone pushes
the event at once through the headless `publishNowMain` engine. The PC
rings from the bypass for up to 30 min (`FALLBACK_RING_CAP` from the
bypass, not the day's cap), outside the window, after a session started
and after the day's own ring was used. It stops on a `dismissed` newer
than the bypass, which the phone also pushes at once. Free and sick days
and an escape stand it down. The tick reads the phone until `A + 4 h`
(`BYPASS_WATCH`); the fallback timer ticks 04:00-11:59 (and 21:xx, below).
To see these answers without a backend, `_fallback --dry-run --at <instant>
--published <file>` reads the phone's logs from a JSON list of
`[device_id, alarm.json]` pairs instead of Firebase (`_published_file`).
## An uninstall that gets through (focus-owner, 2026-11-23)
WakeAlarm cannot be uninstalled: focus-owner holds `setUninstallBlocked`
and `setUserControlDisabledPackages` on it every pass. The Pixel's
`dumpsys device_policy` shows `packageUninstallBlocked` for it (2026-11-23).
On the AVD, `adb uninstall`, `pm uninstall --user 0` and `-k --user 0` all
fail with `DELETE_FAILED_INTERNAL_ERROR` ("Attempted to delete protected
package"): the user-control pin refuses it before the uninstall block is
asked. Deploys use `adb install -r`, which both allow.
If WakeAlarm is gone anyway, WakeAlarm cannot record a bypass, so
focus-owner does (`phone-focus-mode` `focus-owner/.../UninstallLockdown.kt`,
`UninstallEvents.kt`, `lib/sync/`):
- **Missing** means not found, or found with `FLAG_INSTALLED` clear. A
hidden app is installed.
- **Lockdown**, every day including free and sick days: the lockdown
allowlist while the app is missing and through the day after it returns.
Its own prefs, so wake_alarm's `LIFT_LOCKDOWN` does not clear it (a
reinstalled WakeAlarm would send one at once). No day cap.
- **Event**: `bypass` with `cause: uninstalled` and the phone-local `date`,
under device `focus-owner`, record `alarm`, field `phone_events`. One at
once when the app goes missing (it rings the PC only inside a tick
window), then one per later day at the first pass at or after the alarm
time focus-owner read from the sync (08:00 if none). The PC rings every
morning until a full dismiss logs `dismissed`; on a free or sick day it
stays silent while the phone stays locked.
- **Queue**: the lockdown never waits on the push. An unsent event is
retried every pass, a failure is logged once a day, nothing is dropped.
- **Push-only**: focus-owner writes its own file and never merges a peer's
log into it (a pulled list would replace its events, field by field).
Its `phone_events` HLC is the newest event's own `at`, so a late retry
never out-ranks a list the reinstalled phone published.
- `newest_push` skips device `focus-owner`: its write is not the phone's.
- Set up once per install: Google sign-in plus the passphrase (the cloud
and lock icons in focus-owner's app bar). Each success pushes a harmless
`install_check` field that no PC policy reads.
## Testing against a backend: the RTDB emulator
The AVD never signs in to prod. A probe build with
`--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` syncs to the
Firebase RTDB emulator on the PC instead of prod Firebase *and* the GitHub
mirror (`sync_emulator.dart`; plain HTTP is allowed to `10.0.2.2` in the
debug manifest only). Release builds never set the define.
1. `systemd-run --user --collect --unit=wa-rtdb-emu /usr/bin/java -jar
~/.cache/firebase/emulators/firebase-database-emulator-v4.11.2.jar --host
127.0.0.1 --port 9000` (one default namespace; `auth=owner` is admin).
2. Write a dummy passphrase to `files/passphrase` under the app's
`Android/data/<pkg>/` dir; the probe moves it into the keystore on launch
(`probe_passphrase.dart`). Without one every push is `sync locked`.
A probe's `-t` file must re-export the headless entrypoints
(`publishNowMain`, ...): Kotlin resolves them by name in the root library,
and without them the bypass publish never ran.
3. After the bypass: `HOME=<scratch with .config/crdt-sync/password>
PYTHONUSERBASE=~/.local /usr/bin/python3 scripts/emu_published.py
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
--published out.json`.
Traps on the shared AVD:
- It can boot `RUNNING_LOCKED` with PIN 1234, and then `/sdcard` is missing.
Unlock it before you write the passphrase.
- `dpm remove-active-admin` refuses the admin ("non-test admin"). Use
Settings → Device admin apps → WakeAlarm → Deactivate.
- An active admin makes `cmd package suspend` fail, so suspend first, then
activate the admin.
- The probe's `ringNow` does not mark the ring as fired, so `Bypass.record`
logs "no ring or session live". Set the AVD clock (`adb root`,
`settings put global auto_time 0`, `date`) to just before the armed
`AlarmReceiver` time and let the alarm fire. Afterwards set `auto_time`
back to 1.
### Live check 2026-11-22: bypass events on the RTDB emulator
C5 and C6 were checked on emulator-5556 with the `main_session_probe.dart`
build (`WAKE_SYNC_EMULATOR`), with the clock moved to Mon 2026-11-23 07:56
so the 07:57 alarm rang through `AlarmReceiver`. With the alarm still
ringing: `cmd package suspend` at 07:57:34 logged `bypass: suspended`,
and deactivating the admin in Settings at 07:58:04 logged
`bypass: admin_removed`. Each one logged "signalling focus-owner lockdown
through 2026-11-24". `emu_published.py` then read both from the RTDB emulator:
`{"kind":"bypass","data":{"cause":"suspended","date":"2026-11-23"}}` and
`{"kind":"bypass","data":{"cause":"admin_removed","date":"2026-11-23"}}`
(a `notifications_off` bypass from 07:57:11 was also there, because the AVD
has the app's notifications off). Then
`_fallback --dry-run --at 2026-11-23T08:03 --published out.json` answered
`WOULD RING: bypass` (`bypass_at=07:58:04`). focus-owner is not on that AVD:
its unsuspend and its applied lockdown are the earlier C6 check at 83e1e15.
## The 21:00 notifications check
Android lets nothing lock "All WakeAlarm notifications", and with them off
the ring has no screen. The ring-time check above still counts it as a
bypass; this one catches it the evening before, while kuhy can still fix it.
- **Phone.** `NotifState` (the same rule `Bypass.checkPermissions` uses: app
notifications off, or the ring channel at `IMPORTANCE_NONE`) logs a
`notifications` event, data `enabled` (bool) and `trigger`, and pushes it
at once through `publishNowMain`. Triggers: an exact alarm at 21:00
(`NotifAlarm`, request code 1007, `evening`; re-armed by its receiver, by
every `AlarmScheduler.schedule`, boot and the watchdog, always the next
future 21:00) and `NotifBlockReceiver` on `APP_BLOCK_STATE_CHANGED` /
`NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED` for the ring channel
(`app_block`, `channel_block`). Both receivers hold the broadcast open
(`NotifRules.holdMs`: 8 s for a foreground broadcast, whose ANR budget is
10 s, else 25 s) so the headless engine is not frozen mid-push.
- **PC** (`_fallback_evening`, rule in `_evening_policy`). The fallback
timer also ticks 21:00-21:59; those ticks skip the morning code. When
today's newest `notifications` event says off, the PC rings
(`notifications_off`) until a newer one says on, or 30 min
(`FALLBACK_RING_CAP`) from the evening's first ring. The cap has its own
latch, `evening_ring.json`, so it never eats the morning's or a bypass's.
The hour gates only *starting*; a ring started at 21:50 runs its 30 min.
- **No ring** when tomorrow is a free or sick day (`free_tomorrow`,
`sick_tomorrow`), when no event was published today (phone off), or when
Firebase does not answer at the tick. An unreachable poll mid-ring keeps
ringing. Events: `evening_tick`, `evening_ring_start`, `evening_ring_stop`
(never the morning's names, so the audit does not count them).
## The monitors ring too
kuhy turns the speakers off at the knob for the night, so the 11-22 fallback
ring played 30 min into silence. Both rings now also play to every connected
monitor (ELD name in `aplay -l`: `G27Q` on HDMI, `VG28UQL1A` on DP, both on
the NVidia card):
- root path: `ring_alsa.sh` starts one `aplay` loop per monitor, IEC958
unmuted;
- PipeWire path: `_ring_monitors.MonitorLoops` runs
`ring_alsa.sh --monitors` as the user beside `pw-play` (PipeWire does not
expose the NVidia outputs).
Each monitor logs one `ring_sink sink=<name> ... result=ok|error` line.
**Silent probe.** `ring_alsa.sh --probe` writes two seconds of digital
silence to each monitor with IEC958 muted (restored afterwards) and logs one
`ring_probe` line per monitor. `_ring_probe.maybe_probe` starts
`wake-alarm-ring-probe.service` once, at `A − 5` on the first morning with no
graphical session (the state a fallback ring meets), and writes
`ring_probe_done`. "No graphical session" means greeter only: lightdm is
masked only before 05:00, when no ring can happen. A morning kuhy is already
logged in at `A − 5` logs one `ring_probe: waiting_for_no_session` event a
day instead. Read it with `journalctl -u wake-alarm-ring-probe` and
`grep ring_probe ~/.local/state/wake_alarm/events.jsonl`.
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
(`scripts/vmbox/guest_cases_monitors.sh`).
## Found on the way: lockdown signals never arrived
focus-owner defined `SIGNAL_LOCKDOWN` but did not request it, and wake_alarm
sends with it as the receiver permission, so every `LOCKDOWN_UNTIL_EOD` and
`LIFT_LOCKDOWN` was dropped. focus-owner now holds it (eeb0def).

View File

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

View File

@ -1,145 +0,0 @@
# The morning session on the PC — the carrot, and what it costs to skip
Companion to `DOCS-morning-session.md` (the phone side). This is how the
phone's morning turns into "no workout lock, no LeetCode lock" on the PC, and
why an aborted morning turns into neither.
## Why
On 2026-09-19 the alarm rang, the full dismiss ran, the session reached the
bathroom tag — and the phone was powered off. Nothing on the PC noticed: the
phone was publishing every finished session and nothing read it, the
workout-lock "carrot" was a hardcoded 05:00–08:30 window in screen-locker
with no link to getting up, and leetcode-guard locked at login regardless. So
finishing the morning was worth at most 30 minutes, and aborting it cost
nothing. Powering the phone off cannot be prevented (device-owner
provisioning, and a 10 s hardware off still wins); it can be *noticed*.
## The rule
The goal is *waking up*, not reaching a clock. So the PC is open from the
moment it is usable (the night lockdown lifts at 05:00) until the alarm has
rung and been dismissed; the dismiss plus the morning session is the "are
you still up" check, and passing it keeps the PC open until 11:00
(2026-09-20 — the first version only opened at 08:30 and locked someone who
got up at 07:00, the opposite of the point):
| the phone says | `exempt_until` | meaning |
|---|---|---|
| nothing started today (`none`) | **alarm + 15 min** (`SESSION_NONE_GRACE`; alarm = the phone's, clamped to ≤ 08:00 like the trigger) | up early is fine; the phone rings at the alarm, and a dismiss that has not produced a session by then means "not up" |
| started, not finished (`in_progress`) | `min(started_at + 90 min, 09:30)` | provisional — the legs take ~40 min; relative to the start because an alarm earlier than 08:00 is legal and a fixed 09:30 would hand an aborted 06:15 session three hours |
| `completed`, finished inside that same cutoff | **11:00** | the carrot |
| `completed` *after* the cutoff | none | a phone switched back on at noon completes the legs then; that un-locks nothing |
| `failed` | none | today's ordinary ladder |
| alarm unknown (unconfigured PC) | none | fail closed |
Fail closed: a sync outage, a refresher that is not running, a bad signature
— all read as "no carrot". Nothing here can make a lock *earlier* than today.
## The plumbing
**wake-alarm is the only Firebase reader.** `wake-alarm-session.timer`
(`*-*-* 05..06:00/10:00`, `07..10:00/2:00` and `11:00:00`, `Persistent=true`,
~133 reads/day — from 05:00 because that is when the login-armed locks
decide) runs `python -m wake_alarm._session --refresh`:
1. `_sync_transport.fetch_firebase_logs()` — every device's `alarm.json`.
2. `_session_payload.newest_session()` — the finished entries of
`morning_sessions` plus `current_session` when it is live, ranked by
`(date, finished-before-live, HLC, device_id)`. **By content, never by
comparing the two fields' stamps**: a phone that lost the network at
finish and never cleared `current_session` still resolves to the finished
morning. The phone's `active` becomes `in_progress`.
3. `_session.to_entry()` + `write_entry()` — an HMAC-signed
`~/.local/state/wake_alarm/morning_session.json` that **always describes
today** (PC-local date): today's session with `exempt_until` signed in, or
a `none` entry (exempt until alarm + 15 min) when the phone has nothing
for today. The entry is also what lets a consumer tell "fresh, no session"
from "the refresher has not run yet" by the date alone.
Dates are the phone's local day throughout. `wake_alarm._state._today_str`
is UTC and must not be used here (screen-locker compares against its local
`today_str`; a UTC date would miss by a day every evening).
**Consumers apply one predicate**: signature verifies ∧ `date == local today`
∧ `exempt_until` present ∧ `now < exempt_until`. Neither re-derives the
cutoffs, neither imports `crdt_sync`, neither talks to Firebase:
- screen-locker `screen_locker/_morning_session.py` → **the early-bird
window *is* this carrot** (`EarlyBirdMixin._is_early_bird_time`, since
2026-09-20; the 05:00–08:30 clock and the extended-to-09:00 reward are
gone). The `wake_alarm_skip` rung defers and banks the early-bird marker;
when the carrot ends, the next run tries a phone/RunnerUp workout before
locking (`early-bird-workout-check.timer` at 09:30:30 and 11:00:30). The
decision record carries `exempt_until` and `outcome`.
- leetcode-guard `leetcode_guard/_morning_session.py` → `_cli._run_lock`
returns `EXIT_OK` with `deferred: …` before `build_client()`. A run
deferral, never ledger state (`decide()` stays pure; a deleted file cannot
mint an unlocked day). `leetcode-guard.timer` gained 09:30 and 11:00 slots
so a deferred run is re-decided at both boundaries. `--check` prints a
`morning` line.
**A PC booted mid-morning** has a missing or yesterday's file until the
timer's `Persistent=true` catch-up lands, and that needs the network. Only
the enforce path, only inside 05:00–11:00, and only when the file is not
today's, both consumers retry for ≤ 180 s (5 s steps) and then proceed as
normal with a WARNING. Status paths never wait; tests pin the retry to 0.
The refresher itself retries an unreadable backend every 5 s for 150 s
(`REFRESH_RETRY_SECONDS`) before exiting 1 with a WARNING: a PC booted at
07:48 had no DNS for its first seconds, and the old single try left the next
chance at the 07:50 tick (2026-11-07).
**`next_step`** (signed with the rest): while the session is `in_progress`,
the label of the first leg not in the phone's `passed` map, else `null`.
Names and labels live in `_session_legs.py` and are pinned to the phone's
`SessionLeg` by `wake_alarm/tests/fixtures/session_legs.json`, asserted by a
Python and a Dart test.
## Known limits (v1, deliberate)
- A lock already on screen is not lifted by a later publish: a session
that completes at 09:45 after the 09:30 lock stays locked. The publish
would have to arrive before the boundary. (The 05:00 login-arm no longer
hits this: the day starts exempt.)
- A session finishing inside ~2 min before 09:30 may be seen as
`in_progress` at the 09:30 tick and lock; bounded by the timer cadence.
## The workday stick (2026-09-23)
The carrot above only pulls on a day the PC is actually being used to enjoy
it — a weekend. On a workday the user leaves for the office regardless, so
losing/keeping the PC's lock was worth nothing, and powering the phone off
at ring time (which stops the alarm dead — nothing left to sync, no session
ever recorded) cost nothing either.
On **Tuesday/Wednesday/Thursday** — `wake_alarm._constants.STICK_DAYS`, the
same weekdays screen-locker already calls "relaxed"
(`_weekly_check.is_relaxed_day`) and leetcode-guard already prices as cheap
(`Pricing.doubled_days`) — a genuine miss (`failed`, or `none` past its own
`SESSION_NONE_GRACE`; a *late* `completed` is not a miss, the walk still
happened) costs tomorrow's leniency in both apps instead of just resetting
to normal. `wake_alarm._workday_penalty.maybe_apply()` runs at the end of
every `_session.refresh()` and, when a stick-day miss is detected and today
is not a free day, signs and writes
`~/.local/state/wake_alarm/workday_penalty.json` (`{"penalty_date":
"<tomorrow>", "issued_date": "<today>"}`) — deliberately a separate file
from `morning_session.json`, since that one always describes *today* and is
overwritten at the date rollover, so it cannot carry a marker forward.
screen-locker and leetcode-guard each read it with the same HMAC + date
predicate they already use for `morning_session.json`.
A phone-side stick (locking down distracting apps on the phone itself,
signalled to `phone-focus-mode`'s `focus-owner`) is the other half of this
and lives in `phone_app/`, not here — see its own commit/doc for the exact
signal shape.
## Commands
```sh
python -m wake_alarm._session --refresh # fetch, select, rewrite the file
python -m wake_alarm._session --show # the verified file + a verdict line
python -m wake_alarm._energy # {"date", "level"} or exit 1
systemctl --user list-timers | grep wake-alarm-session
journalctl --user -u wake-alarm-session.service -n 20
leetcode-guard --check # the "morning" line
```

View File

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

View File

@ -14,7 +14,6 @@ the ring/dismiss path in `phone_app/lib/`.
`AlarmService` (foreground service: wakelock, sound, vibration, full-screen `AlarmService` (foreground service: wakelock, sound, vibration, full-screen
intent) · `AlarmActivity` (dismiss screen over the lockscreen) · intent) · `AlarmActivity` (dismiss screen over the lockscreen) ·
`BootReceiver` (re-arm after reboot) · `StepCounter` (item 3 fallback). `BootReceiver` (re-arm after reboot) · `StepCounter` (item 3 fallback).
Free/sick days and the pre-alarm pool sync: `DOCS-sick-days.md`.
**Never replace any of this with a pub plugin.** The stack is AGP 9.0.1 / **Never replace any of this with a pub plugin.** The stack is AGP 9.0.1 /
Gradle 9.1 / Kotlin 2.3.20; a plugin that will not compile against AGP 9 breaks Gradle 9.1 / Kotlin 2.3.20; a plugin that will not compile against AGP 9 breaks
@ -44,16 +43,6 @@ Things that are a hard crash or a silent no-ring, not a warning:
change. `raiseAlarmVolume()` does run on this hardware (observed raising change. `raiseAlarmVolume()` does run on this hardware (observed raising
`oldIndex:0` → 7, no `SecurityException`), which recovers a stream turned `oldIndex:0` → 7, no `SecurityException`), which recovers a stream turned
down to zero but not one muted by total silence. down to zero but not one muted by total silence.
- **The ring fades in; the stream still goes to max.** Two different knobs,
and merging them trades a gentle start for a silent alarm.
`raiseAlarmVolume()` fixes the *system stream* — a stream left at 0 would
silence the alarm outright. `startVolumeRamp()` climbs the *player's own
gain* from `RAMP_START_GAIN` (0.04) to full over `RAMP_DURATION_MS` (60 s),
quadratically, because perceived loudness is not linear in amplitude.
Measured on the Pixel 6a (2026-08-31) from `dumpsys media.audio_flinger`
track gain: −28 dB at 3 s, −21 dB at 15 s, −12 dB at 30 s, 0 dB at 62 s.
Every step re-reads `player`, and `stopSound()` drops the queue before
releasing it, so a dismissal mid-ramp cannot touch a released `MediaPlayer`.
- **`android:foregroundServiceType="mediaPlayback"` must be on the `<service>` - **`android:foregroundServiceType="mediaPlayback"` must be on the `<service>`
in the manifest AND passed to `startForeground()`.** Omitting either is a in the manifest AND passed to `startForeground()`.** Omitting either is a
hard crash the moment the alarm fires on API 34+ — and it is invisible on an hard crash the moment the alarm fires on API 34+ — and it is invisible on an
@ -115,49 +104,6 @@ minutes and answer questions without standing up, which is weaker than the
gate this replaced. Without some such hatch a dead tag at 06:00 leaves an gate this replaced. Without some such hatch a dead tag at 06:00 leaves an
alarm that literally cannot be switched off. alarm that literally cannot be switched off.
## Home presence — the alarm knows where it is
Away from home the two tags are screwed to walls in another city, so the
sequence is unsatisfiable. `HomePresence.read` (Kotlin) reports raw
observations and `lib/services/home_presence.dart` decides; away skips the two
*tag* stages and **keeps the normal 3 challenges**. The walk still counts.
- **Never "modernise" `WifiManager.getConnectionInfo()`.** It is deprecated at
API 31 in favour of `NetworkCapabilities.getTransportInfo()`, and that
replacement does not work here: the *synchronous*
`ConnectivityManager.getNetworkCapabilities()` redacts every
location-sensitive field, so `transportInfo` is null and the BSSID silently
vanishes. Measured on the Pixel 6a (API 36, 2026-08-31) — connected to a
known AP, fine location granted, location services on — the capabilities
route returned `ssid=null bssid=null` while the GPS fallback quietly covered
for it. Un-redacted `transportInfo` needs a `registerNetworkCallback`.
- **A redacted BSSID is `02:00:00:00:00:00`, not null and not an error.**
Android returns it when fine location is missing *or* location services are
off. Untreated it is a valid-looking MAC that never matches, so every
morning reads "away" and the ritual silently stops happening.
- **Unreadable means away** — the user's explicit choice. A revoked permission
therefore weakens the alarm rather than breaking it loudly, which is why
`HomePresenceLine` puts the verdict *and its cause* on the home screen.
**Unconfigured is not unreadable:** an install that never captured a home
keeps the strict sequence, or shipping this would have deleted the gate.
- **Presence resolves before the missing-tags bypass** (`ring_startup.dart`).
Both skips latch one-way, so whichever fires first fixes the count; the
other order would give every away morning with NFC off the punitive 6.
Equally, `activateBypass()` is refused after `activateAwayProfile()` — the
ring screen's 5-minute timer fires unconditionally and an away morning
crosses 5 minutes routinely.
- **Registration passes `withFix: true`; the ring screen does not.** A Wi-Fi
answer short-circuits GPS, which is what makes the verdict instant at home —
but it also meant capture never recorded a coordinate, so the GPS fallback
could only ever be configured with Wi-Fi off, i.e. never.
- **BSSIDs are a list, and the SSID matches too.** A dual-band router answers
to a different BSSID per band and the phone roams overnight; one stored
address would call a band switch "travelling".
- The read runs from `AlarmActivity` (foregrounded, so while-in-use location
suffices). **Do not move it into `AlarmService`** — that would mean
`foregroundServiceType="mediaPlayback|location"` plus
`FOREGROUND_SERVICE_LOCATION`, on the one path that must not break.
**`ringNow` + `lib/main_ring_probe.dart` are a deliberate manual test **`ringNow` + `lib/main_ring_probe.dart` are a deliberate manual test
handle**, the phone-side equivalent of `wake-alarm.service` on the PC: the handle**, the phone-side equivalent of `wake-alarm.service` on the PC: the
normal arm path needs a sync backend connected, so there is no other way to normal arm path needs a sync backend connected, so there is no other way to
@ -169,81 +115,15 @@ channel and arms nothing. Do not "clean these up" without replacing the
capability. capability.
Emulator: `wake_alarm_api36` (Pixel 6a profile, API 36). The SDK tools are at Emulator: `wake_alarm_api36` (Pixel 6a profile, API 36). The SDK tools are at
`~/sdk/Android/Sdk` but **not on PATH** — export `ANDROID_HOME` and add `~/Android/Sdk` but **not on PATH** — export `ANDROID_HOME` and add
`cmdline-tools/latest/bin`, `emulator` and `platform-tools` yourself. The `cmdline-tools/latest/bin`, `emulator` and `platform-tools` yourself. The
phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so
`phone_deploy.sh` needs `--release` or the install fails with `phone_deploy.sh` needs `--release` or the install fails with
`INSTALL_FAILED_UPDATE_INCOMPATIBLE`. `INSTALL_FAILED_UPDATE_INCOMPATIBLE`.
**Never pass `--build-number` by hand**, including for the probes: use
`phone_deploy.sh <app> --release --target lib/main_ring_probe.dart` and let it
pick. Android compares versionCode only upward, so a hand-picked number puts
the phone above what CI will mint and locks CI out until the commit count
catches up — the only other escape is an uninstall, which wipes the sync
identity (the tags and home come back from sync since 2026-09-11, see
below). This happened on 2026-08-31 (probe
builds at 200/201 stranded the phone at 207 against a ceiling of 156).
`.versioncode-offset` at the repo root is the recovery valve, read by **both**
`release-apk.yml` and the local gate so the two can only move together; it is
currently 101. `hooks/build_number_guard_pretool.sh` now blocks the bypass.
**The ring screen must close itself on dismiss.** `AlarmActivity` handles **The ring screen must close itself on dismiss.** `AlarmActivity` handles
`closeRingScreen` (the shared `AlarmChannel` holds `applicationContext` and `closeRingScreen` (the shared `AlarmChannel` holds `applicationContext` and
cannot finish an activity). Without it the dismiss screen stays up over the cannot finish an activity). Without it the dismiss screen stays up over the
lockscreen forever — back is disabled by design in both halves — and the live lockscreen forever — back is disabled by design in both halves — and the live
instance would carry a satisfied room proof and the solved answer into the instance would carry a satisfied room proof and the solved answer into the
next ring. next ring.
## Tags and home location survive a reinstall
Both used to live only in SharedPreferences, and a reinstall on 2026-09-11
lost them. They are properties of the flat, not of one install, so
`lib/services/settings_sync.dart` carries them as two extra per-field entries
on the same `alarm.json` record the PC reads (`nfc_tag_ids`,
`home_location`); the PC parser reads only the hour/minute fields and ignores
the rest. `AlarmSyncService.pushWith` is a real `syncLog` tick now — pull every
device directory, merge per field by HLC, push — and `AlarmPublisher.publish`
wraps it: stage local edits → sync → apply the winners back into prefs. That
last step is the restore. Verified 2026-09-11 on a fresh `wake_alarm_api36`
install: both tags and the home appeared with zero taps after Google sign-in.
- **Last-writer-wins by wall time, from the local `editedAt`** stamps
(`roomProof.editedAt`, `homeLocation.editedAt`). A value applied *from* the
log is stamped with the log's wall time, and comparisons are on wall time
only — comparing counter/node id on that tie would push the same value
straight back every tick.
- A value from before stamps existed is staged at epoch+1 ms: pushed when
nothing else is known, loses to any real edit.
- **Registering a tag pushes on the Back to the home screen** — the Settings
pop now runs `_syncToPc()`, not just `_loadSyncState()`. Without that the
push waited for the next cold start, which is the same "it vanished" again.
- `setLocal` merges into the existing record; a whole-record upsert there
would drop the settings fields from every push. `HomeBody.syncEpoch`
remounts the presence line after each sync so a restored home shows at once.
- The emulator is a real peer: its device directory outranks the phone by
HLC while it exists. Delete `wake-alarm-sync/devices/<emulator-uuid>` after
a restore test.
## The home screen's startup order, and the ring's clock
Moved here from `CLAUDE.md` on 2026-09-16 for its line cap; nothing below
has changed.
**`HomeScreen.initState` must stay strictly sequential.** It runs
`_applyPolicy()` → `_loadSyncState()` → `_syncToPc()` through one
`_bootstrapSync()`, because the last reads what the first two write and
`AlarmPublisher.publish` takes the service as a *parameter* — captured by
value, so a later assignment can never reach it. Running them concurrently
(as they once were) meant the startup publish always passed `null`, and since
that was the only publish site, **nothing published for three weeks** while
the PC honoured a record from 2026-08-09. `_pickEarlier` must publish too, or
the one schedule edit the app offers never reaches the PC.
Relatedly: `publish()` reports a missing *backend* and a missing *store*
differently on purpose. One string for both is what made the above look like a
configuration the user had never done, while Firebase was connected the whole
time.
`RingScreen` takes an injectable `clock`. `Stopwatch` reads the wall clock,
which `tester.pump()` does not advance, so without that seam no widget test
can reach the two-minute floor or the five-minute bypass.

View File

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

View File

@ -1,72 +0,0 @@
# Sick days -- PC side (2026-10-16)
Split out of `DOCS-wake-enforcement.md` (250-line gate). The phone half and
the pool itself: `DOCS-sick-days.md`.
A sick day (that does not keep `alarm`, see below) is a date in the shared `sickdays` pool (`~/src/utils/sickdays`):
uncapped, no reason, today or later, and **not a free day** -- its own pool,
its own reason strings (`sick_day` / `sick day`). On a sick day `D` (the
alarm's day, so the RTC asks about *tomorrow* the evening before):
| piece | on a sick day |
|---|---|
| fallback ring | never starts; a ring in progress stops (`stop_reason` `sick_day`) |
| RTC self-wake | not armed for `D`; an alarm we armed for `D` is disarmed (`rtc_skip` / `rtc_disarmed`, reason `sick day`) |
| trigger | `morning-routine.service` is not started (`sick day`), like a free day |
| workday penalty | never written for `D`; one *issued* on `D` before `D` was marked is deleted (`penalty_cancelled`, `cause: sick_day`) by the next `_session --refresh` or `_rtc --arm` |
| `morning_session.json` | unchanged: it only *grants* exemptions, and every locker stands down on a sick day by its own check |
| audit | RTC / up-by-A / ring / lockdown checks are n/a; a penalty for `D` on disk or a `lockdown_sent` for a miss on `D` is flagged |
All of it lives behind `wake_alarm/_sick.py`. **Fail closed:** an
unreadable pool, or `sickdays` not importable under `/usr/bin/python`, is
"not sick" -- enforcement runs.
**Sync.** The decisions read the local pool, and the act modes pull it from
Firebase first (`sickdays.sync_quietly()`), because the sickdays sync timer
alone cannot be trusted at the moment that matters: it is a monotonic
15-minute timer, paused during hibernate and with no `Persistent` catch-up,
so right after the RTC resume the pool can be an interval stale. Pulled:
`_rtc --arm` when the target is a stick day that is not free; the fallback
tick whenever it already goes to the network (`A-5 .. A+45`, and every poll
of a ring in progress, so a day marked sick mid-ring stops it); the day's
first penalty write. The trigger reads only the local file -- the fallback
has pulled from `A-5`. `--dry-run` / `--show` never pull (a pull rewrites
the pool file).
**Other readers of `workday_penalty.json`** (screen-locker, leetcode-guard)
must treat the file as void when **either** its `issued_date` is a day the
*alarm* stands down on (`sickdays.stands_down(sickdays.LOCKER_ALARM,
date.fromisoformat(issued_date))`) **or** its `penalty_date` is a day *their
own* locker stands down on (`stands_down(LOCKER_WORKOUT, ...)` for
screen-locker, `LOCKER_LEETCODE` for leetcode-guard). `issued_date` covers a
miss at 08:15 marked sick at 14:00 -- the deletion runs on the next RTC tick
(<= 15 min) or the next morning's refresh, and a reader must not depend on
that; the ring day belongs to the alarm switch, the penalty day to whatever
the penalty charges.
**Keeping the alarm (`sickdays` 0.2.0).** A sick day may keep lockers
(`sickdays add --keep alarm`). Everything in the table above is the single
`alarm` switch (`_sick.alarm_stands_down`): on a sick day that keeps `alarm`
the fallback ring, RTC self-wake, trigger, workday penalty (written, and not
retracted) and audit behave exactly as on a normal stick day.
**Phone, assumed name:** the phone's `alarm_fired` on a sick day carries
`data.reason = "sick_day"` (by analogy with `free_day`); the audit treats
it as not the morning's ring.
**A stand-down latches at ring time (fixed 2026-11-16).** On 2026-11-11 the
07:40 ring stood down for a sick day (`alarm_fired reason=sick_day`), the
phone cleared the mark at 11:38, and the 19:31 stick check re-read the cache,
found a normal Wednesday with no dismissal and sent a lockdown. That punished
a day whose alarm never rang, so no dismiss was possible. `AlarmReceiver` now
records the skip (`RingWatch.markSkipped`, a `DateHistory` per reason), and
`StickCheck.decideDay` returns `sick_day`/`free_day` for a latched day even
after a clear. The streak look-back skips it too. A phone that was off at A
latches nothing, so a clear still makes that day a stick day (hole 1).
Tests: `StickCheckSickTest`.
**Still open: on-device check.** At the next real miss (Tue/Wed/Thu), right
after 09:30 run `adb -s 23181JEGR08034 logcat -d | grep -E
"LOCKDOWN_ACTIVATED|WORKDAY_LOCKDOWN"` (read-only) and confirm
`LOCKDOWN_ACTIVATED` is followed by `WORKDAY_LOCKDOWN`.

View File

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

View File

@ -1,38 +0,0 @@
# Text-free keep list
Every `textgate scan` hit that stays on purpose. `scripts/check_textgate_keep.sh`
runs the scan and fails on any hit no row below covers. Rework rationale and the
per-screen decisions: `~/data/wake-alarm_notext/keep.md` (2026-11-10 rework).
## Scan exceptions
First cell: a file, or a directory ending in `/`. Second cell: the exact text,
or `*` for any text. The checker parses only this table.
| Path | Text | Reason |
|---|---|---|
| `docs/explanations/` | * | Generated by the `explain-diff` skill (`docs/explanations/index.html`). Explanation pages for the repo, not app UI; a text-free explanation defeats its purpose. |
## Kept but not flagged by the scan
Rows copied from the rework's keep list. The scan does not report these today;
they are listed so the next rework does not delete them.
### OS-level labels: the app name only
| Where | Text | Reason |
|---|---|---|
| `phone_app/lib/ui/app_name.dart` `kAppName` | `WakeAlarm` | `MaterialApp.title`: the task-switcher name, a proper noun |
| `phone_app/android/app/src/main/AndroidManifest.xml` | `android:label="WakeAlarm"` | launcher label, a proper noun |
| `phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AppName.kt` `APP_NAME` | `WakeAlarm` | name of the ring and session notification channels |
### Content: data the program only displays
| Where | Content | Reason |
|---|---|---|
| `room_proof_screen.dart`, `session_tags_screen.dart` | registered NFC tag ids | authored identifiers read off the tag |
| `ring_challenge.dart` `challenge.display` | digits, operators, sequences, the reversed word | the thing you must read to dismiss; always visible |
| `home_location_screen.dart` | captured SSID, BSSIDs, coordinates | read from the radio |
| all screens | clock times, numeral dates, counts, kg, `N/M` | numbers |
| `escape_dialog.dart` | the excuse text kuhy types | typed value |
| `alarm_publisher.dart` two `publish()` failure strings | spoken labels, two distinct cue kinds | CLAUDE.md: keep both messages |

View File

@ -3,7 +3,7 @@
`scripts/vmbox/harness.sh` is this repo's default gate for the shell and `scripts/vmbox/harness.sh` is this repo's default gate for the shell and
system pieces — `install.sh`, the systemd units, `shutdown-wrapper.sh`, the system pieces — `install.sh`, the systemd units, `shutdown-wrapper.sh`, the
power-key inhibitor and the re-fire path. It provisions a throwaway Arch guest power-key inhibitor and the re-fire path. It provisions a throwaway Arch guest
(`~/src/utils/vmbox`), installs this repo into it exactly the way a real machine (`~/utils/vmbox`), installs this repo into it exactly the way a real machine
does, runs the cases, and returns a host-side verdict. does, runs the cases, and returns a host-side verdict.
```bash ```bash
@ -39,13 +39,8 @@ it fails, the harness stops with exit 2 and dumps the log.
- **The phone.** The entire dismiss sequence — two NFC tags, the step counter, - **The phone.** The entire dismiss sequence — two NFC tags, the step counter,
the challenges, the 5-minute bypass — lives in `phone_app/` and is verified the challenges, the 5-minute bypass — lives in `phone_app/` and is verified
on the Pixel 6a, never here. This harness knows nothing about it. on the Pixel 6a, never here. This harness knows nothing about it.
- **The bootloader and the real firmware.** The harness guest is BIOS/GRUB - **The bootloader.** The guest is BIOS/GRUB, this PC is UEFI. Any
(`vm new --uefi` exists since 2026-10-01, OVMF, but is not this board's firmware/ESP work goes straight to the host.
firmware). `vm wake` emulates the RTC power-on from poweroff/hibernate, so
the arming and the boot/resume units are testable; whether *this* board
wakes is host-only (S4 verified 2026-10-01, `DOCS-wake-enforcement.md`).
- **The ring's audio.** The guest gate plays to `snd-dummy`; the speakers,
and a card held busy by the user's PipeWire, are host-only.
- **A green run is not host verification.** Report it as "passed in vmbox, not - **A green run is not host verification.** Report it as "passed in vmbox, not
verified on the host", always. verified on the host", always.

View File

@ -1,233 +0,0 @@
# Wake enforcement v2 — PC fallback alarm, immediate stick, escape hatch
Agreed with kuhy on 2026-10-01. This file is the **contract** between the
phone app, the PC package, focus-owner (`~/src/phone-focus-mode`) and the
daily audit. Change a name here and in every reader in the same commit.
## Why
The carrot (`DOCS-morning-session-pc.md`) pulls only on days the PC is used
in the morning — Fri–Mon. On Tue/Wed/Thu kuhy leaves for work, so the only
lever is something that bites *today*. Two holes made skipping cheap:
1. **A phone switched off before the alarm escaped everything.**
`RingWatch.markFired` never ran, so `WorkdayStick` saw no abandoned ring.
2. **Nothing rang if the phone was off.** The PC's waking role was deleted on
2026-08-30; this brings back exactly one piece of it because the phone
*cannot* ring while powered off — the reason AGENTS.md asks for.
## Behaviour
### PC fallback alarm (every ringing day)
Let `A` be today's alarm (`_sync.get_alarm()`, clamped ≤ 08:00 like the
trigger). Not on a free day, not on a sick day (below). Per-minute tick, `A-5min .. A+45min`:
| condition (first match wins) | action |
|---|---|
| escape recorded for today, or a session started today | stop / do not ring |
| ring already ran 30 min today (`FALLBACK_RING_CAP`) | never again today |
| `now ≥ A + 2 min` and no `ring_started` for today | ring — `phone_silent` |
| `now ≥ A + 15 min` (`SESSION_NONE_GRACE`) | ring — `no_session` |
A **bypass** (the app paused, its admin removed, a permission revoked, the
ring killed) rings before this table, outside the window, until a newer
dismiss or 30 min: **`DOCS-bypass.md`**.
A ring stops on: session start, escape, or the 30-min cap. Firebase
unreachable counts as "no ping, no session" (fail toward ringing) and is
logged as `firebase_unreachable`. While ringing, stop conditions are polled
every 20 s.
**A `no_session` ring after a phone ring is correct, not a missed read
(traced 2026-11-16).** On 2026-10-26 and 2026-11-01 the PC went
`waiting` → `no_session` at A+15. It never logged `phone_silent`, so it did
see `ring_started`. What it never saw was a session for today: the
session tick logged "Newest morning is 2026-10-25" and "2026-10-29" all
morning. Firebase agrees. On 11-01 the phone fired, opened the ring screen
at 07:43 and then logged nothing until a boot at 11:27: no `dismissed`
event, no session. On 10-26 the session started at 11:01. So the PC was
right on both days. A ringing phone that nobody dismisses is the case the
`no_session` row exists for. `test_fallback_policy.py`
(`test_ring_started_waits_for_the_session_grace`) pins it. Why the phone
went quiet after 07:43 on 11-01 is a separate phone question.
**Sound.** 100 %, unmuted, a tone that rises over the first 60 s.
- Active graphical session on seat0 → user PipeWire (`wpctl` + `pw-play`).
- Otherwise (kuhy is not in `audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
to the speakers' card (`ALC897 Analog`, card name `Generic_1`) via `aplay`.
- Both paths also ring every connected monitor (2026-11-22, `DOCS-bypass.md`).
- A morning ring meets the "otherwise" state: the night lockdown masks
lightdm 23:00-05:00 only, and from 05:00 seat0 holds lightdm's greeter
(an X server, but no kuhy session) until kuhy logs in. 2026-11-22: greeter
at 05:00, ALSA ring 07:51, kuhy's session 10:09.
### PC wakes itself (nights before Tue/Wed/Thu)
`wake-alarm-rtc.timer` (evenings + on boot) arms the RTC for
`A − 10 min` of the next stick-day morning with
`sudo -n /usr/sbin/rtcwake -m no -t <epoch>` (already NOPASSWD). The alarm
lives in CMOS, so it survives however the PC goes down.
`~/.config/wake_alarm/pc_wake.json` `{"mode": "hibernate" | "poweroff"}`:
- `hibernate` (default): a logind drop-in makes the **power key** hibernate.
Verified on the host 2026-10-01: two `rtcwake -m disk` cycles resumed
29–44 s after the alarm (FADT: "RTC can wake system from S4 = 1").
A typed `shutdown` stays a real poweroff.
- `poweroff`: no logind change; relies on the firmware waking from S5.
vmbox only, 2026-11-15 (`vm new --uefi`, OVMF): `rtcwake -m no -s 120`
then `systemctl poweroff` left AIE and `RTC_EN` set in CMOS, and the
guest cold-booted 12 s (guest clock) after the alarm (`result=woke`).
QEMU has no S5 wake path, so `vm wake` emulates the firmware half: this
proves the arming survives a poweroff, not that this board wakes from S5.
Host S5 firmware check dropped by kuhy 2026-11-15 (needs a physical
power-on).
### Phone stick (Tue/Wed/Thu, not free days)
A **miss** = no dismiss by `A + 15 min` and no escape for today. Detected by
an exact alarm at `A + 15` *and* at boot (stored alarm `A` passed by ≥ 15 min,
not dismissed today) — the boot path is what closes hole 1.
Lockdown length stacks over **consecutive stick-day misses** (free days are
skipped, they neither break nor extend the streak; a dismissed or escaped
stick day resets it to 0):
| streak after this miss | locked through |
|---|---|
| 1 | today + 1 day |
| 2 | today + 2 days |
| n | today + min(n, 4) days (5 calendar days max) |
During a workday lockdown focus-owner applies its **lockdown allowlist**
(calls, SMS, Signal, maps, transit/ticket, banking + authenticator,
wake-alarm, todo) — narrower than the night list.
### Sick days (PC side, 2026-10-16)
A sick day stands down the fallback ring, RTC self-wake, trigger, workday
penalty and audit: **`DOCS-sick-days-pc.md`**.
### Escape hatch (until 2026-10-15 inclusive)
Bug-glyph button on the stakes card (spoken label "That was a bug"; the
app is text-free since 2026-11-10). Needs a typed reason ≥ 40 characters.
It lifts the phone lockdown, clears the streak, cancels today's PC penalty,
stops a ringing PC alarm, and writes everything into the incident report.
Unlimited uses — every use is listed at the top of that day's report.
After `escapeHatchLastDay` the button is gone (constant, not a setting).
### Stakes shown in the app
Home card: today's stakes (stick day or carrot day), the carrot cutoff, any
pending lockdown/penalty and the streak. Ring screen: one line. Every number
shown comes from Dart constants mirrored against the Python ones by
`wake_alarm/tests/test_stakes_mirrors.py`.
## Data contract
### Firebase — fields on the phone's `alarm.json` (`stageField`)
| field | value |
|---|---|
| `ring_started` | `{"date": "YYYY-MM-DD", "at": "<ISO-8601 with offset>"}` — set when the ring screen opens (Dart). |
| `escapes` | list, newest first, ≤ 30: `{"id", "date", "at", "reason"}` — `date` is the morning being excused. |
| `stick_state` | `{"streak": n, "locked_through": "YYYY-MM-DD" \| null, "last_miss": "YYYY-MM-DD" \| null}` |
| `phone_events` | list, newest first, ≤ 400 entries and ≤ 14 days: `{"at", "kind", "data": {…}}` |
### focus-owner broadcasts (signature permission `SIGNAL_LOCKDOWN`)
- `com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD` — extra `until`
(`YYYY-MM-DD`, inclusive). Missing extra = today (old senders keep working).
- `com.kuhy.focus_owner.action.LIFT_LOCKDOWN` — clears any lockdown now.
- `com.kuhy.focus_owner.action.UNSUSPEND` — run a pass now (lifts a pause).
### PC files (`~/.local/state/wake_alarm/`)
- `events.jsonl` — every PC event (`_log_sink`), `event` key names below.
- `fallback_ring.json` — today's latch: `{"date", "started_at", "stopped_at",
"reason", "stop_reason"}`.
- `workday_penalty.json` — unchanged shape; not written for an escaped day
or a sick day, and removed when an escape arrives for the day it was
issued or that day is marked sick.
### Event names
Phone (`phone_events.kind`): `alarm_fired` (data: `reason` =
`daily`|`rering`|`free_day`|`sick_day` — only `daily` is the morning's ring),
`ring_screen_opened`, `ring_started_published` (data: `date`, `source` =
`alarm`|`ring_screen`), `dismissed`, `stick_check` (data: `trigger` =
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `bypass` (data: `cause`, `date`, `session`; `DOCS-bypass.md`),
`bypass_ignored`, `notifications` (data: `enabled`, `trigger` =
`evening`|`app_block`|`channel_block`; `DOCS-bypass.md`), `unsuspended`, `lockdown_sent` (data:
`until`, `streak`, `resend`: true when a day already penalised sent its
stored lockdown again), `lift_sent`, `escape_used`, `boot`.
`ring_started` is published twice over: a headless Dart engine started by
`AlarmReceiver` at the fire (so a full-screen intent downgraded to a heads-up
on an unlocked phone still counts) and the ring screen; first of the day wins.
The A+15 check uses `setExactAndAllowWhileIdle` (falls back to
`setAlarmClock` only when exact alarms are refused), so it never shows as the
system's next alarm. Boot/watchdog catch up on up to 5 unchecked past days.
PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
`fallback_ring_start`, `fallback_ring_stop`, `evening_tick`,
`evening_ring_start`, `evening_ring_stop`, `ring_backend`, `rtc_armed`,
`rtc_skip`, `firebase_unreachable`, `escape_seen`, `penalty_written`,
`penalty_cancelled` (field `cause`: `escape` | `sick_day`), `audit_written`.
## The desktop must come back after lockdown (2026-11-20)
The carrot assumes the PC has a desktop in the morning. On 2026-11-20 it did
not: the nightly `auto-system-update` installed NVIDIA 620.73 and kernel 7.3.5
while the PC sat in night lockdown. At 05:00 the unlock started lightdm, Xorg
died on `NVRM: API mismatch`, lightdm hit `start-limit-hit`, and every later
trigger logged "already UNLOCKED". kuhy saw only the text console.
The fix lives in digital-wellbeing (`lib/payloads/night-lockdown-gui-recover.sh`):
a morning trigger that finds state UNLOCKED with lightdm down starts it again,
after `reset-failed`. On a driver mismatch it reloads the NVIDIA modules. When
the running kernel has no modules left, it reboots once that day. Boot units
that raced DNS (`reflector`, `periodic-system-startup`) now retry
(system-maintenance). The cause of that race: testsAndMisc's Arch performance
fixers had disabled `NetworkManager-wait-online`, so `network-online.target`
was reached before the LAN existed; they now keep it enabled. Nothing in this repo changed: the morning session and
its 11:00 deferral were fine; only the desktop was missing.
## Verification status (2026-10-01)
- vmbox gate (`scripts/vmbox/harness.sh`, `guest_cases_v2.sh`): install,
timers, root ring unit on `snd-dummy`, sudoers merge, power-key drop-in,
a real `rtcwake` arm, uninstall — all pass. Passed in vmbox, then installed
on the host.
- Host: S4 RTC wake verified twice; both ring backends start and stop. The
root ALSA ring got `Device or resource busy` while PipeWire still held the
card seconds after a PipeWire ring — at night the card is idle and opens
(a silent root `aplay` passed), but a stream left open overnight would
keep it busy. **Decided 2026-11-15:** on the *first* busy open (no retries)
`ring_alsa.sh` rings through the user's PipeWire (`runuser`, then
`python -m wake_alarm._ring_main`); only if that fails does it `fuser -k
-TERM` the card's playback nodes once, retry ALSA once and exit non-zero.
Fallback before kill, because the holder is PipeWire itself. The fallback's
`ring_backend` event says `FAILED` (`started=false`) when PipeWire cannot
play, and the unit's non-zero exit is the loud failure; the user-level
fallback ring is the last line. Gate: vmbox `ring-alsa-busy-fallback`
(10 repetitions) and `ring-alsa-busy-fails-loudly`.
- Emulator (`wake_alarm_api36`): exact A+15 check hidden from the system
next-alarm, headless `ring_started` on a heads-up ring, boot-path miss
(phone off before the alarm) → lockdown through tomorrow, escape hatch.
Not yet on the Pixel: the real focus-owner reaction and Firebase publish.
- Item 13 (black screen): dropped by kuhy 2026-11-12
- Two-tag dismiss on device: dropped by kuhy 2026-11-12
- Locked-keyguard dismiss on device: dropped by kuhy 2026-11-12
## Evidence for Claude
`python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]` and the 11:05 timer write
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.
An existing report is never overwritten silently: exit 2 `refusing to overwrite <path>`
unless `--force`; `--stdout` (alias `--dry-run`) prints and writes nothing, not even
`audit_written`.

21
LICENSE
View File

@ -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.

112
TODO-file-length-250.md Normal file
View File

@ -0,0 +1,112 @@
# Refactor TODO — enforce the 250-line file cap
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
> and say "do refactor_claude_todo". It is self-contained: everything needed to
> execute is below. Generated 2026-08-14 from a measured survey of every repo.
## Goal
Every file in this repo must be **at most 250 lines** — source, tests, and
prose (`.md`/`.txt`/`.rst`/`.tex`) alike — and must **stay** that way forever,
enforced by a gate that fails the commit, not by a note anyone can ignore.
Why: a file that cannot be read in one piece forces re-reads and partial edits,
which is the single largest avoidable cost in an LLM-assisted workflow. Aim by
churn, not size alone — refactoring pays where code is read and changed often
(Fowler, _refactoring economic benefit_).
## Scope in this repo
- **18 files** currently exceed 250 lines (of 73 eligible files).
- **6,553 lines** sit in violation; longest file is **478 lines**.
Exempt (do NOT split these):
- generated files — `*.g.dart`, `*.freezed.dart`, `*.gr.dart`, `**/l10n/generated/**`,
anything with a `GENERATED` header
- markup — `.html`, `.css`, `.scss`
- data files — `.json`, `.yaml`, `.csv`, wordlists and other data-ish `.txt`
(mean line length under 25 chars)
## Violations, highest ROI first
ROI = lines x commits in the last year. Work top-down; a long file nobody edits
has near-zero payoff and should not be first.
| lines | commits/yr | kind | file |
| ----: | ---------: | :--- | :------------------------------------- |
| 478 | 15 | code | `wake_alarm/_alarm.py` |
| 438 | 12 | code | `wake_alarm/tests/test_alarm_part2.py` |
| 435 | 12 | code | `wake_alarm/tests/test_alarm.py` |
| 358 | 8 | code | `wake_alarm/tests/test_alarm_part3.py` |
| 457 | 4 | code | `wake_alarm/tests/test_alarm_sinks.py` |
| 283 | 6 | code | `wake_alarm/tests/test_alarm_part4.py` |
| 329 | 4 | code | `wake_alarm/_alarm_view.py` |
| 405 | 3 | code | `wake_alarm/_audio.py` |
| 386 | 3 | code | `wake_alarm/tests/test_sync.py` |
| 371 | 3 | code | `wake_alarm/_sync.py` |
| 317 | 3 | code | `wake_alarm/_escape_flow.py` |
| 314 | 3 | code | `wake_alarm/tests/test_state.py` |
| 420 | 2 | code | `wake_alarm/tests/test_alarm_audio.py` |
| 351 | 2 | code | `wake_alarm/tests/test_smart_plug.py` |
| 341 | 2 | code | `wake_alarm/_sinks.py` |
_(3 further files over 250 lines not listed — re-run the survey for the full set.)_
## How to split
- **Python** — extract cohesive helpers into sibling modules; keep the public
API and imports stable.
- **Shell** — split into `lib/*.sh` sourced by a thin entry script. Keep
`set -euo pipefail` in each.
- **Dart / TypeScript** — extract widgets/components into their own files.
- **Tests** — split by test-group into sibling files
(`foo.test.ts` -> `foo.parsing.test.ts`, `foo.render.test.ts`). Coverage must
not drop.
- **Docs** — split into topic files under `docs/` with an index. For an
oversized `CLAUDE.md`, move detail into referenced docs so the
always-loaded part shrinks.
**Do not** game the cap: no one-lining, no deleting tests, no moving code into
an exempt extension, no `# noqa`-style suppressions.
## Make it permanent (required — this is the point)
A refactor without a gate silently regrows. Before this task is done:
1. Wire the shared gate `~/utils/scripts/check_file_length.sh` into this repo's
`.pre-commit-config.yaml` as a local hook. If the repo has no pre-commit
config, add a minimal one.
2. The hook checks **files in the commit** (not the whole tree), so unrelated
commits never break, and it **fails** — exit 1, not a warning.
3. No baseline file and no allowlist. Those are suppressions.
4. If this repo has CI (`.github/workflows`), add the same check there so it
also fails on push.
## Done condition
- `bash ~/utils/scripts/check_file_length.sh --all` from this repo root exits 0.
- The repo's own test suite and coverage bar are still green.
- `pre-commit run --files <changed files>` passes.
- A deliberately over-250-line test file, staged, makes `git commit` **fail**.
- For a deployed daemon/app: the entry point still actually runs.
## Verify
Run the suite, then the alarm entry point. The phone_app companion needs `phone-deploy` verification if touched.
## Why this sat untouched (added 2026-08-24)
This repo ran a LOCAL `scripts/check_file_length.py` with `MAX_LINES = 500`,
under a hook named "Max file length (500 lines)". It reported "gated" while
permitting files every other repo rejects -- so the cap looked enforced and
nothing ever failed. The hook now delegates to the shared 250-line gate in
`~/utils`, which reports 17 real violations.
Done condition is now an exit code, not a count:
```
bash scripts/check_file_length.sh --all # must exit 0
```
REMOVE ME AFTER FINISH

225
TODO-hardening-continue.md Normal file
View File

@ -0,0 +1,225 @@
# Wake-alarm hardening — continue here
REMOVE ME AFTER FINISH
Phases 0–7 are committed (`4286fcb`..`f5eb7fc`). This file is the entry point
for the rest. **Full plan, with every measured finding:**
`~/.claude/plans/wake-alarm-still-does-witty-toucan.md` — read it before
starting; this file deliberately does not duplicate it.
## Done so far
| Item | State |
|---|---|
| 6 audio (HDMI silent) | **Done.** `_reactivate` wired into `WakeAlarm`; verified on the host — the HDMI sink appeared and became default. |
| 7 speakers | `DOCS-speaker-recommendation.md`. Prose only, done. |
| 9 refactor | `_alarm.py` 478→250. 12 new modules; see `DOCS-architecture.md`. |
| 11 failsafe | `FAILSAFE_SILENCE_SECONDS=300`, audio only. Escalation re-tuned to fit inside it. |
| 12 logging | JSONL + cross-process dedupe + derived correlation id. |
| 14 fans | Gone: code, script, sudoers entry, installed state. Three stale doc/message references cleaned up in phase 6. |
| 2 power button | **Done.** `_inhibit.py` (logind block, self-terminating, stale cleanup by pid via `/proc`) + `_alarm_session.py` fire-time record, re-fired by `_trigger` outside the catch-up window. |
| 10 vmbox | **Done.** `scripts/vmbox/harness.sh` + `DOCS-vmbox.md`. 8 cases, fails closed. Found 2 live bugs the host could not reach. |
| 5 curtains | **Done.** `_curtains.py` driver protocol + no-op default, called from `prepare_hardware()`. `DOCS-curtains-hardware.md` has the buy list. |
| 1/4 phone alarm | **Done, verified on the phone.** Five Kotlin files behind one MethodChannel + the Dart ring screen. Fires from Doze on time, wakes the screen over the lockscreen, rings through DND on STREAM_ALARM, and dismisses via an NFC tap + challenge. Confirmed by the user on the Pixel 6a, not inferred. |
| 3 room proofs | **Mostly done.** NFC works end to end: `NfcReader.kt` (hand-written), Settings → "Room proof" registers the tag, and a tap satisfies the gate. Steps+elapsed is the fallback. QR is specified, persisted and unit-tested but has **no scanner UI** — `mobile_scanner` is the droppable extra. |
## Remaining, in order
1. ~~QR scanner UI~~ — **cancelled 2026-08-30.** QR was deleted rather than
finished: it had never been reachable at ring time (no scanner package, no
CAMERA permission, `onQrScanned` had no caller), and a printed code is
photographable, so completing it would have added a bypass to the very gate
the same change was hardening. The dismiss path is now a strict sequence:
tag 1 → 25 steps + 2 min → tag 2 → 3 challenges.
2. **Item 8, mutual gating.** Phone half is now in place. This is the phase
that legitimately touches `_sync.py`, so it carries that split (see below).
3. **Item 13, black screen.** Different repo (`~/testsAndMisc/
linux_configuration`), host-only, blocks nothing.
### Verified end to end on the Pixel 6a, 2026-08-27
**The whole path is confirmed on hardware, by the user, not inferred:**
- Fires from Doze on time (22:03:01 for a 22:03 arm), registered by the system
as `RTC_WAKEUP` / "Next wake from idle".
- Wakes the screen (`Asleep`→`Awake`) and puts `AlarmActivity` on top over the
lockscreen, with the full-screen-intent notification posted.
- **Rings through DND** — `zen_mode=1`, player `state:started` on
`usage=USAGE_ALARM`/`STREAM_ALARM(4)`, `mutedState:none`. The STREAM_ALARM
claim is measured, no longer assumed.
- NFC tag registers (Settings → Room proof) and **a tap dismisses**:
`tag discovered: 0465dab3ce2a81` on the ring screen, challenge solved,
alarm silent.
- Step counter reaches the gate.
**Four defects were found only because it was run on the phone**, every one
invisible to the emulator (no NFC, no step sensor) and to the widget tests
(which mock the channel):
1. `AlarmActivity.onPause` called `NfcReader.stop()`. `enableReaderMode` is
per-activity but `disableReaderMode` is global, so anything briefly in
front of the ring screen killed polling for the rest of the ring.
2. `TYPE_STEP_COUNTER` is cumulative and on-change: it emits nothing until the
user has already walked, and the first emission was being eaten as the
baseline, so the screen sat at `0/25` forever. `TYPE_STEP_DETECTOR` is now
primary — one event per stride, no baseline to miss.
3. NFC does not poll while the ring shows over a locked keyguard
(`mScreenState=ON_LOCKED`). `requestDismissKeyguard()` is called on fire.
It does **not** silently unlock a secured phone — it raises the PIN prompt
— so "tap without touching the phone" was never achievable on a secured
device. Say that plainly; don't let docs imply otherwise.
4. The **flash** challenge hides its code after 4s, which is unsolvable when
the screen is reached by walking to another room. Removed from the phone's
rotation, with a test asserting no self-hiding challenge is ever shown.
**A process lesson worth more than any of them:** after hardware confirmed the
path worked, the next change bundled a MethodChannel restructure with a bug
fix and regressed both NFC and steps. The user caught it. When hardware has
just gone green, make the smallest possible delta on top of *that exact state*
— never a restructure and a fix together.
### Fully automatic, verified on the Pixel 2026-08-27
The alarm is no longer opt-in and can no longer be weakened:
- **Arms itself with zero taps.** Launching the app was enough —
`dumpsys alarm` showed `RTC_WAKEUP ... com.kuhy.wake_alarm_sync/.AlarmReceiver`
at `2026-08-28 08:00:00`, `window=0`, `exactAllowReason=policy_permission`.
- **08:00 daily is baked in** (`AlarmPolicy.baselineHour`, mirrored by the PC's
`FALLBACK_ALARM_HOUR`). There is no arm button and no cancel — the Kotlin
`cancel` handler is deleted, so the capability does not exist rather than
being one `invokeMethod` away.
- **Earlier-only ratchet, confirmed on-device.** Picking a later time was
rejected on the phone with "That is not earlier than 08:00. The alarm can
only be moved earlier.", and the armed alarm stayed at 08:00. An earlier
start is one-shot and resets after the alarm fires.
- **Daily watchdog** (`AlarmWatchdog`) re-arms if nothing is scheduled, and
`BootReceiver` re-establishes it because `setInexactRepeating` does not
survive a reboot.
- **PC watchdog:** `_trigger._clamp_to_baseline()` refuses any resolved alarm
later than 08:00 whatever its source, so a stale or tampered remote value
cannot move the alarm later through sync.
### DND: verified for priority mode, NOT for total silence
Measured on the Pixel: `STREAM_ALARM` is unmuted under **priority** DND
(`zen_mode=1`, mask `0x1a6`) and **muted** under **total silence**
(`zen_mode=2`, mask `0x9be`). The confirmed ring was priority DND. No audio
flag escapes total silence, so if that gap matters the fix is a zen-policy
check at arm time, not an audio change. Detail in `DOCS-phone-alarm.md`.
Two harness traps found while testing this, worth keeping:
- **Do not pass `--build-number` to a probe build** — it produced a
non-running APK.
- **The arm probe can register for TOMORROW.** It calls `schedule()`, then
`main.dart`'s `rearm()` recomputes `nextOccurrence`; if the armed minute has
passed by then the alarm lands on the next day. Always re-check the
registered `triggerTime` is today before waiting for a ring.
### Still unverified
- The **two-tag sequence** has not been walked end to end on the phone: only
one physical tag is registered, so every on-device run so far has fallen
through to the 5-minute bypass. Needs a second tag.
- The **locked-keyguard** dismiss was not run to completion: the confirmed run
was on an unlocked phone. The PIN-prompt path is implemented but unproven.
## Decisions already made — do not re-litigate
- Failsafe stops **sound only**; lock, challenge and workout gate persist.
- Gating is **phone first, then PC**, with a bounded escape: if sync is
unreachable for ~600 s the PC gate degrades to locally-solvable, logged
WARNING. Without that, a Firebase outage means you can neither dismiss nor
get to work.
- Room proof: NFC **or** QR qualifies. **Steps alone does not** — the phone is
stationary in the other room while you walk *to* it, so steps only accrue
after pickup and can be faked by shaking it in bed. Steps + elapsed time is
the fallback when both others fail. (I narrowed "any one satisfies" here;
say if you disagree.)
- Phone alarm: hand-written Kotlin behind one MethodChannel, **not** a plugin.
AGP 9.0.1 / Gradle 9.1 / Kotlin 2.3.20 is bleeding edge and a plugin that
won't compile breaks the build outright. `STREAM_ALARM` is load-bearing —
it is what ignores DND and silent mode.
- Curtains: no hardware; pluggable driver + logging no-op default.
- Quality bar: 100% branch coverage, no new `# noqa` / `type: ignore`.
## Traps found in the phone session
- **The plan's `LogStore.changes` does not exist.** `crdt_sync_dart` has no
Stream at all. Re-arm therefore needs three explicit hooks — startup,
BOOT_COMPLETED, dismiss — and dropping any one makes the alarm ring once
and then silently stop forever.
- **The Android SDK was never missing, only unexported.** `~/Android/Sdk` has
`cmdline-tools`, `emulator` and `platform-tools`; only `adb` was on PATH.
Export `ANDROID_HOME` rather than installing anything.
- **A permission declared in the manifest is not a permission granted.**
Both `POST_NOTIFICATIONS` and `ACTIVITY_RECOGNITION` are runtime grants, and
each one missing silently breaks a different half of the dismiss path
(no full-screen intent / no step sensor). The AVD caught both because a
freshly installed app there sits at `importance=NONE`.
- **A debug probe entrypoint with its own UI proves nothing about the route.**
The first probe rendered its own widget, so the AVD run validated the Kotlin
and nothing about `/ring`. Point the probe at the real app widget.
## Traps that cost time this session
- **The 250-line gate fires on *staged* files.** Touching a file means
splitting it in the same commit. Still over (re-measured 2026-08-27, after
phase 6): `test_sync.py` 386, `_sync.py` 371, `test_smart_plug.py` 351,
`_sinks.py` 341, `_alarm_view.py` 329, `_escape_flow.py` 317,
`test_state.py` 314. Budget for it. `test_trigger.py` is now split and
under.
- **`morning_routine/_orchestrator.py:39` hardcodes `"wake_alarm._alarm"`**
(different repo, `~/testsAndMisc`). Any module-path change updates it in the
*same* commit. This exact omission caused a month-long silent outage. Keep
`main()` in `_alarm.py`.
- **Splitting a test file loses its fixtures.** `_make_mock_tk`,
`_block_real_tk` and `_block_extra_devices` live *after* the imports, so a
naive header-copy drops them and every test errors. Copy the whole region
before the first `class`. Also: a multi-line module docstring gets stranded
if you replace only its first line.
- **Moving a symbol breaks `patch("wake_alarm._alarm.X")` silently** — the
patch stops intercepting and the test asserts nothing. Grep the whole
`tests/` tree for the old target after any move.
- **Autoformat strips an import added before its first usage.** `struct`
vanished from the extracted `_tone.py`; ruff, mypy and pylint all passed.
Only running it caught the `NameError`. Add import and usage in one edit.
- **Never let a beep-loop test miss its rung.** A test that patches only one
of `_beep_soft/_medium/_loud` and waits for it will spin forever on the real
audio stack and hang the whole suite instead of failing. Patch all three.
- Run tests with `/usr/bin/python3`, not the dev venv (no `gatelock` there).
- **`vm run` does not propagate the guest command's exit code** — it reports
the VM's verdict. A gate built on it fails *open*. See `DOCS-vmbox.md`.
- **`_state.py`'s UTC `_today_str()` must NOT be flipped to local**, despite
what the plan says. `screen_locker/_wake_state.py` mirrors the helper and
reads the same `wake_state.json`; flipping it loses an earned workout skip
for any dismissal between 00:00 and 02:00 local. `_alarm_session.py` shows
the way around it: carry an aware `fired_at`, compare elapsed time, no date
key at all.
- **Do not split a file the current change does not already have to touch.**
The gate fires on *staged* files, so an oversized file only becomes your
problem once you edit it. Editing `_sync.py` merely to repoint an import
pulled its 371 lines into the changeset and cascaded into five new modules
and a broken tree before being reverted. Prefer putting a new constant in
its single consumer (as `_curtains.py` does) over touching `_constants.py`.
- **A `__main__` CLI extracted to a new module breaks its documented command
silently.** `python -m wake_alarm._sync --show` printed nothing and exited
0 — invisible to ruff, mypy, pylint and the suite alike. If a later phase
moves that CLI, run the documented command and check the *output*.
- **Ruff's autofix will gut a function** whose results are only printed —
it stripped both the assignments and the `print` from a vmbox check, and
every linter stayed green. Grep the file for its output call after any
autofix.
## Verify
```
/usr/bin/python3 -m pytest wake_alarm/tests/ -q # 455 pass, 100% cov
bash scripts/vmbox/harness.sh # 8/8 cases, exit 0
pre-commit run --files <changed>
/usr/bin/python3 -m wake_alarm._trigger --dry-run
/usr/bin/python3 -m wake_alarm._alarm --demo # real window; ask first
```
Done = every item above shipped, this file deleted.

View File

@ -3,26 +3,20 @@
# #
# Usage: bash install.sh # Usage: bash install.sh
# #
# The phone is the alarm. The PC starts the morning routine at the time the # The PC no longer wakes anyone -- the phone does. All this installs is the
# phone last synced, and -- wake enforcement v2, DOCS-wake-enforcement.md -- # per-minute trigger that starts morning-routine.service (and therefore the
# rings itself only when the phone stays silent, and wakes itself (RTC) # workout lock) at the time the phone last synced.
# before a Tue/Wed/Thu alarm.
# #
# What it does: # What it does:
# 1. Installs wake_alarm + dependencies for /usr/bin/python # 1. Installs wake_alarm + dependencies for /usr/bin/python
# 2. Installs the systemd user units and enables their timers (trigger, # 2. Installs the systemd user units and enables the per-minute trigger timer
# session, strip, fallback, rtc, audit) # 3. Removes the retired waking machinery from earlier installs
# 3. Installs the root pieces of the fallback alarm: the ring WAVs, the
# ALSA ring script + system unit, the sudoers lines that let the user
# start/stop that unit, and (pc_wake.json "hibernate" mode only) the
# logind drop-in that makes the power key hibernate
# 4. Removes the retired waking machinery from earlier installs
# #
# Deliberately NOT done, and why: # Deliberately NOT done any more, and why:
# - no shutdown wrapper and no sleep hook: the RTC alarm lives in CMOS and # - no shutdown wrapper, no rtcwake, no sleep hook: the PC does not wake you
# survives however the PC goes down, so neither is needed # - the /etc/sudoers.d/wake-alarm entry is left ALONE. screen-locker's own
# - systemd-logind is never restarted (that kills the graphical session); # _wake_alarm.py still shells out to `sudo rtcwake`, so removing it here
# the drop-in is applied with a HUP reload # would silently break a live feature in another repo.
set -euo pipefail set -euo pipefail
@ -45,93 +39,11 @@ readonly SCRIPT_DIR
readonly REPO_DIR="$SCRIPT_DIR" readonly REPO_DIR="$SCRIPT_DIR"
readonly TRIGGER_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-trigger.service" readonly TRIGGER_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-trigger.service"
readonly TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer" readonly TRIGGER_TIMER_SRC="$SCRIPT_DIR/wake-alarm-trigger.timer"
readonly SESSION_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-session.service"
readonly SESSION_TIMER_SRC="$SCRIPT_DIR/wake-alarm-session.timer"
readonly STRIP_SERVICE_SRC="$SCRIPT_DIR/wake-alarm-strip.service"
readonly STRIP_PATH_SRC="$SCRIPT_DIR/wake-alarm-strip.path"
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user" readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
# Enforcement v2 user units (service + timer each).
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
# Root pieces of the fallback alarm.
readonly PC_DIR="$SCRIPT_DIR/scripts/pc"
readonly WAV_DIR="/usr/local/share/wake-alarm"
readonly RING_SCRIPT_DST="/usr/local/lib/wake-alarm/ring_alsa.sh"
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
# The silent monitor check (wake_alarm/_ring_probe.py starts it once).
readonly PROBE_UNIT="wake-alarm-ring-probe.service"
readonly SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
readonly POWERKEY_DST="/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf"
INSTALL_USER="$(id -un)"
readonly INSTALL_USER
readonly SUDOERS_LINES=(
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $ALSA_UNIT"
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl stop $ALSA_UNIT"
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $PROBE_UNIT"
)
TEMP_DIR=""
cleanup() {
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf "$TEMP_DIR"
fi
}
trap cleanup EXIT
install_ring_audio() {
# fuser (psmisc): the ring script's last resort frees a held card with it.
command -v fuser >/dev/null 2>&1 || sudo pacman -S --needed --noconfirm psmisc
# Generated, never committed: the binary hook forbids WAVs in the repo.
/usr/bin/python3 -m wake_alarm._ring_wav --write "$TEMP_DIR/wav" >/dev/null
sudo install -D -m 0644 "$TEMP_DIR/wav/ring.wav" "$WAV_DIR/ring.wav"
sudo install -D -m 0644 "$TEMP_DIR/wav/ring_loop.wav" "$WAV_DIR/ring_loop.wav"
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
sudo install -m 0644 "$PC_DIR/$PROBE_UNIT" "/etc/systemd/system/$PROBE_UNIT"
sudo systemctl daemon-reload
echo " Ring WAVs, $RING_SCRIPT_DST, $ALSA_UNIT and $PROBE_UNIT installed."
}
install_sudoers() {
# Merge, never clobber: the file also holds the rtcwake entry the RTC
# arming relies on. Validated with visudo before it replaces anything.
local merged="$TEMP_DIR/sudoers" line
# The file is root-only (0440); a missing one starts the merge empty.
sudo cat "$SUDOERS_FILE" 2>/dev/null | tee "$merged" >/dev/null || : >"$merged"
if ! grep -q '/usr/sbin/rtcwake' "$merged"; then
echo "$INSTALL_USER ALL=(root) NOPASSWD: /usr/sbin/rtcwake" >>"$merged"
fi
for line in "${SUDOERS_LINES[@]}"; do
grep -qxF "$line" "$merged" || echo "$line" >>"$merged"
done
sudo visudo -cf "$merged" >/dev/null
sudo install -m 0440 -o root -g root "$merged" "$SUDOERS_FILE"
echo " $SUDOERS_FILE: rtcwake, start/stop $ALSA_UNIT, start $PROBE_UNIT (validated)."
}
install_powerkey_dropin() {
local mode
mode="$(/usr/bin/python3 -m wake_alarm._pc_wake_mode)"
if [[ "$mode" == "hibernate" ]]; then
if sudo cmp -s "$PC_DIR/wake-alarm-powerkey.conf" "$POWERKEY_DST"; then
echo " Power key already hibernates (mode: $mode)."
return 0
fi
sudo install -D -m 0644 "$PC_DIR/wake-alarm-powerkey.conf" "$POWERKEY_DST"
elif sudo test -f "$POWERKEY_DST"; then
sudo rm -f "$POWERKEY_DST"
else
echo " Power key untouched (mode: $mode)."
return 0
fi
# Reload, NEVER restart: restarting logind kills the graphical session.
sudo systemctl kill -s HUP systemd-logind
echo " logind drop-in updated for mode $mode and reloaded."
}
echo "=== Wake Alarm Trigger Installer ===" echo "=== Wake Alarm Trigger Installer ==="
echo "[1/4] Installing wake_alarm for /usr/bin/python..." echo "[1/3] Installing wake_alarm for /usr/bin/python..."
# Editable, and from this clone: a later `git pull` here then updates the # Editable, and from this clone: a later `git pull` here then updates the
# running production code with no reinstall. A non-editable snapshot taken # running production code with no reinstall. A non-editable snapshot taken
# from a scratch directory silently stops tracking this repo. # from a scratch directory silently stops tracking this repo.
@ -139,39 +51,15 @@ echo "[1/4] Installing wake_alarm for /usr/bin/python..."
echo " Installed. Verifying import..." echo " Installed. Verifying import..."
/usr/bin/python3 -c "import wake_alarm; import gatelock" /usr/bin/python3 -c "import wake_alarm; import gatelock"
echo " wake_alarm and gatelock import under /usr/bin/python." echo " wake_alarm and gatelock import under /usr/bin/python."
# The alarm is end-to-end encrypted: without crdt_sync (pynacl, argon2-cffi)
# the trigger can only fall back to the cache and 08:00. Fail the install.
/usr/bin/python3 -c "import crdt_sync, nacl, argon2"
echo " crdt_sync (E2E) imports under /usr/bin/python."
echo "[2/4] Installing systemd user units..." echo "[2/3] Installing systemd user units..."
mkdir -p "$SYSTEMD_USER_DIR" mkdir -p "$SYSTEMD_USER_DIR"
cp "$TRIGGER_SERVICE_SRC" "$TRIGGER_TIMER_SRC" \ cp "$TRIGGER_SERVICE_SRC" "$TRIGGER_TIMER_SRC" "$SYSTEMD_USER_DIR/"
"$SESSION_SERVICE_SRC" "$SESSION_TIMER_SRC" \
"$STRIP_SERVICE_SRC" "$STRIP_PATH_SRC" "$SYSTEMD_USER_DIR/"
for unit in "${V2_UNITS[@]}"; do
cp "$SCRIPT_DIR/$unit.service" "$SCRIPT_DIR/$unit.timer" "$SYSTEMD_USER_DIR/"
done
systemctl --user daemon-reload systemctl --user daemon-reload
systemctl --user enable --now wake-alarm-trigger.timer systemctl --user enable --now wake-alarm-trigger.timer
echo " Trigger timer enabled and started (ticks once a minute)." echo " Trigger timer enabled and started (ticks once a minute)."
systemctl --user enable --now wake-alarm-session.timer
echo " Session timer enabled (07:00-11:00, every 2 min)."
systemctl --user enable --now wake-alarm-strip.path
echo " Strip path enabled (corner reminder while the morning is in progress)."
for unit in "${V2_UNITS[@]}"; do
systemctl --user enable --now "$unit.timer"
done
echo " Fallback (04-09, every min), RTC (every 15 min + boot) and audit"
echo " (11:05) timers enabled."
echo "[3/4] Installing the fallback alarm's root pieces (sudo)..." echo "[3/3] Removing retired waking machinery from earlier installs..."
TEMP_DIR="$(mktemp -d)"
install_ring_audio
install_sudoers
install_powerkey_dropin
echo "[4/4] Removing retired waking machinery from earlier installs..."
# Opportunistic, and deliberately NOT fatal. This script runs under `set -e` # Opportunistic, and deliberately NOT fatal. This script runs under `set -e`
# and the cleanup needs root, so on a machine without cached/passwordless sudo # and the cleanup needs root, so on a machine without cached/passwordless sudo
# a hard call would abort the install *after* the package and timer are # a hard call would abort the install *after* the package and timer are
@ -195,6 +83,3 @@ echo "time the phone last synced."
echo "Check what it resolves right now: python -m wake_alarm._sync --show" echo "Check what it resolves right now: python -m wake_alarm._sync --show"
echo "Check what the next tick would do: python -m wake_alarm._trigger --dry-run" echo "Check what the next tick would do: python -m wake_alarm._trigger --dry-run"
echo "Watch it live: journalctl --user -fu wake-alarm-trigger.service" echo "Watch it live: journalctl --user -fu wake-alarm-trigger.service"
echo "Fallback alarm: python -m wake_alarm._fallback --dry-run"
echo "RTC plan: python -m wake_alarm._rtc --show"
echo "Audit a morning: python -m wake_alarm._audit --dry-run [YYYY-MM-DD]"

View File

@ -12,4 +12,3 @@ GeneratedPluginRegistrant.java
key.properties key.properties
**/*.keystore **/*.keystore
**/*.jks **/*.jks
.kotlin/

View File

@ -77,37 +77,3 @@ kotlin {
flutter { flutter {
source = "../.." source = "../.."
} }
dependencies {
// JVM unit tests (src/test) for the pure decision code -- StickCheck,
// DayCache, RingDecision, PoolSyncSchedule. No Robolectric: anything
// that needs a Context stays out of them.
testImplementation("junit:junit:4.13.2")
}
// Start the Dart compile first. Without the configuration cache (Flutter's
// FlutterTask does not support it) Gradle runs one :app task at a time, and
// `compileFlutterBuild<Variant>` sat ~190th in the plan: on a clean tree it
// started ~8 s in, after :app had idled waiting on plugin resources, then
// held :app for ~20 s while Kotlin, dex and manifests queued behind it.
// Running it before pre<Variant>Build overlaps it with the plugin projects.
// mustRunAfter only orders; it pulls the compile into no task graph.
tasks.matching { it.name.matches(Regex("pre\\w+Build")) }.configureEach {
val variant = name.removePrefix("pre").removeSuffix("Build")
mustRunAfter(tasks.matching { it.name == "compileFlutterBuild$variant" })
}
// Debug APKs only reach the Pixel 6a (arm64-v8a) and the x86_64 emulator.
// Flutter packs three ABIs into every debug APK (182 MB), and merging,
// stripping and zipping libraries no debug install loads cost the clean
// probe build seconds it does not have: the 32-bit ABIs, and the engine's
// 15 MB Vulkan validation layer, loaded only when the manifest sets
// io.flutter.embedding.android.EnableVulkanValidation (it does not).
// Release keeps every ABI.
androidComponents {
onVariants(selector().withBuildType("debug")) { variant ->
variant.packaging.jniLibs.excludes.addAll(
listOf("lib/armeabi-v7a/**", "lib/x86/**", "**/libVkLayer_khronos_validation.so"),
)
}
}

View File

@ -4,5 +4,4 @@
to allow setting breakpoints, to provide hot reload, etc. to allow setting breakpoints, to provide hot reload, etc.
--> -->
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<application android:networkSecurityConfig="@xml/network_security_config" />
</manifest> </manifest>

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Debug builds only: plain HTTP to the PC's Firebase RTDB emulator, which
the AVD reaches as 10.0.2.2 (lib/services/sync_emulator.dart). Every
other host keeps the platform default (HTTPS only). -->
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">10.0.2.2</domain>
</domain-config>
</network-security-config>

View File

@ -19,24 +19,8 @@
<!-- Room proof (item 3): steps are the fallback, NFC the real proof. --> <!-- Room proof (item 3): steps are the fallback, NFC the real proof. -->
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/> <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.NFC"/> <uses-permission android:name="android.permission.NFC"/>
<!-- Home presence: the BSSID of the connected Wi-Fi is redacted to
02:00:00:00:00:00 without fine location, so this gates the Wi-Fi
check as much as the GPS fallback. While-in-use only: the read
runs from AlarmActivity, which is foregrounded over the
lockscreen, so no ACCESS_BACKGROUND_LOCATION and no change to
AlarmService's foregroundServiceType. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Install-time, no prompt. WifiManager/ConnectivityManager throw
SecurityException without these, which would look exactly like
"not at home". -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Lets WorkdayStick reach focus-owner's signature-protected receiver;
both apps are signed with the same release key. -->
<uses-permission android:name="com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"/>
<application <application
android:label="WakeAlarm" android:label="wake_alarm_sync"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"> android:icon="@mipmap/ic_launcher">
<activity <activity
@ -84,57 +68,6 @@
<receiver <receiver
android:name=".WatchdogReceiver" android:name=".WatchdogReceiver"
android:exported="false"/> android:exported="false"/>
<!-- The stick's exact check at A + 15 (StickAlarm.kt); not exported,
only this app's own PendingIntent reaches it. -->
<receiver
android:name=".StickCheckReceiver"
android:exported="false"/>
<!-- The pre-alarm sync of the free/sick day pools (PoolSyncAlarm.kt);
not exported, only this app's own PendingIntent reaches it. -->
<receiver
android:name=".PoolSyncReceiver"
android:exported="false"/>
<!-- The 21:00 notifications check (NotifAlarm.kt); not exported,
only this app's own PendingIntent reaches it. -->
<receiver
android:name=".NotifCheckReceiver"
android:exported="false"/>
<!-- Sent by the system to this app only: its notifications or the
ring channel blocked or unblocked in Settings (NotifAlarm.kt). -->
<receiver
android:name=".NotifBlockReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.app.action.APP_BLOCK_STATE_CHANGED"/>
<action android:name="android.app.action.NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED"/>
</intent-filter>
</receiver>
<!-- The silent buzz before a session deadline (SessionWarn.kt). -->
<receiver
android:name=".SessionWarnReceiver"
android:exported="false"/>
<!-- An active device admin cannot be paused from the launcher;
removing it is a bypass (Bypass.kt). Activated over adb. -->
<receiver
android:name=".WakeAdminReceiver"
android:exported="true"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/wake_admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>
<!-- Sent by the system to this app only; a pause is a bypass. -->
<receiver
android:name=".SuspendReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_SUSPENDED"/>
<action android:name="android.intent.action.MY_PACKAGE_UNSUSPENDED"/>
</intent-filter>
</receiver>
<receiver <receiver
android:name=".BootReceiver" android:name=".BootReceiver"
android:exported="true"> android:exported="true">

View File

@ -3,7 +3,6 @@ package com.kuhy.wake_alarm_sync
import android.app.KeyguardManager import android.app.KeyguardManager
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.view.WindowManager
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel
@ -20,19 +19,7 @@ class AlarmActivity : FlutterActivity() {
/** Dart route the ring screen is registered under in main.dart. */ /** Dart route the ring screen is registered under in main.dart. */
private val ringRoute = "/ring" private val ringRoute = "/ring"
/** override fun getInitialRoute(): String = ringRoute
* The ring by default; the session checklist only when asked for by
* [SessionNotice.resumeIntent] (the launcher redirect or the ongoing
* notification) AND nothing is sounding. A ring always wins: an intent
* that opened the checklist over a live alarm would leave the sound
* running with no dismiss sequence in front of it. Read once, at
* creation -- a live `singleInstance` instance just comes forward on
* whatever screen Dart is showing, which is the right thing.
*/
override fun getInitialRoute(): String {
if (AlarmService.running) return ringRoute
return intent?.getStringExtra(SessionNotice.EXTRA_ROUTE) ?: ringRoute
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
// showWhenLocked/turnScreenOn are also set as manifest attributes; the // showWhenLocked/turnScreenOn are also set as manifest attributes; the
@ -41,14 +28,7 @@ class AlarmActivity : FlutterActivity() {
setShowWhenLocked(true) setShowWhenLocked(true)
setTurnScreenOn(true) setTurnScreenOn(true)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
// The morning session lives in this activity for half an hour after
// the ring stops. With the screen allowed to sleep the activity
// pauses and NFC stops polling, so a tag tap would need a wake and
// an unlock first, every leg.
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
dismissKeyguard() dismissKeyguard()
// A revoke or a killed ring, seen on a relaunch into this screen.
Bypass.checkOnLaunch(this)
} }
/** /**
@ -115,10 +95,6 @@ class AlarmActivity : FlutterActivity() {
// pauses this one and takes reader mode down with it, and the tag tap // pauses this one and takes reader mode down with it, and the tag tap
// must keep working once the ring screen is back in front. // must keep working once the ring screen is back in front.
alarmChannel?.let { NfcReader.start(this, it) } alarmChannel?.let { NfcReader.start(this, it) }
// The user can still lock the phone mid-session with the power
// button. Coming back, the keyguard is up again and NFC is back in
// ON_LOCKED -- the same dead state onCreate handles.
dismissKeyguard()
} }
override fun onPause() { override fun onPause() {

View File

@ -61,109 +61,16 @@ object AlarmChannel {
AlarmService.start(context) AlarmService.start(context)
result.success(null) result.success(null)
} }
// The Dart pool's free dates, cached where AlarmReceiver can
// read them with no engine running. Dart calls this after every
// mark, release and sync; see FreeDays.kt.
"setFreeDays" -> {
val dates = call.argument<List<String>>("dates")
if (dates == null) {
result.error("bad_args", "dates is required", null)
} else {
FreeDays.store(context, dates)
result.success(null)
}
}
// The sick-day twin of setFreeDays; see SickDays.kt.
"setSickDays" -> {
val dates = call.argument<List<String>>("dates")
if (dates == null) {
result.error("bad_args", "dates is required", null)
} else {
SickDays.store(context, dates)
result.success(null)
}
}
// Read-back for the picker: what AlarmReceiver will see.
"getSickDays" -> result.success(SickDays.dates(context))
"hasNfc" -> result.success(NfcReader.isAvailable(context)) "hasNfc" -> result.success(NfcReader.isAvailable(context))
// Raw observations only; home_presence.dart decides what they mean.
// Lives here rather than in MainActivity's override (as NfcReader
// does) because WifiManager/LocationManager need no Activity, and
// the ring screen must be able to reach it through AlarmActivity.
"readPresence" -> HomePresence.read(
context,
call.argument<Double>("homeLat"),
call.argument<Double>("homeLon"),
call.argument<Boolean>("withFix") ?: false,
) { observations -> result.success(observations) }
// Handled by AlarmActivity, which owns the window; reaching here // Handled by AlarmActivity, which owns the window; reaching here
// means the picker asked, where there is no ring screen to close. // means the picker asked, where there is no ring screen to close.
"closeRingScreen" -> result.success(null) "closeRingScreen" -> result.success(null)
"stepCount" -> result.success(StepCounter.stepsSinceRingStart(context)) "stepCount" -> result.success(StepCounter.stepsSinceRingStart(context))
// The morning session's one live deadline, as an absolute epoch
// instant; null drops it (a leg with its re-ring spent must not
// inherit the previous leg's alarm). Dart ints cross the channel
// as Int when they fit and Long when they do not; an epoch in
// millis never fits.
"armReRing" -> {
val at = call.argument<Number>("atMillis")?.toLong()
if (at == null) {
AlarmScheduler.clearReRing(context)
} else {
AlarmScheduler.scheduleReRing(context, at)
}
result.success(null)
}
// The session's finish path, and the only thing that drops a
// pending re-ring. Not named "cancel" and not reachable from any
// screen but the session's own: the wake alarm itself still has
// no off switch.
"finishSession" -> {
AlarmScheduler.clearReRing(context)
SessionNotice.clear(context)
result.success(null)
}
// The live leg, for the launcher redirect and the ongoing
// notification; see SessionNotice.kt. Called on every leg
// change, never per tick.
"updateSessionNotice" -> {
val date = call.argument<String>("date")
val label = call.argument<String>("label")
if (date == null || label == null) {
result.error("bad_args", "date and label are required", null)
} else {
val at = call.argument<Number>("deadlineMillis")?.toLong()
SessionNotice.update(context, date, label, at)
result.success(null)
}
}
// Whether a launch right now would be redirected into the
// morning; the probes ask before starting a test ring.
"morningLive" ->
result.success(AlarmService.running || SessionNotice.isLiveToday(context))
// Whether the ring is sounding; the session screen polls this so
// a deadline that rang while it sat in the background puts the
// dismiss sequence in front the moment it is looked at.
"isRinging" -> result.success(AlarmService.running)
"takeBypassReRing" -> result.success(BypassReRing.take(context))
"peekBypassReRing" -> result.success(BypassReRing.peek(context))
"beginStepCount" -> { "beginStepCount" -> {
StepCounter.markRingStart(context) StepCounter.markRingStart(context)
result.success(null) result.success(null)
} }
// The dismiss gate actually completed -- see RingWatch. Called else -> result.notImplemented()
// once, from the same spot `afterDismiss` starts or resumes a
// session, regardless of outcome: reaching afterDismiss at all
// means the ring was dismissed.
"markRingDismissed" -> {
RingWatch.markDismissed(context)
StickRunner.onDismissed(context)
EventLog.append(context, "dismissed")
result.success(null)
}
else -> if (!EnforcementChannel.handleCall(context, call, result)) {
result.notImplemented()
}
} }
} }

View File

@ -3,7 +3,6 @@ package com.kuhy.wake_alarm_sync
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.util.Log
/** /**
* Receives the exact alarm and hands straight off to [AlarmService]. * Receives the exact alarm and hands straight off to [AlarmService].
@ -16,45 +15,6 @@ import android.util.Log
*/ */
class AlarmReceiver : BroadcastReceiver() { class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
// A session deadline: the user dismissed the alarm and then stalled.
// No free/sick-day check (neither ever starts a session) and no daily
// re-arm -- that is the wake alarm's business, not this one's.
if (intent.getStringExtra(AlarmScheduler.EXTRA_REASON) == AlarmScheduler.REASON_RERING) {
Log.i(TAG, "session deadline missed: re-ringing")
EventLog.append(context, "alarm_fired", mapOf("reason" to "rering"))
AlarmService.start(context)
return
}
// A shared free or sick day means the alarm does not ring -- not
// later, not quieter, not at all -- and nothing ring-related is
// recorded: no markFired and no ring_started for the PC. Only the
// skip itself is latched, so the stick still stands the day down if
// the mark is cleared after the ring time. Re-arm for tomorrow (the armed
// instant has passed, so it rolls over) so the day after is normal.
// Both caches fail closed: unreadable means ring.
val skip = RingDecision.skip(FreeDays.isToday(context), SickDays.isToday(context))
if (skip != null) {
Log.i(TAG, "${skip.label}: not ringing; re-armed for tomorrow")
RingWatch.markSkipped(context, skip)
EventLog.append(context, "alarm_fired", mapOf("reason" to skip.wire))
AlarmScheduler.rearmFromStorage(context)
return
}
// The one fresh (non-re-ring) daily alarm. Recorded here, not in
// Dart, so a poweroff mid-ring can never race it: setAlarmClock has
// already woken the CPU by the time this line runs.
RingWatch.markFired(context)
AlarmService.start(context) AlarmService.start(context)
EventLog.append(context, "alarm_fired", mapOf("reason" to "daily"))
// After the sound is started, never before: tells the PC the phone
// is ringing even when the ring screen never opens.
HeadlessRingStart.start(context)
// Notifications or the full-screen intent switched off: the ring has
// no screen, so the morning counts as bypassed.
Bypass.checkPermissions(context)
}
private companion object {
const val TAG = "WakeAlarmReceiver"
} }
} }

View File

@ -6,7 +6,6 @@ import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Build import android.os.Build
import java.time.LocalTime
import java.util.Calendar import java.util.Calendar
/** /**
@ -23,29 +22,11 @@ object AlarmScheduler {
/** Request code for the single alarm PendingIntent; reused so re-arming replaces. */ /** Request code for the single alarm PendingIntent; reused so re-arming replaces. */
private const val REQUEST_CODE = 1001 private const val REQUEST_CODE = 1001
/**
* Request code for the morning session's re-ring.
*
* Distinct from [REQUEST_CODE] on purpose: a PendingIntent is keyed by
* request code, so arming the re-ring under 1001 would silently replace
* tomorrow's wake alarm with a one-shot twenty minutes from now.
*/
private const val RERING_REQUEST_CODE = 1003
/** Intent extra naming why the receiver fired; absent on the daily alarm. */
const val EXTRA_REASON = "reason"
/** [EXTRA_REASON] value for a session deadline. */
const val REASON_RERING = "rering"
/** SharedPreferences file holding the armed time, so boot can re-arm it. */ /** SharedPreferences file holding the armed time, so boot can re-arm it. */
private const val PREFS = "wake_alarm_scheduler" private const val PREFS = "wake_alarm_scheduler"
private const val KEY_HOUR = "hour" private const val KEY_HOUR = "hour"
private const val KEY_MINUTE = "minute" private const val KEY_MINUTE = "minute"
/** Epoch millis of the armed re-ring, so a reboot mid-session restores it. */
private const val KEY_RERING_AT = "rering_at"
/** Sentinel for "no alarm stored", distinguishable from a valid 0. */ /** Sentinel for "no alarm stored", distinguishable from a valid 0. */
private const val NONE = -1 private const val NONE = -1
@ -62,21 +43,12 @@ object AlarmScheduler {
AlarmManager.AlarmClockInfo(at, showIntent(context)), AlarmManager.AlarmClockInfo(at, showIntent(context)),
firePendingIntent(context), firePendingIntent(context),
) )
// Every arm path (picker, boot, dismiss, free-day skip, watchdog)
// ends here, so the stick's own check can never be left unarmed.
StickAlarm.schedule(context, LocalTime.of(hour, minute))
// Same funnel for the pre-alarm day-pool sync (PoolSyncAlarm.kt).
PoolSyncAlarm.schedule(context, LocalTime.of(hour, minute))
// And the 21:00 notifications check (NotifAlarm.kt).
NotifAlarm.schedule(context)
} }
/** Cancels the armed alarm and forgets the stored time. */ /** Cancels the armed alarm and forgets the stored time. */
fun cancel(context: Context) { fun cancel(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(firePendingIntent(context)) manager.cancel(firePendingIntent(context))
StickAlarm.cancel(context)
PoolSyncAlarm.cancel(context)
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(KEY_HOUR).remove(KEY_MINUTE).apply() .remove(KEY_HOUR).remove(KEY_MINUTE).apply()
} }
@ -96,68 +68,6 @@ object AlarmScheduler {
return true return true
} }
/** The stored daily time `A`, or null when none was ever armed. */
fun storedAlarm(context: Context): LocalTime? {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val hour = prefs.getInt(KEY_HOUR, NONE)
val minute = prefs.getInt(KEY_MINUTE, NONE)
if (hour == NONE || minute == NONE) return null
return LocalTime.of(hour, minute)
}
/**
* Arms the morning session's re-ring for the absolute instant [atMillis].
*
* Same [AlarmManager.setAlarmClock] path as the daily alarm: it is the
* one this repo has proved starts the foreground service with the screen
* off. Replaces any earlier re-ring — the session has exactly one live
* deadline at a time.
*/
fun scheduleReRing(context: Context, atMillis: Long) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putLong(KEY_RERING_AT, atMillis).apply()
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.setAlarmClock(
AlarmManager.AlarmClockInfo(atMillis, showIntent(context)),
reRingPendingIntent(context),
)
SessionWarn.arm(context, atMillis)
}
/**
* Drops the pending re-ring. Reached only from the session's own finish
* path (`finishSession`); there is no Dart-facing cancel for the alarm
* itself.
*/
fun clearReRing(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
manager.cancel(reRingPendingIntent(context))
SessionWarn.clear(context)
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(KEY_RERING_AT).apply()
}
/**
* Re-arms a stored re-ring after a reboot; false when none is still due.
*
* A past instant is dropped, never fired: a session whose deadline
* passed while the phone was off is over, and a stale instant is not
* confined to reboots -- Android re-delivered BOOT_COMPLETED to a
* force-stopped app on its next launch (Pixel 6a, 2026-09-16), which
* fired a nine-minute-old deadline into an evening with no session.
*/
fun restoreReRing(context: Context): Boolean {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val at = prefs.getLong(KEY_RERING_AT, NONE.toLong())
if (at == NONE.toLong()) return false
if (at <= System.currentTimeMillis()) {
prefs.edit().remove(KEY_RERING_AT).apply()
return false
}
scheduleReRing(context, at)
return true
}
/** /**
* Whether the system will actually honour a full-screen intent. * Whether the system will actually honour a full-screen intent.
* *
@ -204,14 +114,6 @@ object AlarmScheduler {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
) )
/** The re-ring's own PendingIntent; the extra is how the receiver tells them apart. */
private fun reRingPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
RERING_REQUEST_CODE,
Intent(context, AlarmReceiver::class.java).putExtra(EXTRA_REASON, REASON_RERING),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** Tapping the clock's alarm chip opens the app rather than the ring screen. */ /** Tapping the clock's alarm chip opens the app rather than the ring screen. */
private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity( private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity(
context, context,

View File

@ -9,12 +9,11 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.ServiceInfo import android.content.pm.ServiceInfo
import android.media.AudioAttributes import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer import android.media.MediaPlayer
import android.media.RingtoneManager import android.media.RingtoneManager
import android.os.Build import android.os.Build
import android.os.Handler
import android.os.IBinder import android.os.IBinder
import android.os.Looper
import android.os.PowerManager import android.os.PowerManager
import android.util.Log import android.util.Log
import android.os.VibrationEffect import android.os.VibrationEffect
@ -32,29 +31,17 @@ import android.os.VibratorManager
class AlarmService : Service() { class AlarmService : Service() {
private var player: MediaPlayer? = null private var player: MediaPlayer? = null
/** Drives the volume ramp; cleared in [stopSound]. */
private val rampHandler = Handler(Looper.getMainLooper())
private var wakeLock: PowerManager.WakeLock? = null private var wakeLock: PowerManager.WakeLock? = null
private var vibrator: Vibrator? = null private var vibrator: Vibrator? = null
companion object { companion object {
private const val TAG = "AlarmService" private const val TAG = "AlarmService"
private const val CHANNEL_ID = NotifState.RING_CHANNEL_ID private const val CHANNEL_ID = "wake_alarm_ring"
private const val NOTIFICATION_ID = 42 private const val NOTIFICATION_ID = 42
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */ /** Vibration: 1s buzz, 1s gap, repeating from index 0. */
private val VIBRATION_PATTERN = longArrayOf(0, 1000, 1000) private val VIBRATION_PATTERN = longArrayOf(0, 1000, 1000)
/**
* Whether the ring is sounding right now. Same process as both
* activities, so a launch during a ring can route to the dismiss
* screen instead of the home screen or a session checklist.
*/
@Volatile
var running: Boolean = false
private set
/** Starts the ring. Safe to call when already ringing — start is idempotent. */ /** Starts the ring. Safe to call when already ringing — start is idempotent. */
fun start(context: Context) { fun start(context: Context) {
val intent = Intent(context, AlarmService::class.java) val intent = Intent(context, AlarmService::class.java)
@ -63,11 +50,6 @@ class AlarmService : Service() {
/** Stops the ring and releases every resource it holds. */ /** Stops the ring and releases every resource it holds. */
fun stop(context: Context) { fun stop(context: Context) {
// Cleared here, not only in onDestroy: stopService is
// asynchronous, and the session screen that follows a dismiss
// polls this flag from its first tick -- a stale true would
// re-ring the alarm it had just silenced.
running = false
context.stopService(Intent(context, AlarmService::class.java)) context.stopService(Intent(context, AlarmService::class.java))
} }
} }
@ -86,14 +68,12 @@ class AlarmService : Service() {
acquireWakeLock() acquireWakeLock()
startSound() startSound()
startVibration() startVibration()
running = true
// START_STICKY: if the system kills us under memory pressure while the // START_STICKY: if the system kills us under memory pressure while the
// user is still asleep, the alarm comes back rather than going silent. // user is still asleep, the alarm comes back rather than going silent.
return START_STICKY return START_STICKY
} }
override fun onDestroy() { override fun onDestroy() {
running = false
stopSound() stopSound()
stopVibration() stopVibration()
releaseWakeLock() releaseWakeLock()
@ -105,9 +85,10 @@ class AlarmService : Service() {
// IMPORTANCE_HIGH is required for a full-screen intent to be honoured. // IMPORTANCE_HIGH is required for a full-screen intent to be honoured.
val channel = NotificationChannel( val channel = NotificationChannel(
CHANNEL_ID, CHANNEL_ID,
APP_NAME, "Wake alarm",
NotificationManager.IMPORTANCE_HIGH, NotificationManager.IMPORTANCE_HIGH,
).apply { ).apply {
description = "The ringing wake alarm"
// The service owns sound and vibration, so the channel must not add // The service owns sound and vibration, so the channel must not add
// its own — a channel sound would play on the notification stream // its own — a channel sound would play on the notification stream
// and be silenced by DND, unlike STREAM_ALARM. // and be silenced by DND, unlike STREAM_ALARM.
@ -128,6 +109,8 @@ class AlarmService : Service() {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
) )
return Notification.Builder(this, CHANNEL_ID) return Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Wake alarm")
.setContentText("Tap to dismiss")
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm) .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setCategory(Notification.CATEGORY_ALARM) .setCategory(Notification.CATEGORY_ALARM)
.setOngoing(true) .setOngoing(true)
@ -166,20 +149,30 @@ class AlarmService : Service() {
) )
isLooping = true isLooping = true
prepare() prepare()
// Start almost silent. The stream still goes to max below, so a
// stream muted to zero cannot silence the alarm -- it is the
// player's own gain that climbs.
setVolume(AlarmVolume.RAMP_START_GAIN, AlarmVolume.RAMP_START_GAIN)
start() start()
} }
AlarmVolume.raiseStream(this) raiseAlarmVolume()
AlarmVolume.startRamp(rampHandler) { player } }
/**
* Alarm stream turned down to zero must not silence the alarm.
*
* Guarded: setStreamVolume can throw under an active zen rule, and by this
* point startForeground() has already posted — an exception here would
* take the whole ring down over a volume bump that is only an
* improvement, not the mechanism.
*/
private fun raiseAlarmVolume() {
try {
val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager
val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM)
audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0)
} catch (e: SecurityException) {
Log.w(TAG, "could not raise the alarm volume; ringing anyway", e)
}
} }
private fun stopSound() { private fun stopSound() {
// Before releasing the player: a queued step that runs afterwards
// would touch a released MediaPlayer.
rampHandler.removeCallbacksAndMessages(null)
player?.run { player?.run {
if (isPlaying) stop() if (isPlaying) stop()
release() release()

View File

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

View File

@ -54,11 +54,6 @@ object AlarmWatchdog {
fun verify(context: Context) { fun verify(context: Context) {
val rearmed = AlarmScheduler.rearmFromStorage(context) val rearmed = AlarmScheduler.rearmFromStorage(context)
Log.i(TAG, "daily check: rearmed=$rearmed") Log.i(TAG, "daily check: rearmed=$rearmed")
// rearmFromStorage arms it too, but only with an alarm stored.
NotifAlarm.schedule(context)
// Third net behind the exact check and boot: within a day, whatever
// dropped the other two, today's miss is still caught here.
StickRunner.run(context, "watchdog")
} }
private fun pendingIntent(context: Context): PendingIntent = private fun pendingIntent(context: Context): PendingIntent =

View File

@ -1,9 +0,0 @@
package com.kuhy.wake_alarm_sync
/**
* The app's only visible word, used as every notification channel's name.
*
* Matches `android:label` in AndroidManifest.xml and Dart's `kAppName`, so the
* notification settings name the app the way the launcher does.
*/
const val APP_NAME = "WakeAlarm"

View File

@ -3,7 +3,6 @@ package com.kuhy.wake_alarm_sync
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.util.Log
/** /**
* Re-arms the stored alarm after a reboot. * Re-arms the stored alarm after a reboot.
@ -14,28 +13,10 @@ import android.util.Log
class BootReceiver : BroadcastReceiver() { class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
val rearmed = AlarmScheduler.rearmFromStorage(context) AlarmScheduler.rearmFromStorage(context)
// A reboot mid-session must not end the session silently: the live
// leg's deadline is stored alongside the daily time. Not only after
// a reboot, either -- see restoreReRing for the launch-time replay.
val rering = AlarmScheduler.restoreReRing(context)
Log.i(TAG, "boot: rearmed=$rearmed rering=$rering")
EventLog.append(context, "boot", mapOf("rearmed" to rearmed, "rering" to rering))
// setInexactRepeating does not survive a reboot, so the daily check // setInexactRepeating does not survive a reboot, so the daily check
// has to be re-established here or it silently stops after the first // has to be re-established here or it silently stops after the first
// restart — exactly when a watchdog is most needed. // restart — exactly when a watchdog is most needed.
AlarmWatchdog.schedule(context) AlarmWatchdog.schedule(context)
// The 21:00 notifications check, also with no alarm stored.
NotifAlarm.schedule(context)
// A phone switched off before the alarm and back on after A + 15 has
// missed: this is the path that closes that hole (rearmFromStorage
// above has already armed the exact check for a phone back earlier).
StickRunner.run(context, "boot")
// Switched off mid-ring and back on the same day: the ring was killed.
Bypass.checkRingKilled(context)
}
private companion object {
const val TAG = "WakeAlarmBoot"
} }
} }

View File

@ -1,147 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import java.time.LocalDate
/** How the alarm was got around; [wire] is the `bypass` event's `cause`. */
enum class BypassCause(val wire: String) {
SUSPENDED("suspended"),
ADMIN_REMOVED("admin_removed"),
FSI_REVOKED("fsi_revoked"),
NOTIFICATIONS_OFF("notifications_off"),
RING_KILLED("ring_killed"),
}
/** The bypass rules as pure functions; [Bypass] gathers the inputs. */
object BypassRules {
/** A bypass counts on a ringing day while the ring or the morning session is live. */
fun counts(ringingDay: Boolean, ringLive: Boolean, sessionLive: Boolean): Boolean =
ringingDay && (ringLive || sessionLive)
/** The same cause recorded less than [windowMs] ago. */
fun isRepeat(last: Pair<String, Long>?, cause: String, now: Long, windowMs: Long): Boolean =
last != null && last.first == cause && now - last.second in 0 until windowMs
/** Today's ring fired, was never dismissed, and nothing is ringing now. */
fun ringKilled(firedToday: Boolean, dismissedToday: Boolean, ringing: Boolean): Boolean =
firedToday && !dismissedToday && !ringing
/**
* Whether this bypass's ring is a new session re-ring to name for it.
* One already sounding (a leg's deadline) stays that re-ring: one sound,
* one re-ring, its reason the one that started it.
*/
fun stampReRing(sessionLive: Boolean, ringing: Boolean): Boolean = sessionLive && !ringing
fun encodeStamp(cause: String, date: String): String = "$date|$cause"
/** The cause in [stored] if it was stamped on [today]; a stale one is dropped. */
fun takeStamp(stored: String?, today: String): String? {
val parts = stored?.split("|", limit = 2) ?: return null
return if (parts.size == 2 && parts[0] == today) parts[1] else null
}
}
/**
* Records a bypass of the alarm: the app paused from the launcher
* ("Wstrzymaj aplikację", 2026-11-20 and 11-22), its device admin removed,
* notifications or the full-screen intent switched off, or the ring killed.
*
* A bypass is a miss on any ringing day ([StickCheck]), so it locks the phone
* down through the next day and stacks the streak. It is published at once
* (the `bypass` phone event), so the PC rings until a fresh dismiss, and the
* phone rings again: the morning goes on as if the bypass never happened,
* one re-ring richer when a session was live.
*/
object Bypass {
private const val TAG = "WakeAlarmBypass"
// One launch runs the checks from MainActivity and then AlarmActivity
// (emulator, 2026-11-22: two events, two publishes for one revoke).
private const val REPEAT_WINDOW_MS = 60_000L
private var lastRecorded: Pair<String, Long>? = null
/** Records [cause] if it counts today; returns whether it did. */
@Synchronized
fun record(context: Context, cause: BypassCause): Boolean {
val today = LocalDate.now()
val ringLive = RingWatch.firedToday(context) && !RingWatch.dismissedOn(context, today)
val sessionLive = SessionNotice.isLiveToday(context)
if (!BypassRules.counts(ringingDay(context, today), ringLive, sessionLive)) {
Log.i(TAG, "${cause.wire}: no ring or session live; not a bypass")
EventLog.append(context, "bypass_ignored", mapOf("cause" to cause.wire))
return false
}
val now = System.currentTimeMillis()
if (BypassRules.isRepeat(lastRecorded, cause.wire, now, REPEAT_WINDOW_MS)) {
Log.i(TAG, "bypass: ${cause.wire} again within a minute; already recorded")
return true
}
lastRecorded = cause.wire to now
Log.w(TAG, "bypass: ${cause.wire}")
RingWatch.markBypass(context, today)
EventLog.append(
context,
"bypass",
mapOf("cause" to cause.wire, "date" to today.toString(), "session" to sessionLive),
)
if (cause == BypassCause.SUSPENDED) WorkdayStick.sendUnsuspend(context)
StickRunner.run(context, "bypass")
if (BypassRules.stampReRing(sessionLive, AlarmService.running)) {
BypassReRing.stamp(context, cause.wire, today.toString())
}
ringAgain(context)
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
return true
}
/**
* Every launch, from either activity: the launcher restores whichever
* one was on top (the ring or the session screen), so checking only in
* MainActivity missed a revoke made mid-morning (emulator, 2026-11-22).
*/
fun checkOnLaunch(context: Context) {
checkRingKilled(context)
checkPermissions(context)
}
/** Checks the permissions the ring needs; a revoked one on a live morning is a bypass. */
fun checkPermissions(context: Context) {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (NotifState.off(context)) {
record(context, BypassCause.NOTIFICATIONS_OFF)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
!manager.canUseFullScreenIntent()
) {
record(context, BypassCause.FSI_REVOKED)
}
}
/** On a launch or boot: today's ring fired, undismissed, and is not ringing. */
fun checkRingKilled(context: Context) {
val killed = BypassRules.ringKilled(
firedToday = RingWatch.firedToday(context),
dismissedToday = RingWatch.dismissedOn(context, LocalDate.now()),
ringing = AlarmService.running,
)
if (killed) record(context, BypassCause.RING_KILLED)
}
/** Starts the ring again; a refused start (still suspended) waits for the unsuspend. */
fun ringAgain(context: Context) {
try {
AlarmService.start(context)
} catch (e: RuntimeException) {
Log.w(TAG, "ring not restarted yet: $e")
}
}
private fun ringingDay(context: Context, day: LocalDate): Boolean =
AlarmScheduler.storedAlarm(context) != null &&
!FreeDays.isFree(context, day) &&
!SickDays.isSick(context, day) &&
RingWatch.skippedOn(context, day) == null
}

View File

@ -1,35 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import java.time.LocalDate
/**
* The cause of a bypass that restarted the ring during a live morning
* session, handed to Dart once (`takeBypassReRing`) so the session records
* that re-ring as `bypass:<cause>` rather than the leg's deadline.
*
* Dated, so a session that ends without a dismiss cannot leak it into
* tomorrow's first re-ring.
*/
object BypassReRing {
private const val PREFS = "wake_alarm_bypass_rering"
private const val KEY = "stamp"
fun stamp(context: Context, cause: String, date: String) {
prefs(context).edit().putString(KEY, BypassRules.encodeStamp(cause, date)).commit()
}
/** The stamped cause, left in place: every screen ticking on this ring sees it. */
fun peek(context: Context): String? =
BypassRules.takeStamp(prefs(context).getString(KEY, null), LocalDate.now().toString())
/** The stamped cause, cleared: called once, when the re-ring is recorded. */
fun take(context: Context): String? {
val stored = prefs(context).getString(KEY, null) ?: return null
prefs(context).edit().remove(KEY).commit()
return BypassRules.takeStamp(stored, LocalDate.now().toString())
}
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}

View File

@ -1,51 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.app.admin.DeviceAdminReceiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import java.time.LocalDate
/**
* The app's own device admin. An active admin cannot be paused
* ("Wstrzymaj aplikację"): Android refuses to suspend it. Deactivating it is
* possible in Settings and no one can stop that, so it is a bypass instead.
* Activated over adb (`dpm set-active-admin`), never by a tap.
*/
class WakeAdminReceiver : DeviceAdminReceiver() {
override fun onDisabled(context: Context, intent: Intent) {
Bypass.record(context, BypassCause.ADMIN_REMOVED)
}
}
/**
* `MY_PACKAGE_SUSPENDED` / `UNSUSPENDED`, sent by the system to this app
* itself. Suspended: record the bypass and ask focus-owner to lift it.
* Unsuspended: when today's bypass is live, ring again (the start may have
* been refused while suspended).
*/
class SuspendReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_MY_PACKAGE_SUSPENDED -> {
Log.w(TAG, "suspended")
Bypass.record(context, BypassCause.SUSPENDED)
}
Intent.ACTION_MY_PACKAGE_UNSUSPENDED -> {
Log.i(TAG, "unsuspended")
EventLog.append(context, "unsuspended")
if (RingWatch.bypassOn(context, LocalDate.now())) {
if (!AlarmService.running) Bypass.ringAgain(context)
// Again now the app runs normally: the push made while
// suspended may not have gone out.
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
}
}
}
}
private companion object {
const val TAG = "WakeAlarmSuspend"
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,31 +20,9 @@ class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
// A ring that fired, went undismissed and is not sounding was killed
// (force stop, a pause that got through): a bypass, which rings again.
Bypass.checkOnLaunch(this)
if (resumeMorning()) return
requestAlarmPermissions() requestAlarmPermissions()
} }
/**
* Steps aside into [AlarmActivity] while the morning is live: a ring is
* sounding, or today's session is still on a leg.
*
* Decided here, natively, before any Dart runs: the home screen must
* never come up mid-session (a home gesture used to be a way out with
* no way back, 2026-09-17), and the permission prompt above must never
* appear over a ring. Checked on resume as well as create -- this
* activity is `singleTop`, and a warm instance brought back from the
* launcher never re-runs onCreate.
*/
private fun resumeMorning(): Boolean {
if (!AlarmService.running && !SessionNotice.isLiveToday(this)) return false
startActivity(SessionNotice.resumeIntent(this))
finishAndRemoveTask()
return true
}
/** /**
* Asks for the two runtime permissions the alarm cannot work without. * Asks for the two runtime permissions the alarm cannot work without.
* *
@ -57,18 +35,11 @@ class MainActivity : FlutterActivity() {
* without it, so the steps fallback would report "sensor unavailable" * without it, so the steps fallback would report "sensor unavailable"
* forever. That matters because a room proof that can never be satisfied * forever. That matters because a room proof that can never be satisfied
* makes the alarm undismissable, not merely degraded. * makes the alarm undismissable, not merely degraded.
*
* ACCESS_FINE_LOCATION (API 23+): without it the connected Wi-Fi's BSSID
* comes back redacted and every provider is silent, so HomePresence can
* never answer. Unreadable means away, so a missing grant would drop the
* strict tag stages at home too. This is the ONLY place it is asked for:
* a permission dialog must never appear over a ringing alarm.
*/ */
private fun requestAlarmPermissions() { private fun requestAlarmPermissions() {
val wanted = arrayOf( val wanted = arrayOf(
Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.ACTIVITY_RECOGNITION, Manifest.permission.ACTIVITY_RECOGNITION,
Manifest.permission.ACCESS_FINE_LOCATION,
) )
val missing = wanted.filter { val missing = wanted.filter {
ContextCompat.checkSelfPermission(this, it) != ContextCompat.checkSelfPermission(this, it) !=
@ -136,7 +107,6 @@ class MainActivity : FlutterActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
if (resumeMorning()) return
if (registeringTag) alarmChannel?.let { NfcReader.start(this, it) } if (registeringTag) alarmChannel?.let { NfcReader.start(this, it) }
} }

View File

@ -1,99 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.time.LocalDateTime
import java.time.ZoneId
/**
* The exact daily alarm at [NotifRules.EVENING] (21:00) that runs
* [NotifState.report] (trigger `evening`), so the PC can ring while the
* notifications are still off and there is time to fix them before sleeping.
*
* Same shape as [PoolSyncAlarm]: setExactAndAllowWhileIdle (never an
* alarm-clock entry, which would show as the "next alarm"), inexact when
* exact alarms are refused, its own receiver and request code
* ([REQUEST_CODE]), never [AlarmReceiver], which would ring.
*
* Armed from [AlarmScheduler.schedule] (every arm path: launch, dismiss,
* skip), from [BootReceiver] and from the watchdog, and re-armed by its own
* receiver. Always the next future 21:00 ([NotifRules.nextEvening]), so a
* re-arm never restores an instant that has passed.
*/
object NotifAlarm {
private const val REQUEST_CODE = 1007
private const val TAG = "WakeAlarmNotifAlarm"
fun schedule(context: Context) {
val at = NotifRules.nextEvening(LocalDateTime.now())
val millis = at.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
Log.i(TAG, "notifications check armed for $at via ${arm(context, millis)}")
}
/** Arms [millis], exactly when permitted; returns which API did it. */
private fun arm(context: Context, millis: Long): String {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val exactAllowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
manager.canScheduleExactAlarms()
if (exactAllowed) {
try {
manager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
millis,
pendingIntent(context),
)
return "setExactAndAllowWhileIdle"
} catch (e: SecurityException) {
Log.w(TAG, "exact alarm refused; arming inexact", e)
}
}
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, millis, pendingIntent(context))
return "setAndAllowWhileIdle"
}
/** Holds [receiver]'s broadcast of [intent] open for [NotifRules.holdMs], then lets it go. */
fun hold(receiver: BroadcastReceiver, intent: Intent) {
val foreground = (intent.flags and Intent.FLAG_RECEIVER_FOREGROUND) != 0
val pending = receiver.goAsync()
Handler(Looper.getMainLooper())
.postDelayed({ pending.finish() }, NotifRules.holdMs(foreground))
}
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, NotifCheckReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Receives [NotifAlarm]: re-arms tomorrow's first, so a crash below cannot end the chain. */
class NotifCheckReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
NotifAlarm.schedule(context)
NotifAlarm.hold(this, intent)
NotifState.report(context, "evening")
}
}
/**
* The app's notifications, or the ring channel, blocked or unblocked in
* Settings. The system sends both to this app alone; switching them back on
* publishes `enabled=true` at once, which stops the PC's evening ring.
*/
class NotifBlockReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val channel = intent.getStringExtra(NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID)
val trigger = NotifRules.trigger(intent.action, channel) ?: return
NotifAlarm.hold(this, intent)
NotifState.report(context, trigger)
}
}

View File

@ -1,77 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.app.NotificationManager
import android.content.Context
import android.util.Log
import java.time.LocalDateTime
import java.time.LocalTime
/** The notifications check's rules as pure functions; [NotifState] gathers the inputs. */
object NotifRules {
/** When the evening check runs: early enough to fix it before sleeping. */
val EVENING: LocalTime = LocalTime.of(21, 0)
/**
* Off when the app's notifications are blocked or the ring channel is set
* to none. A channel not created yet ([ringImportance] null) is not a block.
*/
fun off(appEnabled: Boolean, ringImportance: Int?): Boolean =
!appEnabled || ringImportance == NotificationManager.IMPORTANCE_NONE
/** The next [EVENING] strictly after [now]: never one that has passed. */
fun nextEvening(now: LocalDateTime): LocalDateTime {
val tonight = now.toLocalDate().atTime(EVENING)
return if (tonight.isAfter(now)) tonight else tonight.plusDays(1)
}
/**
* How long a receiver holds its broadcast open after starting the push:
* a receiver that returns lets Android freeze the headless Dart engine
* mid-request (see [PoolSyncReceiver]). A foreground broadcast (the
* block-state ones are sent that way) has a 10 s budget, a background
* one 60 s; overrunning either is an ANR that kills the push.
*/
fun holdMs(foreground: Boolean): Long = if (foreground) 8_000L else 25_000L
/** The `notifications` event's data. */
fun eventData(enabled: Boolean, trigger: String): Map<String, Any?> =
mapOf("enabled" to enabled, "trigger" to trigger)
/** The event trigger for a block-state broadcast, or null when it is not about the ring. */
fun trigger(action: String?, channelId: String?): String? = when (action) {
NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED -> "app_block"
NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED ->
if (channelId == NotifState.RING_CHANNEL_ID) "channel_block" else null
else -> null
}
}
/**
* Whether the ring can show at all: "All WakeAlarm notifications" switched
* off, or the ring channel blocked, silences it, and no device policy can
* lock that switch (2026-11-22).
*
* Two readers: [Bypass.checkPermissions] at ring time (a bypass), and
* [report] at 21:00 ([NotifAlarm]) and whenever the switch moves
* ([NotifBlockReceiver]), which logs a `notifications` event and pushes it
* at once so the PC rings in the evening while it is still off.
*/
object NotifState {
const val RING_CHANNEL_ID = "wake_alarm_ring"
private const val TAG = "WakeAlarmNotif"
/** Whether notifications that the ring needs are switched off now. */
fun off(context: Context): Boolean {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = manager.getNotificationChannel(RING_CHANNEL_ID)
return NotifRules.off(manager.areNotificationsEnabled(), channel?.importance)
}
/** Logs the state as a `notifications` event and publishes it now. Main thread. */
fun report(context: Context, trigger: String) {
val enabled = !off(context)
Log.i(TAG, "notifications enabled=$enabled ($trigger)")
EventLog.append(context, "notifications", NotifRules.eventData(enabled, trigger))
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,97 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.util.Calendar
import java.util.Locale
/**
* Tracks, natively, whether today's ring was ever dismissed.
*
* The dismiss gate (tag1 -> steps -> tag2 -> challenges) lives in Dart, but a
* phone powered off before touching any of it never runs Dart at all that
* morning -- there is no session, no store, nothing to ask. Two dates, set
* from opposite ends of the ring, are enough to answer "was this abandoned"
* with no engine required:
*
* - [markFired] -- called from [AlarmReceiver], the instant a *fresh*
* (non-re-ring) alarm fires. This runs well before a poweroff mid-ring
* could ever prevent it -- setAlarmClock has already woken the CPU.
* - [markDismissed] -- called from Dart over the alarm channel, the instant
* the initial dismiss gate actually completes (`session_handoff.dart`'s
* `afterDismiss`).
*
* The stick ([StickCheck]) reads only [dismissedOn]. It used to ask "did a
* ring fire and go undismissed", which needs the *fired* date -- and a phone
* switched off before the alarm never fires, so that escaped everything.
* The fired date stays as evidence for whoever debugs a morning.
*/
object RingWatch {
private const val PREFS = "wake_alarm_ring_watch"
private const val KEY_FIRED_DATE = "fired_date"
private const val KEY_DISMISSED_DATE = "dismissed_date"
private const val KEY_DISMISSED_DATES = "dismissed_dates"
private const val KEY_SKIPPED_PREFIX = "skipped_dates_"
private const val KEY_BYPASS_DATES = "bypass_dates"
// Written only by builds that have [Bypass], next to KEY_FIRED_DATE. A
// ring fired by an older build (11-22: paused, never dismissed) must not
// read as a killed ring the first time the new build launches.
private const val KEY_WATCHED_FIRED_DATE = "watched_fired_date"
fun markFired(context: Context) {
prefs(context).edit()
.putString(KEY_FIRED_DATE, today())
.putString(KEY_WATCHED_FIRED_DATE, today())
.apply()
}
fun markDismissed(context: Context) {
prefs(context).edit().putString(KEY_DISMISSED_DATE, today()).apply()
DateHistory.add(prefs(context), KEY_DISMISSED_DATES, LocalDate.now())
}
/**
* Latches that today's ring stood down for [skip]; called from
* [AlarmReceiver]. The stick reads it back via [skippedOn], so clearing
* the mark later that day cannot make the silenced day a miss.
*/
fun markSkipped(context: Context, skip: RingSkip) {
DateHistory.add(prefs(context), KEY_SKIPPED_PREFIX + skip.wire, LocalDate.now())
}
/** Whether today's fresh ring fired under a build with [Bypass]; [Bypass] asks it. */
fun firedToday(context: Context): Boolean =
prefs(context).getString(KEY_WATCHED_FIRED_DATE, null) == today()
/** Latches a bypass ([Bypass]) on [day]; the stick reads it as a miss. */
fun markBypass(context: Context, day: LocalDate) {
DateHistory.add(prefs(context), KEY_BYPASS_DATES, day)
}
/** Whether a bypass was recorded on [day]. */
fun bypassOn(context: Context, day: LocalDate): Boolean =
DateHistory.contains(prefs(context), KEY_BYPASS_DATES, day)
/** Why the ring stood down on [day], or null when it was not skipped. */
fun skippedOn(context: Context, day: LocalDate): RingSkip? =
RingSkip.entries.firstOrNull {
DateHistory.contains(prefs(context), KEY_SKIPPED_PREFIX + it.wire, day)
}
/**
* Whether the dismiss gate completed on [day]; read by [StickRunner],
* which judges past days too. The single [KEY_DISMISSED_DATE] predates
* the history and still answers for its one day.
*/
fun dismissedOn(context: Context, day: LocalDate): Boolean =
DateHistory.contains(prefs(context), KEY_DISMISSED_DATES, day) ||
prefs(context).getString(KEY_DISMISSED_DATE, null) == day.toString()
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun today(): String =
SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Calendar.getInstance().time)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- No policies: the admin exists only so Android refuses to pause the app. -->
<device-admin>
<uses-policies />
</device-admin>

View File

@ -1,37 +0,0 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* A bypass during a live morning session re-rings it, and that re-ring is
* recorded as `bypass:<cause>`, not as the leg's deadline (2026-11-22).
*/
class BypassReRingTest {
@Test
fun `a bypass with the session live and nothing ringing stamps its re-ring`() {
assertTrue(BypassRules.stampReRing(sessionLive = true, ringing = false))
}
@Test
fun `a bypass while a deadline re-ring sounds keeps that one`() {
assertFalse(BypassRules.stampReRing(sessionLive = true, ringing = true))
}
@Test
fun `a bypass of the first ring is not a session re-ring`() {
assertFalse(BypassRules.stampReRing(sessionLive = false, ringing = false))
}
@Test
fun `a stamp is taken only on its own day`() {
val stamp = BypassRules.encodeStamp("fsi_revoked", "2026-11-22")
assertEquals("fsi_revoked", BypassRules.takeStamp(stamp, "2026-11-22"))
assertNull(BypassRules.takeStamp(stamp, "2026-11-23"))
assertNull(BypassRules.takeStamp(null, "2026-11-22"))
assertNull(BypassRules.takeStamp("garbage", "2026-11-22"))
}
}

View File

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

View File

@ -1,63 +0,0 @@
package com.kuhy.wake_alarm_sync
import android.app.NotificationManager
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.LocalDateTime
/** The 21:00 notifications check (2026-11-22): when it runs and what it says. */
class NotifRulesTest {
private fun at(day: Int, hour: Int, minute: Int = 0, second: Int = 0) =
LocalDateTime.of(2026, 11, day, hour, minute, second)
@Test
fun beforeNineTheCheckIsTonight() {
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 3)))
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 20, 59, 59)))
}
@Test
fun theInstantThatJustFiredIsNeverReturned() {
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 21)))
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 23, 59)))
}
@Test
fun offWhenTheAppIsBlockedOrTheRingChannelIsNone() {
assertTrue(NotifRules.off(appEnabled = false, ringImportance = null))
assertTrue(
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_NONE),
)
assertFalse(
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_HIGH),
)
// The channel is created at the first ring; none yet is not a block.
assertFalse(NotifRules.off(appEnabled = true, ringImportance = null))
}
@Test
fun theEventCarriesEnabledAndTheTrigger() {
assertEquals(
mapOf("enabled" to false, "trigger" to "evening"),
NotifRules.eventData(enabled = false, trigger = "evening"),
)
}
@Test
fun aForegroundBroadcastIsHeldInsideItsTenSeconds() {
assertTrue(NotifRules.holdMs(foreground = true) < 10_000L)
assertTrue(NotifRules.holdMs(foreground = false) in 10_000L until 60_000L)
}
@Test
fun onlyTheAppOrTheRingChannelCounts() {
val app = NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED
val channel = NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED
assertEquals("app_block", NotifRules.trigger(app, null))
assertEquals("channel_block", NotifRules.trigger(channel, NotifState.RING_CHANNEL_ID))
assertEquals(null, NotifRules.trigger(channel, "wake_alarm_session"))
assertEquals(null, NotifRules.trigger("android.intent.action.BOOT_COMPLETED", null))
}
}

View File

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

View File

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

View File

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

View File

@ -1,117 +0,0 @@
package com.kuhy.wake_alarm_sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
/**
* A bypass (the app paused, its admin removed, a permission revoked, the
* ring killed) is a miss on any ringing day, 2026-11-22.
*/
class StickCheckBypassTest {
// 2026-11-20 is a Friday, 22 a Sunday, 24 a Tuesday.
private val fri = LocalDate.of(2026, 11, 20)
private val sun = LocalDate.of(2026, 11, 22)
private val mon = sun.plusDays(1)
private val tue = sun.plusDays(2)
private fun inputs(
now: LocalDateTime,
bypass: Set<LocalDate> = emptySet(),
dismissed: Set<LocalDate> = emptySet(),
free: Set<LocalDate> = emptySet(),
sick: Set<LocalDate> = emptySet(),
state: StickState = StickState(),
checkedThrough: LocalDate? = null,
) = StickInputs(
now = now,
alarm = LocalTime.of(7, 30),
dismissedOn = { it in dismissed },
escapedOn = { false },
isFree = { it in free },
isSick = { it in sick },
state = state,
checkedThrough = checkedThrough,
bypassOn = { it in bypass },
)
@Test
fun aSundayBypassIsAMissLockingThroughMonday() {
val run = StickCheck.run(inputs(sun.atTime(7, 40), bypass = setOf(sun)))
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
assertEquals(StickState(streak = 1, lockedThrough = mon, lastMiss = sun), run.state)
assertEquals(mon, run.signalUntil)
}
@Test
fun aBypassCountsEvenBeforeTheGraceAndAfterADismiss() {
val run = StickCheck.run(
inputs(tue.atTime(7, 35), bypass = setOf(tue), dismissed = setOf(tue)),
)
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
}
@Test
fun aTuesdayMissAfterASundayBypassStacks() {
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
val run = StickCheck.run(
inputs(
tue.atTime(9, 0),
bypass = setOf(sun),
state = afterSunday,
checkedThrough = mon,
),
)
assertEquals(StickVerdict.MISS, run.verdicts.last().verdict)
assertEquals(2, run.state.streak)
assertEquals(tue.plusDays(2), run.state.lockedThrough)
}
@Test
fun aLateFridayWithNoBypassChangesNothing() {
val run = StickCheck.run(inputs(fri.atTime(11, 0)))
assertEquals(StickVerdict.NOT_STICK_DAY, run.verdicts.single().verdict)
assertEquals(StickState(), run.state)
assertNull(run.signalUntil)
}
@Test
fun freeAndSickDaysStayNeutralEvenWithABypass() {
val free = StickCheck.run(inputs(sun.atTime(8, 0), bypass = setOf(sun), free = setOf(sun)))
assertEquals(StickVerdict.FREE_DAY, free.verdicts.single().verdict)
val sick = StickCheck.run(inputs(tue.atTime(8, 0), bypass = setOf(tue), sick = setOf(tue)))
assertEquals(StickVerdict.SICK_DAY, sick.verdicts.single().verdict)
assertEquals(StickState(), sick.state)
}
@Test
fun aBypassCountsOnlyOnARingingDayWithARingOrSessionLive() {
assertTrue(BypassRules.counts(ringingDay = true, ringLive = true, sessionLive = false))
assertTrue(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = true))
assertFalse(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = false))
assertFalse(BypassRules.counts(ringingDay = false, ringLive = true, sessionLive = true))
}
@Test
fun aRingIsKilledWhenItFiredUndismissedAndNothingRings() {
assertTrue(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = false))
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = true))
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = true, ringing = false))
assertFalse(BypassRules.ringKilled(firedToday = false, dismissedToday = false, ringing = false))
}
@Test
fun theSameCauseWithinAMinuteIsARepeat() {
val last = "fsi_revoked" to 1_000L
assertFalse(BypassRules.isRepeat(null, "fsi_revoked", 1_000L, 60_000L))
assertTrue(BypassRules.isRepeat(last, "fsi_revoked", 60_999L, 60_000L))
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 61_000L, 60_000L))
assertFalse(BypassRules.isRepeat(last, "suspended", 2_000L, 60_000L))
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 999L, 60_000L))
}
}

View File

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

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