Compare commits

...

2 Commits

Author SHA1 Message Date
87c50825f9 drop the banked extra-workout shutdown bonus (no new hours from 2026-W42; streak + early-bird kept)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
A 5+ workout week no longer banks (count - 4)h, and the every-4-week streak
milestone +1h is gone. The streak counter and the 09:00 early-bird extension
stay. The applying path is untouched, so 2026-W41's already-banked 2h keeps
applying through Sunday 2026-10-11; old weekly_shutdown_bonus_hours keys load
and are preserved as-is. The next-week status preview no longer promises
bonus hours.

Claude-Session: https://claude.ai/code/session_01WfVGhY8XcsQsC7qz9UU8xb

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 08:32:40 +02:00
2140ca5180 deps: earned_time 0.6.1 (tutor cutover; new-gate rungs spare the floor)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 08:24:48 +02:00
17 changed files with 203 additions and 125 deletions

View File

@ -134,7 +134,7 @@ repos:
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.0#subdirectory=earned_time
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.1#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
- mcp>=2,<3
- pydantic
@ -155,7 +155,7 @@ repos:
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.0#subdirectory=earned_time
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.1#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
- mcp>=2,<3
- pydantic

View File

@ -10,7 +10,7 @@ dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.0#subdirectory=earned_time",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.1#subdirectory=earned_time",
]
[project.scripts]

View File

@ -4,7 +4,7 @@ bandit==1.9.4
codespell==2.4.3
coverage==7.16.2
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.0#subdirectory=earned_time
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.6.1#subdirectory=earned_time
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.3.1#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.9.0#subdirectory=gatelock
mcp==2.3.0

View File

