Add the Tue/Wed/Thu workday stick: signal focus-owner and write tomorrow's penalty

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-09-23 21:20:58 +02:00
parent 92b7ae5d76
commit bfe8bab58a
17 changed files with 443 additions and 3 deletions

View File

@ -93,7 +93,35 @@ normal with a WARNING. Status paths never wait; tests pin the retry to 0.
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.
- No extra stick for a `failed` session beyond losing the carrot.
## 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

View File

@ -32,6 +32,9 @@
"not at home". -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Lets WorkdayStick reach focus-owner's signature-protected receiver;
both apps are signed with the same release key. -->
<uses-permission android:name="com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"/>
<application
android:label="wake_alarm_sync"
android:name="${applicationName}"

View File

@ -137,6 +137,14 @@ object AlarmChannel {
StepCounter.markRingStart(context)
result.success(null)
}
// The dismiss gate actually completed -- see RingWatch. Called
// once, from the same spot `afterDismiss` starts or resumes a
// session, regardless of outcome: reaching afterDismiss at all
// means the ring was dismissed.
"markRingDismissed" -> {
RingWatch.markDismissed(context)
result.success(null)
}
else -> result.notImplemented()
}
}

View File

@ -32,6 +32,10 @@ class AlarmReceiver : BroadcastReceiver() {
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)
}

View File

