Add every credit to tonight's shutdown

kuhy, 2026-11-18: shutdown 18:00, a run ending 19:58 must give 20:00
and the book's +1h 21:00 -- what the daily reset derives. The
late-credit rule (credit's own time + reward, 2026-10-17) made it
21:58 and 22:58. Unpaid gates now hold the PC behind the evening
chain until 23:00 instead, so the rule and its credit-time plumbing
go: _late_credit, the at= anchors, _done_at. The preview flags any
live-vs-derived MISMATCH again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWLoUxxSPf1m8KUVo8
This commit is contained in:
Krzysztof Rudnicki 2026-11-18 21:12:40 +01:00
parent 64c6105dbe
commit 67a54ba89d
23 changed files with 203 additions and 449 deletions

View File

@ -67,17 +67,19 @@ re-derives it on every live pass from the ledgers, and a sick-day credit only
raises to it (`_raise_on_sick_day`), never adds -- its row is already in the
sum. No lift is saved on a sick day.
## A shutdown never blocks submitting a finished task
## Every credit adds to tonight's shutdown, whenever it lands
A credit timed at or after tonight's shutdown moves tonight to
`min(23:00, the credit's OWN time + its reward)` (`_late_credit.late_tonight`):
only the 23:00 ceiling is hard. The anchor is the credit's own time (the run's
end via `_workout_ledger.entry_done_at`, the ledger row via
`_earned.first_credit_time`), never the sync time, so a late upload buys
nothing. It is live-only: the next day's reset re-derives from scratch. This
replaced the first-credit +60 grace floor (gone 2026-10-17); `_grace_floor`
keeps only `first_done_at`, `tonight_minutes` and the lift file, which
`plan_absorb` spends once if a stale one is left.
A credit adds its reward to tonight's config even after that shutdown passed:
18:00, a run ending 19:58 -> 20:00, the book's +1h -> 21:00, exactly what the
daily reset derives (`scripts/preview_shutdown.py` flags any MISMATCH). Unpaid
gates do not shut the PC down: the evening chain (book, tutor, LeetCode) holds
it behind their locks until 23:00, the only hard bound. The late-credit rule
(`min(23:00, credit's own time + reward)`, 2026-10-17) is gone since
2026-11-18 (kuhy): it turned that evening into 21:58 and 22:58. Trade-off kuhy
accepted: with no gate pending, a workout ending after its earned shutdown
buys only the time left before it. `_grace_floor` keeps `first_done_at`,
`tonight_minutes` and the lift file, which `plan_absorb` spends once if a
stale one is left.
Flat earners are read from their gate's ledger by `earned_time.done_today`
via `_earned.py`: HMAC-verified `credit` rows matched by the earner's own
@ -136,4 +138,4 @@ Dart tests, need the full suite: `scripts/full_gate.sh step <id>` once per id
`full-gate.timer` (22:00, loadavg guard) runs `full_gate.sh all`; a red result
(`$GIT_DIR/gate-full-status`) refuses every push until a full run is green.
Install the nightly: copy `full-gate.{service,timer}` to `~/.config/systemd/user/`
and `systemctl --user enable --now full-gate.timer` (not enabled yet).
and `systemctl --user enable --now full-gate.timer` (enabled on kuhy's PC).

View File

@ -17,8 +17,9 @@ pay of everything credited that day, capped at 23:00
raised to it by the next live pass (`_sick_floor`), and every later credit
that day raises it again.
A credit landing at or after tonight's shutdown is never lost: tonight
becomes `min(23:00, the credit's own time + its reward)` (`_late_credit`). `install.sh` migrates the old
A credit landing after tonight's shutdown adds its reward to that shutdown,
like any other (18:00 + 2h = 20:00 even for a run ending at 19:58); unpaid
evening gates hold the PC until 23:00 instead. `install.sh` migrates the old
`sick_history.json` dates into the pool once (`scripts/migrate_sick_history.py`).
A sick day may *keep* lockers (`sickdays add --keep workout`). A kept workout

View File

@ -44,10 +44,9 @@ def credit_body(
``before``/``after`` are the shutdown config around the credit. The delta
is what the workout earned: tonight's actual move, so a capped or rest-day
credit shows ``+0h``, but never more than ``reward``. A late credit moves
the shutdown from an hour already past to the run's end plus the reward
(:mod:`._late_credit`); that jump is not what the run earned
(18:00 -> 21:58 read "+3h58m" for a 2h run, 2026-11-18).
credit shows ``+0h``, but never more than ``reward``: the late-credit rule
(gone 2026-11-18) once moved 18:00 to 21:58 and the toast read "+3h58m"
for a 2h run.
"""
parts: list[str] = []
if after is None:

View File

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

View File

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

View File

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

View File

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

View File

@ -37,7 +37,6 @@ from screen_locker._day import today_str
from screen_locker._earned import (
counted_gate_earners,
earned_today,
first_credit_time,
first_credits,
first_minutes,
flat_earners,
@ -219,8 +218,7 @@ def _apply_flat_bonus(
return False
day = date.fromisoformat(today)
minutes = first_minutes(earner, day)
# Anchored on the credit's own row, so a late solve counts from its time.
if not mixin._adjust_shutdown_time_by(minutes, at=first_credit_time(earner, day)):
if not mixin._adjust_shutdown_time_by(minutes):
_logger.warning("%s bonus: failed to write shutdown config.", earner.label)
return False
state[stamp] = today

View File

@ -7,8 +7,8 @@
target = earned_time.resolve(answers, sick=...) # base + every earner, capped;
# sick: 20:00 + gaming pay
A late credit (``_late_credit``) is live-only: it restarts tonight from its own
time, and the next day's reset re-derives from scratch.
Every live credit adds its minutes to tonight's config, whenever it lands
(2026-11-18), so the live config equals this sum until the next reset.
A declared rest day answers the workout with at least one unit, i.e. its
first-unit bonus; a real workout on top of it earns only what a further unit

View File

@ -160,7 +160,7 @@ class StartupChecksMixin(SyncMixin):
# there is no banked "skip a workout" credit — that mechanic works
# against the goal of maximizing weekly workouts, so it was removed.
# A logged workout outranks every rung above, whatever their order.
# Then: once tonight's lockdown fired (a late credit may have lifted
# Then: once tonight's lockdown fired (a credit may have lifted
# it), never re-arm behind the workout gate the same evening.
if refuse_to_lock_over_logged_workout(
self.has_logged_today, self._record_skip

View File

@ -23,7 +23,6 @@ from screen_locker._day import today_str
from screen_locker._earned import extra_minutes, first_minutes
from screen_locker._rest_day import is_rest_day
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES, count_weekly_workouts
from screen_locker._workout_ledger import entry_done_at
if TYPE_CHECKING:
from pathlib import Path
@ -67,22 +66,12 @@ class WorkoutCreditMixin:
workout_data: dict[str, str]
log_file: Path
def _done_at(self, day: date) -> float | None:
"""When this workout ended; ``None`` (now) when it records no end.
``workout_data`` is the entry's inner dict, so it is wrapped as the
log entry ``entry_done_at`` reads. The run's own end anchors a late
workout, never the moment a sync applied it.
"""
return entry_done_at({"workout_data": self.workout_data}, day)
def _try_adjust_shutdown_for_workout(self) -> bool:
"""Try to adjust shutdown time later for actual workouts."""
workout_type = self.workout_data.get("type", "")
if workout_type not in COUNTED_WORKOUT_TYPES:
return False
day = date.fromisoformat(today_str())
adjusted = self._adjust_shutdown_time_later(at=self._done_at(day))
adjusted = self._adjust_shutdown_time_later()
if adjusted:
_logger.info("Shutdown time moved later as workout reward")
return adjusted
@ -152,7 +141,7 @@ class WorkoutCreditMixin:
slot is CreditSlot.FURTHER
and extra
and before
and self._adjust_shutdown_time_by(extra, at=self._done_at(day))
and self._adjust_shutdown_time_by(extra)
):
new_cfg = self._read_shutdown_config()
if new_cfg:

View File

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

View File

@ -29,7 +29,6 @@ from screen_locker.tests._gatelock_fixtures import (
dual_output,
)
from screen_locker.tests._isolated_state import ISOLATED_STATE
from screen_locker.tests._late_credit_fixtures import _untimed_credits_land_at_noon
from screen_locker.tests._locker_factories import (
_make_locker,
create_locker,
@ -57,7 +56,6 @@ __all__ = [
"_hermetic_gatelock",
"_make_locker",
"_mock_sys_exit",
"_untimed_credits_land_at_noon",
"create_locker",
"create_locker_early_bird",
"create_locker_relaxed_day",

View File

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

View File

@ -1,190 +0,0 @@
"""A credit that lands after tonight's shutdown restarts the clock from it.
kuhy, 2026-10-17: shutting down must never make a finished task impossible to
submit. A credit timed at or after tonight's shutdown moves it to the
credit's own time plus its reward (capped at the ceiling), so LeetCode done
at 19:00 after an 18:00 shutdown means 20:00. Anchored on the credit's time,
never the sync's: a workout done at 17:00 and uploaded at 19:00 is not late.
"""
from __future__ import annotations
from datetime import date, datetime
from typing import TYPE_CHECKING, Any
from unittest.mock import patch
import earned_time
import pytest
from screen_locker import _grace_floor, _late_credit, _shutdown, _sick_floor
from screen_locker._earned import first_minutes
from screen_locker._grace_floor import plan_absorb, save_lift
from screen_locker._shutdown import ShutdownMixin
from screen_locker.tests._sick_helpers import mark_sick
if TYPE_CHECKING:
from collections.abc import Iterator
# Captured before conftest pins it to noon for every test.
_real_now = _late_credit._now
_DAY = date(2026, 10, 17) # a Saturday: the Thu-Sun band is tonight's
_ISO = _DAY.isoformat()
def at(hhmm: str, day: date = _DAY) -> float:
"""Unix time of ``hhmm`` local on ``day``."""
hour, minute = (int(p) for p in hhmm.split(":"))
return datetime(day.year, day.month, day.day, hour, minute).astimezone().timestamp()
def host_workout_minutes() -> int:
"""The reward in minutes that the workout earner pays on the test day."""
return first_minutes(earned_time.WORKOUT, _DAY)
def m(hhmm: str) -> int:
"""Convert an HH:MM string into minutes after midnight."""
hour, minute = (int(p) for p in hhmm.split(":"))
return hour * 60 + minute
class Host(ShutdownMixin):
"""The real add paths over an in-memory config."""
def __init__(self, tonight: str, *, ok: bool = True) -> None:
self.config: tuple[int, int, int] = (m(tonight), m(tonight), 300)
self.ok = ok
def _read_shutdown_config(self) -> tuple[int, int, int] | None:
return self.config
def _write_shutdown_config(
self, mon_wed: int, thu_sun: int, morning_end: int, *, restore: bool = False
) -> bool:
assert restore
if self.ok:
self.config = (mon_wed, thu_sun, morning_end)
return self.ok
@property
def tonight(self) -> int:
"""Tonight's shutdown time in minutes (the Thu-Sun band)."""
return self.config[1]
@pytest.fixture(autouse=True)
def _on_the_day() -> Iterator[Any]:
with (
patch.object(_sick_floor, "today_str", return_value=_ISO),
patch.object(_grace_floor, "today_str", return_value=_ISO),
patch.object(_shutdown, "today_str", return_value=_ISO),
patch.object(_late_credit, "today_str", return_value=_ISO),
):
yield
class TestLateCredit:
"""Credits timed after tonight's shutdown restart the clock from their own time."""
def test_a_credit_before_the_shutdown_adds_as_before(self) -> None:
"""A credit before the shutdown simply adds its reward to tonight."""
host = Host("20:00")
assert host._adjust_shutdown_time_by(60, at=at("18:30")) is True
assert host.tonight == m("21:00")
def test_a_credit_after_the_shutdown_counts_from_its_own_time(self) -> None:
"""A late credit sets tonight to its own time plus the reward, in both bands."""
host = Host("18:00")
assert host._adjust_shutdown_time_by(60, at=at("19:00")) is True
assert host.tonight == m("20:00")
assert host.config[0] == m("20:00") # both bands, like the floors
def test_a_credit_exactly_at_the_shutdown_is_late(self) -> None:
"""The check script locks at ``now >= shutdown``."""
host = Host("19:00")
host._adjust_shutdown_time_by(60, at=at("19:00"))
assert host.tonight == m("20:00")
def test_capped_at_the_ceiling(self) -> None:
"""A late credit never pushes tonight past the 23:00 ceiling."""
host = Host("22:30")
host._adjust_shutdown_time_by(120, at=at("22:45"))
assert host.tonight == m("23:00")
def test_after_the_ceiling_nothing_moves_past_it(self) -> None:
"""A credit after the ceiling leaves tonight at 23:00."""
host = Host("23:00")
host._adjust_shutdown_time_by(60, at=at("23:10"))
assert host.tonight == m("23:00")
def test_a_late_upload_is_not_a_late_credit(self) -> None:
"""Done at 17:00, synced at 19:00: 18:00 + 2 h, not 19:00 + 2 h."""
host = Host("18:00")
assert host._adjust_shutdown_time_later(at=at("17:00")) is True
assert host.tonight == m("18:00") + host_workout_minutes()
def test_a_late_workout_counts_from_its_end(self) -> None:
"""A workout finishing after the shutdown counts from its end time."""
host = Host("18:00")
host._adjust_shutdown_time_later(at=at("19:00"))
assert host.tonight == min(m("23:00"), m("19:00") + host_workout_minutes())
def test_a_credit_timed_on_another_day_is_never_late(self) -> None:
"""A credit stamped on a different day is treated as not late."""
host = Host("18:00")
host._adjust_shutdown_time_by(60, at=at("19:00", date(2026, 10, 16)))
assert host.tonight == m("19:00")
def test_no_time_means_now(self) -> None:
"""Without an explicit time the credit is anchored on the current time."""
host = Host("18:00")
with patch.object(_late_credit, "_now", return_value=at("19:30")):
host._adjust_shutdown_time_by(60)
assert host.tonight == m("20:30")
def test_now_is_the_wall_clock(self) -> None:
"""The default clock reads the real wall-clock time."""
with patch.object(_late_credit.time, "time", return_value=123.0):
assert _real_now() == 123.0
def test_a_late_credit_clears_the_lift(self) -> None:
"""Past the shutdown the floor is spent: nothing is left to absorb."""
save_lift(30)
host = Host("18:00")
host._adjust_shutdown_time_by(60, at=at("19:00"))
assert host.tonight == m("20:00")
assert plan_absorb(60) == (60, 0)
def test_a_failed_write_keeps_the_lift(self) -> None:
"""If writing the config fails the saved lift is kept."""
save_lift(30)
host = Host("18:00", ok=False)
assert host._adjust_shutdown_time_by(60, at=at("19:00")) is False
assert plan_absorb(0) == (0, 30)
def test_unreadable_config_fails(self) -> None:
"""An unreadable shutdown config makes the late adjustment fail."""
host = Host("18:00")
with patch.object(Host, "_read_shutdown_config", return_value=None):
assert host._adjust_shutdown_time_by(60, at=at("19:00")) is False
class TestLateOnASickDay:
"""Late-credit behaviour on a sick day, where the sick target is the floor."""
def test_late_after_the_sick_target(self) -> None:
"""A credit after the sick target counts from its own time."""
mark_sick(_DAY)
host = Host("20:00")
with patch.object(_sick_floor, "sick_target", return_value=m("20:00")):
assert host._adjust_shutdown_time_by(60, at=at("21:00")) is True
assert host.tonight == m("22:00")
def test_not_late_raises_to_the_target_only(self) -> None:
"""A not-late credit on a sick day only raises tonight to the sick target."""
mark_sick(_DAY)
host = Host("21:00")
with patch.object(_sick_floor, "sick_target", return_value=m("22:00")):
host._adjust_shutdown_time_by(60, at=at("15:00"))
assert host.tonight == m("22:00")

View File

@ -120,8 +120,8 @@ class TestUnlockScreenShutdownAdjustment:
locker.unlock_screen()
# Anchored on the workout's own end, so a late upload buys nothing.
locker._adjust_shutdown_time_later.assert_called_once_with(at=123.0)
# The reward adds to tonight's shutdown whenever the run ended.
locker._adjust_shutdown_time_later.assert_called_once_with()
def test_unlock_screen_skips_adjustment_for_sick_day(
self,

View File

@ -6,9 +6,10 @@ in ``earned_time.earners_for(day)`` is done to its full units (the tutor's
four blocks included) must shut down exactly at ``shutdown_ceiling_for(day)``
-- never short of it, and never past it. Checked through screen-locker's own
paths, not a re-implementation: the daily reset's :func:`derive`, and the live
pass (first workout, further workouts, flat gates, counted gate blocks, each
timed at ``first`` so a 22:30 one is a late credit) over :class:`ShutdownMixin`
with an in-memory config.
pass (first workout, further workouts, flat gates, counted gate blocks) over
:class:`ShutdownMixin` with an in-memory config. ``first`` only feeds the
reset's ``first_done_at``: since 2026-11-18 a credit adds to tonight's shutdown
whenever it lands, so the live pass has no clock.
Every gate maturity state is covered: ``first_credits`` omitted (0.5.0
``penalty_from``), empty (every earner on its ``confirmed_on``), never paid
@ -19,14 +20,13 @@ maturing (paid yesterday), mature, and a new tutor beside mature gates.
from __future__ import annotations
from datetime import date, datetime, time, timedelta
from functools import partial
from typing import TYPE_CHECKING, Any
from unittest.mock import patch
import earned_time
import pytest
from screen_locker import _gate_bonus, _grace_floor, _late_credit, _shutdown
from screen_locker import _gate_bonus, _grace_floor, _shutdown
from screen_locker._ceiling import HARD_CEILING_MINUTES, ceiling
from screen_locker._earned import extra_minutes, first_minutes, is_gate
from screen_locker._earned import registry as registry_for
@ -149,19 +149,16 @@ class _Host(ShutdownMixin):
def _live_pass(day: date, case: tuple[str, bool, int, str]) -> int:
"""Reset with nothing done, then every credit as the live pass applies it."""
_, rest, workouts, first = case
_, rest, workouts, _first = case
host = _Host(derive(_inputs(day, case, done=False)).minutes)
# Every credit lands at ``first`` (09:00 when "none"): at 22:30 they are
# late credits (_late_credit), which must still land on the ceiling.
when = _at(day, first) or _at(day, "09:00")
# A rest day's first unit is already in the reset; a real workout on it
# is a further unit (_workout_credit's rest_paid rule).
further = workouts if rest else workouts - 1
if not rest:
host._adjust_shutdown_time_later(at=when)
host._adjust_shutdown_time_later()
extra = extra_minutes(earned_time.WORKOUT, day)
for _ in range(further if extra else 0):
host._adjust_shutdown_time_by(extra, at=when)
host._adjust_shutdown_time_by(extra)
state: dict[str, Any] = {}
# One plain-function patch per day, not a MagicMock per unit: building
# ~5000 mocks was half of this file's runtime. ``answered`` is the ledger's
@ -170,13 +167,13 @@ def _live_pass(day: date, case: tuple[str, bool, int, str]) -> int:
with patch.object(_gate_bonus, "earned_units", lambda _e, _d: answered[0]):
for gate in (e for e in registry_for(day) if is_gate(e)):
if gate.kind == "flat":
host._adjust_shutdown_time_by(first_minutes(gate, day), at=when)
host._adjust_shutdown_time_by(first_minutes(gate, day))
continue
for units in range(1, (gate.max_units or 1) + 1):
answered[0] = units
apply_counted_bonus(
state,
partial(host._adjust_shutdown_time_by, at=when),
host._adjust_shutdown_time_by,
gate,
day.isoformat(),
)
@ -192,7 +189,6 @@ def frozen_day_fixture() -> Iterator[Callable[[date], Any]]:
return (
patch.multiple(_shutdown, today_str=lambda: iso, is_sick=lambda _d: False),
patch.multiple(_grace_floor, today_str=lambda: iso),
patch.multiple(_late_credit, today_str=lambda: iso),
)
return at_day
@ -210,8 +206,8 @@ def test_the_live_pass_lands_every_all_done_day_on_the_ceiling(
case = (maturity, rest, workouts, first)
misses = []
for day in _DAYS:
shutdown_patch, grace_patch, late_patch = frozen_day(day)
with shutdown_patch, grace_patch, late_patch:
shutdown_patch, grace_patch = frozen_day(day)
with shutdown_patch, grace_patch:
got = _live_pass(day, case)
_grace_floor.GRACE_STATE_FILE.unlink(missing_ok=True)
if got != ceiling(day):

View File

@ -92,7 +92,7 @@ class TestFlatBonuses:
state = tmp_path / "state.json"
mixin = _mixin()
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(60, at=None)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {"reading_bonus_date": today_str()}
@ -125,7 +125,7 @@ class TestANewlyRegisteredEarner:
mixin = _mixin()
apply_flat_bonuses_if_new(state, mixin)
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(60, at=None)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {"extra_bonus_date": today_str()}
def test_its_ledger_is_read_like_any_other(self, tmp_path: Path) -> None:
@ -134,7 +134,7 @@ class TestANewlyRegisteredEarner:
mixin = _mixin()
with signing_key(tmp_path):
apply_flat_bonuses_if_new(tmp_path / "state.json", mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(60, at=None)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
def test_a_penalised_earner_lowers_the_base_from_its_day(
self, monkeypatch: pytest.MonkeyPatch
@ -179,18 +179,6 @@ class TestRealLedgers:
"reading_bonus_date": today_str(),
}
def test_the_live_pass_hands_on_the_credit_s_own_time(self, tmp_path: Path) -> None:
"""A late credit counts from its ledger row, never the pass's clock."""
midnight = datetime.now(tz=UTC).astimezone().replace(hour=0, minute=0, second=0)
write_ledger(earned_time.LEETCODE, [credit(earned_time.LEETCODE, midnight)])
mixin = _mixin()
with signing_key(tmp_path), answering({"leetcode": True}):
apply_flat_bonuses_if_new(tmp_path / "state.json", mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(
_earned.first_minutes(earned_time.LEETCODE, midnight.date()),
at=float(int(midnight.timestamp())),
)
class TestProjectionFollowsTheCut:
"""Every projected row is priced on its own date, not on today's base."""

View File

@ -103,7 +103,7 @@ class TestLivePass:
mixin = _mixin()
assert apply_leetcode_bonus_if_new(state, mixin) is True
assert apply_leetcode_bonus_if_new(state, mixin) is False
mixin._adjust_shutdown_time_by.assert_called_once_with(60, at=None)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"leetcode_bonus_date": today_str(),

View File

@ -51,7 +51,7 @@ class TestReadingLivePass:
mixin = _mixin()
assert apply_reading_bonus_if_new(state, mixin) is True
assert apply_reading_bonus_if_new(state, mixin) is False
mixin._adjust_shutdown_time_by.assert_called_once_with(60, at=None)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"reading_bonus_date": today_str(),

View File

@ -54,7 +54,7 @@ class TestTarget:
assert not workout_units(0, rest_day=False)
def test_an_early_first_task_no_longer_lifts_the_sum(self) -> None:
"""The grace floor is gone (2026-10-17): late credits replace it."""
"""The grace floor is gone (2026-10-17): nothing lifts tonight above the sum."""
target = derive(
DayInputs(_DAY, {**_FLAT, "anki": True}, first_done=at("18:55"))
)

View File

@ -89,7 +89,7 @@ class SimShutdown(ShutdownMixin):
self.config = (*clamp, morning_end)
return True
def credit(self, name: str, day: date, at: float | None = None) -> None:
def credit(self, name: str, day: date) -> None:
"""One live pass: the earner's add (lift-absorbing), then the floors.
``sick`` is not an earner: it marks the (temporary) pool and runs the
@ -99,10 +99,10 @@ class SimShutdown(ShutdownMixin):
if name == SICK_STEP:
sick_pool(day, sick_day=True)
elif name == earned_time.WORKOUT.name:
self._adjust_shutdown_time_later(at=at)
self._adjust_shutdown_time_later()
else:
minutes = first_minutes(earned_time.earner(name), day)
self._adjust_shutdown_time_by(minutes, at=at)
self._adjust_shutdown_time_by(minutes)
self._apply_sick_floor()

View File

@ -5,7 +5,7 @@ READ-ONLY on the real system: it never runs the sudo helper, never writes
``/etc``, ``shutdown_base.json``, ``grace_floor.json``, ``rest_days.json``,
``log.json`` or the real workout ledger. Simulations run the real code paths
(TCX parsing + walk summing via the RunnerUp backfill, rest-day signing and
verification, ``_shutdown_target.derive``, the sick floor, late credits and the
verification, ``_shutdown_target.derive``, the sick floor and the
lift bookkeeping, a temporary ``sickdays`` pool) against a temporary
directory, with an in-memory shutdown config.
@ -33,7 +33,7 @@ import tempfile
import earned_time
from screen_locker import _earned, _grace_floor, _late_credit, _shutdown, _sick_floor
from screen_locker import _earned, _grace_floor, _shutdown, _sick_floor
from screen_locker._constants import SHUTDOWN_CONFIG_FILE
from screen_locker._day import today_str
from screen_locker._earned import hhmm
@ -116,22 +116,16 @@ def _simulate(args: argparse.Namespace, tmp: Path) -> None:
_report("simulated", target)
def hhmm_minutes(text: str) -> int:
"""``HH:MM`` as minutes after midnight."""
hour, minute = (int(p) for p in text.split(":"))
return hour * 60 + minute
def _sequence(args: argparse.Namespace, tmp: Path) -> None:
day = date.fromisoformat(args.day)
for module in (_grace_floor, _late_credit, _shutdown, _sick_floor):
for module in (_grace_floor, _shutdown, _sick_floor):
vars(module)["today_str"] = lambda: args.day
vars(module)["GRACE_STATE_FILE"] = tmp / "grace_floor.json"
use_temp_pool(tmp)
done = {e.name: False for e in _earned.flat_earners()}
sim = SimShutdown(derive(DayInputs(day, done)).minutes)
_say(f"[sequence] {day} start {hhmm(sim.config[0])} (nothing done, not sick)")
workouts, first, went_late = 0, None, False
workouts, first = 0, None
# The real target reads today's real ledgers; the sim's are ``done``.
vars(_sick_floor)["sick_target"] = lambda d, _log: (
derive(DayInputs(d, done, workouts, sick_day=True)).minutes
@ -144,19 +138,12 @@ def _sequence(args: argparse.Namespace, tmp: Path) -> None:
done[name] = True
if name != SICK_STEP:
first = min(first or stamp(day, at), stamp(day, at))
late = name != SICK_STEP and hhmm_minutes(at) >= sim.config[0]
sim.credit(name, day, stamp(day, at))
sim.credit(name, day)
want = derive(
DayInputs(day, done, workouts, first_done=first, sick_day=is_sick(day))
)
# A late credit is live-only, so from it on the derived sum is no judge.
went_late = went_late or late
if late:
verdict = " LATE: from its own time"
elif went_late:
verdict = " live, after a late credit"
else:
verdict = "" if sim.config[0] == want.minutes else " MISMATCH"
# Every credit adds to tonight (2026-11-18), so live must equal derived.
verdict = "" if sim.config[0] == want.minutes else " MISMATCH"
_say(
f" {name}@{at}: config {hhmm(sim.config[0])} "
f"(derived {hhmm(want.minutes)}{verdict})"