@ -2,12 +2,15 @@
Tracks:
- Consecutive weeks with 5+ workouts (streak counter).
- Banked shutdown-time bonus hours earned from extra workouts, applied
every day of the following week. This never reduces enforcement (unlike
a banked "skip a workout" credit would) — it only grants extra comfort
time on top of a floor you still have to earn each day.
- ISO weeks in which the early-bird window is extended to 09:00.
A 5+ workout week no longer banks shutdown-time hours for the following week
(dropped 2026-10-10; 2026-W41 was the last week to receive any). The
``weekly_shutdown_bonus_hours`` map is still *read* by
:func:`weekly_shutdown_bonus_hours`, so hours already banked for the current
week keep applying, and ``scripts/restore_and_bonus.py`` can still bank a
one-off compensation into it — but the week transition never writes it.
State is persisted in ``extra_benefits_state.json`` next to this file.
"""
@ -25,8 +28,7 @@ if TYPE_CHECKING:
_logger = logging.getLogger(__name__)
_MILESTONE_INTERVAL = 4 # every 4-week streak → +1h extra shutdown bonus
_BONUS_THRESHOLD = 5 # workouts/week required to earn extra rewards
_BONUS_THRESHOLD = 5 # workouts/week required to extend the streak + early-bird
def _load_state(state_file: Path) -> dict[str, Any]:
@ -39,7 +41,7 @@ def _load_state(state_file: Path) -> dict[str, Any]:
except (OSError, json.JSONDecodeError) as exc:
_logger.warning(
"Could not read extra-benefits state from %s: %s — starting from "
"empty state, so the workout streak and any banked bonus hours are "
"empty state, so the workout streak and early-bird extension are "
"lost for this run",
state_file,
exc,
@ -62,32 +64,13 @@ def _current_iso_week(now: datetime) -> str:
return f"{year}-W{week:02d}"
def preview_bonus_if_week_ended_now(
current_week_count: int, current_streak: int
) -> tuple[int, int]:
"""(would_be_new_streak, would_be_bonus_hours) if the ISO week ended now.
Pure extraction of ``process_week_transition``'s threshold math — no file
I/O, safe to call from a read-only status view for a "next week preview."
"""
if current_week_count < _BONUS_THRESHOLD:
return 0, 0
streak = current_streak + 1
bonus_hours = current_week_count - 4
if streak % _MILESTONE_INTERVAL == 0:
bonus_hours += 1
return streak, bonus_hours
def process_week_transition(log_file: Path, state_file: Path) -> list[str]:
"""Process last week's results if we've entered a new ISO week.
Counts workouts from the previous ISO week. If count >= 5:
- Increments the consecutive-streak counter.
- Banks (count - 4) hours of shutdown-time bonus for the current week,
applied once per day on top of the daily base reset.
- Marks the *current* ISO week as having extended early-bird (09:00).
- Adds +1h more bonus every ``_MILESTONE_INTERVAL`` streak weeks.
Otherwise the streak resets to 0. No shutdown-time hours are banked.
Returns a list of human-readable reward strings (empty if no transition).
"""
@ -113,9 +96,6 @@ def process_week_transition(log_file: Path, state_file: Path) -> list[str]:
prev_week_count = count_weekly_workouts(log_file, today=prev_week_dt)
streak = int(state.get("consecutive_5plus_weeks", 0))
weekly_bonus_hours: dict[str, int] = dict(
state.get("weekly_shutdown_bonus_hours", {})
)
eb_weeks: list[str] = list(state.get("extended_early_bird_iso_weeks", []))
rewards: list[str] = []
@ -123,33 +103,30 @@ def process_week_transition(log_file: Path, state_file: Path) -> list[str]:
prev_week_str = f"{prev_year}-W{prev_week:02d}"
if prev_week_count >= _BONUS_THRESHOLD:
extra = prev_week_count - 4
streak, bonus_hours = preview_bonus_if_week_ended_now(prev_week_count, streak)
streak += 1
if current_week_str not in eb_weeks:
eb_weeks.append(current_week_str)
rewards.append(
f"{prev_week_count} workouts in {prev_week_str}! "
f"+{extra}h shutdown bonus this week, early-bird extended to 09:00"
f"{streak}-week streak, early-bird extended to 09:00 this week"
)
if streak % _MILESTONE_INTERVAL == 0:
rewards.append(f"{streak}-week streak milestone! +1h extra shutdown bonus")
weekly_bonus_hours[current_week_str] = bonus_hours
else:
if streak > 0:
rewards.append(f"Streak reset (was {streak} weeks of 5+ workouts)")
streak = 0
# Merge onto the loaded state rather than rebuilding it from these four
# keys: sibling fields written by the recovery scripts (e.g.
# ``shutdown_bonus_granted_for``, the guard that stops a compensation
# bonus being granted twice) live in this file too, and rebuilding would
# drop them at the next weekly rollover — silently re-arming a double-grant.
# Merge onto the loaded state rather than rebuilding it from these three
# keys: the legacy ``weekly_shutdown_bonus_hours`` map (still read, and
# still written by restore_and_bonus.py) and sibling fields written by the
# recovery scripts (e.g. ``shutdown_bonus_granted_for``, the guard that
# stops a compensation bonus being granted twice) live in this file too,
# and rebuilding would drop them at the next weekly rollover — losing this
# week's banked hours and silently re-arming a double-grant.
updated = dict(state)
updated.update(
{
"consecutive_5plus_weeks": streak,
"last_processed_iso_week": current_week_str,
"weekly_shutdown_bonus_hours": weekly_bonus_hours,
"extended_early_bird_iso_weeks": eb_weeks,
}
)
@ -165,7 +142,12 @@ def current_streak(state_file: Path) -> int:
def weekly_shutdown_bonus_hours(
state_file: Path, *, today: datetime | None = None
) -> int:
"""Return the banked shutdown-time bonus (hours) for the current ISO week."""
"""Return the banked shutdown-time bonus (hours) for the current ISO week.
The week transition stopped banking these after 2026-W41; what is left is
any hours already banked for this week, or a manual compensation written
by ``scripts/restore_and_bonus.py``.
"""
now = today if today is not None else datetime.now(tz=UTC).astimezone()
current_week_str = _current_iso_week(now)
bonus_hours: dict[str, int] = _load_state(state_file).get(

View File

@ -81,10 +81,10 @@ class PokeLocker(ScreenLocker):
Mirrors ``StartupChecksMixin._check_non_verify_exits``, not
``sync_now`` (which never resets): the week transition must be
processed BEFORE the reset, and the weekly bonus layered on only when
this call did the reset. If the poke stamped the day without them, the
locker's own reset later would be a no-op and that day's streak bonus
would be lost.
processed BEFORE the reset, and any banked weekly bonus layered on only
when this call did the reset. If the poke stamped the day without them,
the locker's own reset later would be a no-op and that day's banked
bonus would be lost.
"""
for reward in process_week_transition(self.log_file, EXTRA_BENEFITS_FILE):
_logger.info("Weekly reward: %s", reward)