@ -54,6 +54,10 @@ object AlarmWatchdog {
fun verify(context: Context) {
val rearmed = AlarmScheduler.rearmFromStorage(context)
Log.i(TAG, "daily check: rearmed=$rearmed")
// Fallback net for an abandoned ring on a phone that never rebooted
// (BootReceiver already covers the poweroff case): within a day,
// whatever the reason, WorkdayStick catches it here too.
WorkdayStick.checkAndSignal(context)
}
private fun pendingIntent(context: Context): PendingIntent =

View File

@ -24,6 +24,9 @@ class BootReceiver : BroadcastReceiver() {
// has to be re-established here or it silently stops after the first
// restart — exactly when a watchdog is most needed.
AlarmWatchdog.schedule(context)
// The moment a phone powered off mid-ring comes back is exactly when
// an abandoned ring should be caught -- see WorkdayStick.
WorkdayStick.checkAndSignal(context)
}
private companion object {

View File

@ -0,0 +1,53 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import java.text.SimpleDateFormat
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`).
*
* [abandonedRingDate] is non-null exactly when a ring fired and nothing
* since has dismissed it -- checked from [BootReceiver] and the daily
* [WatchdogReceiver] tick, both of which run without a Flutter engine.
*/
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"
fun markFired(context: Context) {
prefs(context).edit().putString(KEY_FIRED_DATE, today()).apply()
}
fun markDismissed(context: Context) {
prefs(context).edit().putString(KEY_DISMISSED_DATE, today()).apply()
}
/** The date a ring fired but was never dismissed, or null. */
fun abandonedRingDate(context: Context): String? {
val fired = prefs(context).getString(KEY_FIRED_DATE, null) ?: return null
val dismissed = prefs(context).getString(KEY_DISMISSED_DATE, null)
return if (fired == dismissed) null else fired
}
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun today(): String =
SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Calendar.getInstance().time)
}

View File

@ -0,0 +1,48 @@
package com.kuhy.wake_alarm_sync
import android.content.Context
import android.content.Intent
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
/**
* Signals `focus-owner` to lock down distracting apps when a
* Tuesday/Wednesday/Thursday ring was abandoned -- see [RingWatch].
*
* 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 {
/** [Calendar.DAY_OF_WEEK] values for Tuesday/Wednesday/Thursday. */
private val STICK_DAYS =
setOf(Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY)
private const val ACTION_LOCKDOWN = "com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD"
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"
/** Checks for an abandoned stick-day ring and signals focus-owner. */
fun checkAndSignal(context: Context) {
val abandoned = RingWatch.abandonedRingDate(context) ?: return
if (!isStickDay(abandoned)) return
Log.i(TAG, "abandoned ring on $abandoned: signalling focus-owner lockdown")
context.sendBroadcast(
Intent(ACTION_LOCKDOWN).setPackage(FOCUS_OWNER_PACKAGE),
PERMISSION_SIGNAL,
)
}
private fun isStickDay(isoDate: String): Boolean {
val format = SimpleDateFormat("yyyy-MM-dd", Locale.US)
val parsed = runCatching { format.parse(isoDate) }.getOrNull() ?: return false
val calendar = Calendar.getInstance()
calendar.time = parsed
return calendar.get(Calendar.DAY_OF_WEEK) in STICK_DAYS
}
}

View File

@ -60,6 +60,17 @@ class AlarmScheduler {
/// Stops the ring and immediately re-arms for tomorrow.
Future<void> dismiss() => _channel.invokeMethod<void>('dismiss');
/// Tells the native side today's ring was actually dismissed.
///
/// Called once, from `SessionHandoff.afterDismiss` regardless of outcome —
/// reaching that call at all means the dismiss gate was satisfied. Native
/// pairs this with the fired timestamp it records independently
/// (`RingWatch`), so an abandoned ring (phone powered off before this
/// ever runs) can be told apart from a completed one with no Dart engine
/// required on the next boot.
Future<void> markRingDismissed() =>
_channel.invokeMethod<void>('markRingDismissed');
/// Whether the system will honour the full-screen intent.
///
/// False from API 34 unless granted. The caller must treat this as a hard

View File

@ -34,6 +34,10 @@ class SessionHandoff {
/// as it stands (failed, since it never finished) rather than resumed —
/// yesterday's clocks would re-ring the moment the screen came up.
Future<bool> afterDismiss({required bool away}) async {
// Reaching this call at all means the dismiss gate was satisfied --
// recorded before anything else so an interrupted await below still
// leaves the native side knowing the ring was answered.
await scheduler.markRingDismissed();
final now = _now();
final today = SessionRules.dateKey(now);
final current = await store.loadCurrent();

View File

@ -49,6 +49,11 @@ void main() {
expect(calls.single.method, 'dismiss');
});
test('markRingDismissed invokes markRingDismissed', () async {
await scheduler.markRingDismissed();
expect(calls.single.method, 'markRingDismissed');
});
test('rearm returns the platform result', () async {
reply = true;
expect(await scheduler.rearm(), isTrue);

View File

@ -13,14 +13,19 @@ void main() {
final now = DateTime(2026, 9, 17, 8, 4);
var hasNfc = true;
late List<String> calls;
setUp(() {
hasNfc = true;
calls = <String>[];
SharedPreferences.setMockInitialValues(<String, Object>{});
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel(AlarmScheduler.channelName),
(call) async => call.method == 'hasNfc' ? hasNfc : null,
(call) async {
calls.add(call.method);
return call.method == 'hasNfc' ? hasNfc : null;
},
);
});
@ -50,6 +55,14 @@ void main() {
expect(await SessionStore().loadCurrent(), isNull);
});
test(
'every dismiss tells native the ring was answered, even when away',
() async {
await handoff().afterDismiss(away: true);
expect(calls, contains('markRingDismissed'));
},
);
test('a dismiss during a live session is a re-ring', () async {
final store = SessionStore();
await store.save(

View File

@ -156,3 +156,13 @@ SESSION_COMPLETED_UNTIL: tuple[int, int] = (11, 0)
# dismissed (ring -> tags -> steps -> answers -> the start publish reaches the
# PC). A phone switched off at the alarm locks this long after it.
SESSION_NONE_GRACE: timedelta = timedelta(minutes=15)
# --- Workday stick (Tue/Wed/Thu miss -> tomorrow loses its leniency) ------
# The same weekdays screen-locker calls "relaxed" (_weekly_check.is_relaxed_day)
# and leetcode-guard prices as cheap (Pricing.doubled_days) -- both already go
# easy on exactly these three days, which is why a miss costs nothing today
# without this file. Python weekday(): Mon=0 ... Sun=6.
STICK_DAYS: frozenset[int] = frozenset({1, 2, 3}) # Tue, Wed, Thu
WORKDAY_PENALTY_FILE: Path = LOG_STATE_DIR / "workday_penalty.json"

View File

@ -40,6 +40,7 @@ from wake_alarm._session_payload import newest_session
from wake_alarm._session_policy import to_entry
from wake_alarm._sync import get_alarm
from wake_alarm._sync_transport import fetch_firebase_logs
from wake_alarm._workday_penalty import maybe_apply as _maybe_apply_workday_penalty
_logger = logging.getLogger(__name__)
@ -101,7 +102,10 @@ def refresh(now: datetime) -> dict[str, object] | None:
# than the baseline, so a later synced value never widens the grace.
alarm=min((alarm.hour, alarm.minute), (FALLBACK_ALARM_HOUR, 0)),
)
return entry if write_entry(entry) else None
if not write_entry(entry):
return None
_maybe_apply_workday_penalty(entry, now)
return entry
def describe(entry: dict[str, object], now: datetime) -> str:

View File

@ -0,0 +1,98 @@
"""Tue/Wed/Thu miss -> tomorrow loses its usual leniency.
The no-lock carrot (``_session_policy``) only motivates finishing the
morning when the PC is around to enjoy it -- true on a weekend, false on a
workday, since the user leaves for work regardless of whether the PC is
locked. On Tuesday/Wednesday/Thursday -- the same set screen-locker calls
"relaxed" (``_weekly_check.is_relaxed_day``) and leetcode-guard prices as
cheap (``Pricing.doubled_days``) -- a miss instead costs tomorrow's leniency
in both, so skipping is never free just because nobody is home to notice.
Distinct from ``morning_session.json``: that file always describes *today*
and is overwritten at the date rollover, so it cannot carry a marker forward
to tomorrow. This file's only field a consumer checks is ``penalty_date``:
today == penalty_date means "no leniency today," the same shape as
``morning_session.json``'s own ``exempt_until`` predicate.
"""
from __future__ import annotations
from datetime import date, datetime, timedelta
import json
import logging
import freedays
from gatelock.log_integrity import compute_entry_hmac
from wake_alarm._constants import STICK_DAYS, WORKDAY_PENALTY_FILE
from wake_alarm._session_policy import NONE_OUTCOME
_logger = logging.getLogger(__name__)
def is_stick_day(day: date) -> bool:
"""Tuesday/Wednesday/Thursday -- the same set already treated as lenient."""
return day.weekday() in STICK_DAYS
def is_workday_miss(entry: dict[str, object], now: datetime) -> bool:
"""Whether today's session entry is a genuine miss, not just late.
``failed`` is always a miss. ``none`` is only a miss once its own grace
has expired -- before that the morning could still start. A late
``completed`` (the walk happened, just after the carrot's cutoff) is
deliberately not a miss: the goal was waking up, and that happened.
"""
outcome = entry.get("outcome")
if outcome == "failed":
return True
if outcome != NONE_OUTCOME:
return False
until = entry.get("exempt_until")
if not isinstance(until, str):
return False
try:
return now >= datetime.fromisoformat(until)
except ValueError:
return False
def penalty_entry(*, today: date) -> dict[str, object]:
"""The unsigned body: tomorrow loses its leniency."""
return {
"penalty_date": (today + timedelta(days=1)).isoformat(),
"issued_date": today.isoformat(),
}
def write_penalty(entry: dict[str, object]) -> bool:
"""Sign and write ``entry``; False when the disk refused."""
signature = compute_entry_hmac(entry)
if signature is not None:
entry["hmac"] = signature
else:
_logger.warning("HMAC key unavailable — writing unsigned workday penalty")
try:
WORKDAY_PENALTY_FILE.parent.mkdir(parents=True, exist_ok=True)
WORKDAY_PENALTY_FILE.write_text(json.dumps(entry, indent=2))
except OSError as exc:
_logger.warning("Could not write %s: %s", WORKDAY_PENALTY_FILE, exc)
return False
return True
def maybe_apply(entry: dict[str, object], now: datetime) -> bool:
"""Write tomorrow's penalty when today is a missed stick-day; else no-op.
Best-effort: never raises, since the per-refresh caller must not fail on
this. A free day is never penalised even if unsynced state elsewhere
would otherwise have rung the alarm -- the pool is fail-closed the other
direction (a corrupt read is "not free"), which is exactly what is
wanted here too: an unreadable pool means no penalty, never a spurious
one.
"""
if freedays.is_free_day(now.date()) or not is_stick_day(now.date()):
return False
if not is_workday_miss(entry, now):
return False
return write_penalty(penalty_entry(today=now.date()))

View File

@ -41,6 +41,10 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
"wake_alarm._session.MORNING_SESSION_FILE",
tmp_path / "morning_session.json",
),
patch(
"wake_alarm._workday_penalty.WORKDAY_PENALTY_FILE",
tmp_path / "workday_penalty.json",
),
# The shared free-day pool lives under ~/.local/share, outside every
# path above. Without this, a real free day on the developer's
# machine would silence the alarm in every trigger test here.

View File

@ -0,0 +1,140 @@
"""Tue/Wed/Thu miss -> tomorrow's penalty file."""
from __future__ import annotations
from datetime import date, datetime
import json
from pathlib import Path
from unittest.mock import patch
from wake_alarm import _workday_penalty
from wake_alarm._workday_penalty import (
is_stick_day,
is_workday_miss,
maybe_apply,
penalty_entry,
write_penalty,
)
# 2026-09-22 is a Tuesday.
TUESDAY = date(2026, 9, 22)
WEDNESDAY = date(2026, 9, 23)
THURSDAY = date(2026, 9, 24)
MONDAY = date(2026, 9, 21)
FRIDAY = date(2026, 9, 25)
SATURDAY = date(2026, 9, 26)
SUNDAY = date(2026, 9, 27)
class TestIsStickDay:
def test_tuesday_wednesday_thursday_are_stick_days(self) -> None:
assert is_stick_day(TUESDAY)
assert is_stick_day(WEDNESDAY)
assert is_stick_day(THURSDAY)
def test_the_rest_of_the_week_is_not(self) -> None:
for day in (MONDAY, FRIDAY, SATURDAY, SUNDAY):
assert not is_stick_day(day)
class TestIsWorkdayMiss:
def test_failed_is_always_a_miss(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone()
assert is_workday_miss({"outcome": "failed"}, now)
def test_none_before_its_own_grace_is_not_a_miss_yet(self) -> None:
now = datetime(2026, 9, 22, 8, 0).astimezone()
entry = {
"outcome": "none",
"exempt_until": datetime(2026, 9, 22, 8, 15).astimezone().isoformat(),
}
assert not is_workday_miss(entry, now)
def test_none_past_its_own_grace_is_a_miss(self) -> None:
now = datetime(2026, 9, 22, 8, 16).astimezone()
entry = {
"outcome": "none",
"exempt_until": datetime(2026, 9, 22, 8, 15).astimezone().isoformat(),
}
assert is_workday_miss(entry, now)
def test_none_without_exempt_until_is_not_a_miss(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone()
assert not is_workday_miss({"outcome": "none"}, now)
def test_none_with_unreadable_exempt_until_is_not_a_miss(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone()
entry = {"outcome": "none", "exempt_until": "not-a-timestamp"}
assert not is_workday_miss(entry, now)
def test_late_completed_is_not_a_miss(self) -> None:
"""The walk happened, just after the carrot's cutoff -- not a skip."""
now = datetime(2026, 9, 22, 12, 0).astimezone()
assert not is_workday_miss({"outcome": "completed"}, now)
def test_in_progress_is_not_a_miss(self) -> None:
now = datetime(2026, 9, 22, 8, 5).astimezone()
assert not is_workday_miss({"outcome": "in_progress"}, now)
class TestPenaltyEntry:
def test_penalty_targets_tomorrow(self) -> None:
entry = penalty_entry(today=TUESDAY)
assert entry == {
"penalty_date": "2026-09-23",
"issued_date": "2026-09-22",
}
class TestWritePenalty:
def test_round_trip_is_signed(self) -> None:
entry = penalty_entry(today=TUESDAY)
assert write_penalty(entry)
assert "hmac" in entry
on_disk = json.loads(_workday_penalty.WORKDAY_PENALTY_FILE.read_text())
assert on_disk == entry
def test_unsigned_when_the_key_is_missing(self) -> None:
with patch("wake_alarm._workday_penalty.compute_entry_hmac", return_value=None):
entry = penalty_entry(today=TUESDAY)
assert write_penalty(entry)
assert "hmac" not in entry
def test_write_failure_is_false(self) -> None:
with patch.object(Path, "write_text", side_effect=OSError("ro")):
assert not write_penalty(penalty_entry(today=TUESDAY))
class TestMaybeApply:
def _entry(self, outcome: str = "failed") -> dict[str, object]:
return {"outcome": outcome}
def test_weekend_never_gets_a_penalty(self) -> None:
now = datetime(2026, 9, 26, 12, 0).astimezone() # Saturday
assert not maybe_apply(self._entry(), now)
assert not _workday_penalty.WORKDAY_PENALTY_FILE.exists()
def test_free_day_never_gets_a_penalty(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone() # Tuesday
with patch(
"wake_alarm._workday_penalty.freedays.is_free_day", return_value=True
):
assert not maybe_apply(self._entry(), now)
assert not _workday_penalty.WORKDAY_PENALTY_FILE.exists()
def test_a_completed_stick_day_gets_no_penalty(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone() # Tuesday
with patch(
"wake_alarm._workday_penalty.freedays.is_free_day", return_value=False
):
assert not maybe_apply(self._entry("completed"), now)
assert not _workday_penalty.WORKDAY_PENALTY_FILE.exists()
def test_a_missed_stick_day_writes_tomorrows_penalty(self) -> None:
now = datetime(2026, 9, 22, 12, 0).astimezone() # Tuesday
with patch(
"wake_alarm._workday_penalty.freedays.is_free_day", return_value=False
):
assert maybe_apply(self._entry("failed"), now)
on_disk = json.loads(_workday_penalty.WORKDAY_PENALTY_FILE.read_text())
assert on_disk["penalty_date"] == "2026-09-23"