View File

@ -104,13 +104,13 @@ class StartupChecksMixin(SyncMixin):
if self._is_scheduled_skip_today():
self._record_skip("scheduled_skip_day", "Today is a scheduled skip day.")
return
# Award streak / shutdown-bonus / EB-extension rewards from last week
# before the daily reset, so a Monday transition's bonus is recorded
# in time for _apply_weekly_shutdown_bonus below to see it.
# Award streak / EB-extension rewards from last week before the daily
# reset. The transition no longer banks shutdown hours; any already
# banked for this week are layered on by _apply_weekly_shutdown_bonus.
for reward_msg in process_week_transition(self.log_file, EXTRA_BENEFITS_FILE):
_logger.info("Weekly reward: %s", reward_msg)
# Reset shutdown config to base (19:00) at the start of each new day,
# then layer this week's earned bonus back on top of the fresh base.
# then layer this week's banked bonus (if any) back on the fresh base.
if reset_to_base_if_new_day(
SHUTDOWN_BASE_FILE,
self,

View File

@ -211,7 +211,6 @@ def gather_status(
shutdown=_shutdown_projection(
shutdown_config_file=shutdown_config_file,
extra_benefits_file=extra_benefits_file,
log_file=log_file,
today_local=today_local,
),
lock_explanation=lock_explanation,

View File

@ -14,15 +14,10 @@ from datetime import date, datetime, timedelta
from typing import TYPE_CHECKING
from screen_locker._earned import hhmm
from screen_locker._extra_benefits import (
current_streak,
preview_bonus_if_week_ended_now,
weekly_shutdown_bonus_hours,
)
from screen_locker._extra_benefits import weekly_shutdown_bonus_hours
from screen_locker._shutdown import read_shutdown_config
from screen_locker._shutdown_base import base_minutes
from screen_locker._status_types import ShutdownProjection, ShutdownProjectionDay
from screen_locker._weekly_check import count_weekly_workouts
if TYPE_CHECKING:
from pathlib import Path
@ -36,7 +31,8 @@ _RELAXED_DAY_EXPLANATION = (
)
_WEEKDAY_LABELS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_MON_WED_WEEKDAYS = frozenset({0, 1, 2})
# The weekly streak bonus is banked in whole hours.
# A banked weekly bonus (legacy, or a restore_and_bonus.py compensation) is in
# whole hours.
_MINUTES_PER_HOUR = 60
@ -62,10 +58,13 @@ def _shutdown_projection(
*,
shutdown_config_file: Path,
extra_benefits_file: Path,
log_file: Path,
today_local: datetime,
) -> ShutdownProjection:
"""Build the shutdown-time projection: tonight, rest of week, next week."""
"""Build the shutdown-time projection: tonight, rest of week, next week.
Next week is the plain per-day base: a 5+ workout week no longer banks
shutdown hours for the week after (only the early-bird extension).
"""
tonight = read_shutdown_config(shutdown_config_file)
bonus = (
weekly_shutdown_bonus_hours(extra_benefits_file, today=today_local)
@ -74,16 +73,7 @@ def _shutdown_projection(
monday = today_local.date() - timedelta(days=today_local.weekday())
rest_of_week = _week_rows(monday, bonus, speculative=False)
this_week_count = count_weekly_workouts(log_file, today=today_local)
streak = current_streak(extra_benefits_file)
_would_be_streak, would_be_bonus = preview_bonus_if_week_ended_now(
this_week_count, streak
)
next_week_preview = _week_rows(
monday + timedelta(weeks=1),
would_be_bonus * _MINUTES_PER_HOUR,
speculative=True,
)
next_week_preview = _week_rows(monday + timedelta(weeks=1), 0, speculative=True)
return ShutdownProjection(
tonight=tonight,

View File

@ -27,7 +27,7 @@ __all__ = ["SyncMixin"]
_logger = logging.getLogger(__name__)
# The weekly streak bonus is banked in whole hours; the schedule takes minutes.
# A banked weekly bonus is in whole hours; the schedule takes minutes.
_MINUTES_PER_HOUR = 60
@ -138,7 +138,12 @@ class SyncMixin:
self.workout_data = {}
def _apply_weekly_shutdown_bonus(self) -> None:
"""Layer this week's earned shutdown bonus back on top of the fresh base."""
"""Layer this week's banked shutdown bonus (if any) on the fresh base.
Week transitions stopped banking hours after 2026-W41; only hours
already banked for this week or a restore_and_bonus.py compensation
remain to apply.
"""
bonus = weekly_shutdown_bonus_hours(EXTRA_BENEFITS_FILE)
if bonus > 0 and self._adjust_shutdown_time_by(bonus * _MINUTES_PER_HOUR):
_logger.info("Weekly bonus: +%dh shutdown time this week.", bonus)

View File

@ -85,8 +85,10 @@ class TestProcessWeekTransition:
year, week, _ = now.isocalendar()
return f"{year}-W{week:02d}"
def test_awards_bonus_hours_for_5plus_workouts(self, tmp_path: Path) -> None:
"""5+ workouts in previous week: streak += 1, bonus hours += extra."""
def test_5plus_week_extends_streak_without_banking_hours(
self, tmp_path: Path
) -> None:
"""5+ workouts: streak += 1 and early-bird, but no shutdown hours banked."""
f = tmp_path / "state.json"
f.write_text(
json.dumps(
@ -103,21 +105,25 @@ class TestProcessWeekTransition:
):
rewards = process_week_transition(tmp_path / "log.json", f)
assert len(rewards) >= 1
assert "+2h shutdown bonus" in rewards[0]
assert len(rewards) == 1
assert rewards[0].startswith("6 workouts in ")
assert rewards[0].endswith(
"! 1-week streak, early-bird extended to 09:00 this week"
)
assert not any("shutdown bonus" in r for r in rewards)
state = json.loads(f.read_text())
assert state["consecutive_5plus_weeks"] == 1
assert state["weekly_shutdown_bonus_hours"][self._current_week_str()] == 2
assert state["weekly_shutdown_bonus_hours"] == {}
def test_awards_milestone_bonus_at_4_week_streak(self, tmp_path: Path) -> None:
"""Streak reaches multiple of 4: +1h extra shutdown bonus."""
def test_4_week_streak_banks_no_milestone_hour(self, tmp_path: Path) -> None:
"""Streak reaching 4 adds no +1h; a legacy bonus map is left untouched."""
f = tmp_path / "state.json"
f.write_text(
json.dumps(
{
"last_processed_iso_week": self._PAST_WEEK,
"consecutive_5plus_weeks": 3,
"weekly_shutdown_bonus_hours": {},
"weekly_shutdown_bonus_hours": {"2020-W52": 2},
"extended_early_bird_iso_weeks": [],
}
)
@ -127,10 +133,11 @@ class TestProcessWeekTransition:
):
rewards = process_week_transition(tmp_path / "log.json", f)
assert any("milestone" in r for r in rewards)
assert not any("milestone" in r or "+1h" in r for r in rewards)
assert "4-week streak" in rewards[0]
state = json.loads(f.read_text())
assert state["consecutive_5plus_weeks"] == 4
assert state["weekly_shutdown_bonus_hours"][self._current_week_str()] == 2
assert state["weekly_shutdown_bonus_hours"] == {"2020-W52": 2}
def test_marks_current_week_as_extended_early_bird(self, tmp_path: Path) -> None:
"""5+ workouts mark current ISO week as extended EB (line 91-92)."""

View File

@ -1,14 +1,15 @@
"""Tests for _extra_benefits module (streak, shutdown bonus, EB extension)."""
"""Tests for _extra_benefits (streak, legacy banked bonus, EB extension)."""
from __future__ import annotations
from datetime import UTC, datetime
from datetime import UTC, datetime, tzinfo
import json
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, ClassVar, Self
from unittest.mock import patch
from screen_locker._extra_benefits import (
has_extended_early_bird,
preview_bonus_if_week_ended_now,
process_week_transition,
weekly_shutdown_bonus_hours,
)
@ -40,24 +41,62 @@ class TestWeeklyShutdownBonusHours:
assert weekly_shutdown_bonus_hours(f) == 0
class TestPreviewBonusIfWeekEndedNow:
"""Tests for preview_bonus_if_week_ended_now — pure threshold math."""
class _FrozenDatetime(datetime):
"""``datetime`` whose ``now`` is pinned to Monday 2026-10-12 12:00 UTC."""
def test_below_threshold_returns_zero(self) -> None:
"""< 5 workouts: no streak increment, no bonus (line 67 branch)."""
assert preview_bonus_if_week_ended_now(3, current_streak=2) == (0, 0)
@classmethod
def now(cls, tz: tzinfo | None = None) -> Self:
"""The first Monday after the bonus was dropped (start of 2026-W42)."""
del tz
return cls(2026, 10, 12, 12, 0, tzinfo=UTC)
def test_at_threshold_awards_streak_and_bonus(self) -> None:
"""Exactly 5 workouts: streak+1, bonus = count - 4."""
assert preview_bonus_if_week_ended_now(5, current_streak=0) == (1, 1)
def test_above_threshold_awards_larger_bonus(self) -> None:
"""7 workouts: bonus = 7 - 4 = 3."""
assert preview_bonus_if_week_ended_now(7, current_streak=0) == (1, 3)
class TestBonusDroppedAtW42:
"""The 2026-W41 -> W42 rollover banks nothing; W41's hours stay readable."""
def test_milestone_streak_adds_extra_hour(self) -> None:
"""Streak reaching a multiple of 4 adds +1h on top of the base bonus."""
assert preview_bonus_if_week_ended_now(5, current_streak=3) == (4, 2)
_STATE: ClassVar[dict[str, object]] = {
"consecutive_5plus_weeks": 3,
"last_processed_iso_week": "2026-W41",
"weekly_shutdown_bonus_hours": {"2026-W40": 3, "2026-W41": 2},
"extended_early_bird_iso_weeks": ["2026-W41"],
"shutdown_bonus_granted_for": ["2026-08-24"],
}
def test_w42_transition_banks_nothing(self, tmp_path: Path) -> None:
"""5 workouts in W41 and a 4th streak week: early-bird yes, hours no."""
f = tmp_path / "state.json"
f.write_text(json.dumps(self._STATE))
with (
patch("screen_locker._extra_benefits.datetime", _FrozenDatetime),
patch(
"screen_locker._extra_benefits.count_weekly_workouts", return_value=5
),
):
rewards = process_week_transition(tmp_path / "log.json", f)
assert rewards == [
(
"5 workouts in 2026-W41! 4-week streak, "
"early-bird extended to 09:00 this week"
)
]
state = json.loads(f.read_text())
assert state == {
**self._STATE,
"consecutive_5plus_weeks": 4,
"last_processed_iso_week": "2026-W42",
"extended_early_bird_iso_weeks": ["2026-W41", "2026-W42"],
}
w42 = datetime(2026, 10, 12, 12, 0, tzinfo=UTC)
assert weekly_shutdown_bonus_hours(f, today=w42) == 0
assert has_extended_early_bird(f, today=w42) is True
def test_w41_banked_hours_still_apply_through_sunday(self, tmp_path: Path) -> None:
"""Hours banked before the drop keep applying for the rest of W41."""
f = tmp_path / "state.json"
f.write_text(json.dumps(self._STATE))
sunday = datetime(2026, 10, 11, 21, 0, tzinfo=UTC)
assert weekly_shutdown_bonus_hours(f, today=sunday) == 2
class TestHasExtendedEarlyBird:

View File

@ -199,8 +199,14 @@ class TestProjectionFollowsTheCut:
def base(day: date) -> int:
# From the sleep ladder (Sat 2026-10-10) the registry prices the
# day itself; before it, the cut from Tuesday holds.
# The registry in force that day (the tutor cutover switches it).
return earned_time.base_for(day, _earned.registry(day)).shutdown_minutes
# The registry in force that day (the tutor cutover switches it),
# and from today on its first credits: a never-paid tutor spares
# the floor (earned_time 0.6.1).
earners = _earned.registry(day)
starts = _earned.first_credits(earners, day)
return earned_time.base_for(
day, earners, first_credits=starts
).shutdown_minutes
week = [date(2026, 10, 5 + i) for i in range(7)]
assert [base(d) for d in week[1:4]] == [lowered] * 3

View File

@ -17,7 +17,7 @@ import earned_time
import pytest
from screen_locker._day import today_str
from screen_locker._earned import flat_earners, hhmm, registry
from screen_locker._earned import first_credits, gate_earners, hhmm, registry
from screen_locker._shutdown_base import (
_apply_flat_bonus,
apply_flat_bonuses_if_new,
@ -70,12 +70,14 @@ class TestBaseHour:
minus every earner's first unit, not 20:00 minus the cuts, so the day
is priced by the registry and only the "stays lowered" part is ours.
The Anki waiver (``ANKI_WAIVED_FROM``) raises that floor to 19:50, so
"lowered" means below the uncut 20:00, not at or below 19:00.
"lowered" means below the uncut 20:00, not at or below 19:00; a gate
that never paid out (the tutor) spares it (earned_time 0.6.1).
"""
later = date(2030, 1, 1)
expected = earned_time.base_for(later, registry(later)).shutdown_minutes
assert base_minutes(later) == expected
assert expected < base_minutes(date(2026, 9, 30))
starts = first_credits(registry(later), later)
base = earned_time.base_for(later, registry(later), first_credits=starts)
assert base_minutes(later) == base.shutdown_minutes
assert base.shutdown_minutes < base_minutes(date(2026, 9, 30))
def test_default_is_the_local_today(self) -> None:
assert base_minutes() == base_minutes(datetime.now().astimezone().date())
@ -163,7 +165,7 @@ class TestResetIncludesReading:
reset_to_base_if_new_day(tmp_path / "state.json", _mixin())
base = base_minutes()
later = "".join(
f" + 0h {e.label}" for e in flat_earners() if e.name not in _NAMED
f" + 0h {e.label}" for e in gate_earners() if e.name not in _NAMED
)
assert (
f"Daily base reset: {hhmm(base + 60)} (base {hhmm(base)} + 0h workout + "

View File

@ -94,3 +94,37 @@ class TestFormatSummaryLine:
snap = gather_status(**files, now=_FRIDAY_NOON_UTC)
assert "23:00 tonight" in format_summary_line(snap)
class TestNextWeekPreviewHasNoWeeklyBonus:
"""A 5+ workout week no longer promises next week a later shutdown."""
def test_five_workouts_and_a_streak_preview_the_plain_base(
self, tmp_path: Path
) -> None:
"""5 workouts + streak 3 (old rule: +2h next week) -> next week is base."""
files = _files(tmp_path)
files["log_file"].write_text(
json.dumps(
{
f"2024-01-0{day}": {"workout_data": {"type": "phone_verified"}}
for day in range(1, 6)
}
)
)
files["extra_benefits_file"].write_text(
json.dumps({"consecutive_5plus_weeks": 3})
)
with (
patch(
"screen_locker._status_data.has_workout_skip_today", return_value=False
),
patch(
"screen_locker._compliance_predicates.verify_entry_hmac",
return_value=True,
),
):
snap = gather_status(**files, now=_FRIDAY_NOON_UTC)
assert snap.week.counted_count == 5
assert [d.minutes for d in snap.shutdown.next_week_preview] == [20 * 60] * 7

View File

@ -1,9 +1,10 @@
"""The Automation tutor on a simulated cutover: penalty start and grace floor.
``earned_time.TUTOR_FROM`` is a far-future sentinel, so the cutover is
simulated on a fixed day: the registry's cutover (bound by value in
``_registry`` and ``_ladder``) and the tutor's own ``penalty_from`` move to
:data:`_CUTOVER`. Nothing is written outside the suite's redirected home.
``earned_time.TUTOR_FROM`` is 2026-10-10 since earned_time 0.6.1; the
fixture still pins the registry's cutover (bound by value in ``_registry`` and
``_ladder``) and the tutor's own ``penalty_from`` to :data:`_CUTOVER`, so the
suite does not move if a later release moves the cutover. Nothing is written
outside the suite's redirected home.
"""
from __future__ import annotations
@ -92,13 +93,25 @@ class TestNeverCredited:
assert wired.resolution.base.gaming_minutes == (
unwired.resolution.base.gaming_minutes + cut
)
# KNOWN GAP (earned_time 0.6.0): on the sleep ladder the shutdown
# floor is the ceiling minus every registered earner's full pay and
# never asks whether a penalty is in force, so a never-credited tutor
# still costs its shutdown minutes. A fix there flips this assertion.
def test_no_tutor_rung_off_the_shutdown_floor(self) -> None:
"""earned_time 0.6.1: a gate whose penalty has not started spares the floor.
Unwired, the tutor's penalty starts at ``penalty_from`` and its full
rung (13+13+12+12) comes off the ladder floor; wired, the never-paid
tutor costs no shutdown either, so the floor stays at 19:50.
"""
answers = {e.name: 0 for e in registry(_CUTOVER)}
starts = first_credits(registry(_CUTOVER), _CUTOVER)
wired = derive(DayInputs(_CUTOVER, answers, first_credits=starts))
unwired = derive(DayInputs(_CUTOVER, answers))
tutor = earned_time.AUTOMATION_TUTOR
rung = tutor.shutdown_for(tutor.max_units or 1, _CUTOVER)
assert rung == 50
assert wired.resolution.base.shutdown_minutes == (
unwired.resolution.base.shutdown_minutes
unwired.resolution.base.shutdown_minutes + rung
)
assert wired.resolution.base.shutdown_minutes == 19 * 60 + 50
@pytest.mark.usefixtures("tutor")

View File

@ -168,7 +168,7 @@ def main() -> int:
_report("today, real ledgers", target)
weekly = weekly_shutdown_bonus_hours(EXTRA_BENEFITS_FILE) * 60
_say(
f" + weekly streak bonus {weekly} min (layered after the reset, "
f" + banked weekly bonus {weekly} min (layered after the reset, "
f"absorbs the grace lift) -> expected config "
f"{hhmm(min(HELPER_CEILING, max(target.earned + weekly, target.minutes)))}"
)

View File

@ -12,8 +12,9 @@ Two separate corrections, in this order:
2. **Bank the bonus.** Written into ``extra_benefits_state.json`` under
``weekly_shutdown_bonus_hours[<ISO week>]`` -- the same key
``_extra_benefits.weekly_shutdown_bonus_hours()`` reads and
``_apply_weekly_shutdown_bonus`` applies every day of the week. This is the
mechanism the locker already uses for streak rewards; nothing bespoke.
``_apply_weekly_shutdown_bonus`` applies every day of the week. The locker
used this map for streak rewards until 2026-W41; since then this script is
its only writer.
Two bonus hours by default: one for each day a completed workout was not
counted (2026-06-12 and 2026-08-24).