Pay flat bonuses by signed progress

earned_time 0.24 progress rows: the reset and sick floor pass
progress_map to resolve (workout left out, WorkoutCreditMixin owns
it); the live pass pays max(0, pay_now - applied) and stamps
<name>_bonus_minutes. A legacy <name>_bonus_date of today still
means the full bonus, so a mid-day deploy never pays twice. The
reset stamps minutes, never the date, so a partial stays open.
No progress row pays exactly as before; a credit pays in full.

Lands 5b6ac0b from the progress stack as this commit; its parent
4ed64b4 was already on main. Pins earned_time to the new tag
earned-time-v0.24.0 (utils c06f2da), in the manifests and the
pylint hook envs.

The preview keeps both sides: earners come from the day's registry
(main) and are priced through term_for with a progress row (stack).
_preview_sim.ROWS is the one row source for the live add and the
derivation; a new test pins a 1-of-2 review row on 2026-11-24 and
checks the preview pays term_for's share (10), not the flat 20.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 18:50:07 +01:00
parent a8c6177012
commit 5ba9e4b438
21 changed files with 783 additions and 56 deletions

View File

@ -143,7 +143,7 @@ repos:
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
@ -167,7 +167,7 @@ repos:
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit

View File

@ -46,8 +46,10 @@ Anything that pushes the hour with a plain read-add-write and is *not* a term
of that derivation gets wiped by the next reset -- that is how a 00:02 workout
lost its hours on 2026-09-13. A new bonus source is an `Earner` in the
registry, never code here: the reset includes it as a term, and the live pass
(`apply_flat_bonuses_if_new`, stamped `<name>_bonus_date` in
`shutdown_base.json`) picks it up for flat earners. That pass runs the moment
(`apply_flat_bonuses_if_new`, stamped `<name>_bonus_minutes` in
`shutdown_base.json`; the old `<name>_bonus_date` still means the full bonus)
picks it up for flat earners, paying a signed progress row's share
(`earned_time` 0.24) as it rises and a credit in full. That pass runs the moment
a gate writes its ledger: `earner-bonus.path` (rendered from the registry by
`_earner_units`, re-synced by every `--sync-only` pass) starts
`earner-bonus.service` (`--apply-bonuses`). The 15-minute `workout-sync` is

View File

@ -10,7 +10,7 @@ dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time",
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",

View File

@ -4,7 +4,7 @@ bandit==1.9.4
codespell==2.4.3
coverage==7.17.4
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds

View File

@ -0,0 +1,87 @@
"""A gate's signed progress, read for the shutdown sum (``earned_time`` 0.24.0).
A gate signs "done N of M for day D" in its own ledger; ``earned_time`` pays a
no that share of a yes and owns every other pay rule (``term_for``; none is
priced here). A day with no such row pays by yes/no exactly as before. Two
readers here, one per caller:
* :func:`progress_for` -- the whole day's map, for ``earned_time.resolve``
(the daily reset, the sick floor and the preview);
* :func:`term_minutes` -- one earner's pay, for the live pass, which has to
know what it may pay *now* before it subtracts what it already applied.
The workout is left out of the map on purpose: ``WorkoutCreditMixin`` applies
it per unit, so a share paid by the reset alone would be wiped or doubled.
Both look the readers up at call time: an installed ``earned_time`` older than
0.24 pays by yes/no, logged once, never raises.
"""
from __future__ import annotations
import functools
import logging
from typing import TYPE_CHECKING
import earned_time
from screen_locker import _earned
from screen_locker._gate_off import gate_off
if TYPE_CHECKING:
from datetime import date
_logger = logging.getLogger(__name__)
@functools.cache
def _warn_no_progress() -> None:
"""Once per process: the installed earned_time predates progress."""
_logger.warning(
"earned_time has no progress reader (needs >= 0.24); every bonus pays "
"all-or-nothing"
)
def progress_for(day: date) -> dict[str, earned_time.Progress] | None:
"""Each non-workout earner's signed progress on ``day``; ``None`` if none.
``None`` for no row at all (so ``resolve`` is called exactly as before)
and on an ``earned_time`` without ``progress_map``.
"""
fn = getattr(earned_time, "progress_map", None)
if fn is None:
_warn_no_progress()
return None
earners = tuple(
e for e in _earned.registry(day) if e.name != earned_time.WORKOUT.name
)
found: dict[str, earned_time.Progress] = fn(
day,
_earned.LEDGER_HOME,
_earned.HMAC_KEY_FILE,
earners=earners,
gate_off={e.name for e in earners if gate_off(e, day)},
)
return found or None
def term_minutes(earner: earned_time.Earner, day: date, *, answer: bool | None) -> int:
"""The shutdown minutes ``earner`` earned on ``day``, priced by the library.
``earned_time.term_for`` owns every rule (a yes pays the rung, a no the
signed progress's share, ``None`` nothing, the review's dated rule); this
only reads the fact it needs. Before 0.24 it is the old yes/no.
"""
term_for = getattr(earned_time, "term_for", None)
read = getattr(earned_time, "read_progress", None)
if term_for is None or read is None:
_warn_no_progress()
return _earned.first_minutes(earner, day) if answer else 0
fact = read(
earner,
_earned.ledger_file(earner),
_earned.HMAC_KEY_FILE,
day,
gate_off=gate_off(earner, day),
)
return int(term_for(earner, day, answer=answer, progress=fact).shutdown_minutes)

View File

@ -1,7 +1,10 @@
"""Live shutdown credit for counted gate earners: paid per unit, as it lands.
A flat earner (LeetCode, reading) pays once a day, stamped
``<name>_bonus_date``. A counted gate earner -- the Automation tutor, one
A flat earner (LeetCode, reading) pays by its signed progress (a credited
day pays in full), stamped ``<name>_bonus_minutes`` with the minutes the
config already holds; each pass pays only the rise. ``<name>_bonus_date`` is
the legacy stamp (the full bonus, written before progress existed) and is
still honoured. A counted gate earner -- the Automation tutor, one
signed ledger row per verified 15-minute block -- pays per unit, so its stamp
is ``<name>_bonus_units``: the day, and how many units the config already
holds. The live pass pays only the difference, priced by
@ -32,10 +35,32 @@ _logger = logging.getLogger(__name__)
def date_stamp(earner: earned_time.Earner) -> str:
"""The once-per-day key of a flat earner's live pass in the state file."""
"""The legacy key: a flat earner's full bonus applied on that date."""
return f"{earner.name}_bonus_date"
def minutes_stamp(earner: earned_time.Earner) -> str:
"""The key of the minutes a flat earner's live pass applied on a date."""
return f"{earner.name}_bonus_minutes"
def applied_minutes(
state: dict[str, Any], earner: earned_time.Earner, today: str, full: int
) -> int:
"""Minutes of ``earner``'s bonus the config already holds today.
The legacy date stamp means the FULL bonus (so a deploy between two
passes never pays twice); else the minutes stamp of today; else 0.
"""
if state.get(date_stamp(earner)) == today:
return full
raw = state.get(minutes_stamp(earner))
if not isinstance(raw, dict) or raw.get("date") != today:
return 0
minutes = raw.get("minutes")
return minutes if isinstance(minutes, int) and minutes > 0 else 0
def units_stamp(earner: earned_time.Earner) -> str:
"""The per-day key of ``earner``'s applied units in the state file."""
return f"{earner.name}_bonus_units"
@ -53,13 +78,17 @@ def applied_units(state: dict[str, Any], earner: earned_time.Earner, today: str)
def reset_stamps(terms: Iterable[earned_time.Term], today: str) -> dict[str, object]:
"""The stamps for what a daily reset already wrote into the config.
A flat earner that paid is stamped with the date, a counted gate with
its units, so the live pass does not add either a second time today.
A flat earner that paid is stamped with the minutes it paid (a partial
pay is not the full bonus, so never the date), a counted gate with its
units, so the live pass does not add either a second time today.
"""
stamps: dict[str, object] = {}
for t in terms:
if t.earner.kind == "flat" and t.shutdown_minutes:
stamps[date_stamp(t.earner)] = today
stamps[minutes_stamp(t.earner)] = {
"date": today,
"minutes": t.shutdown_minutes,
}
elif t.earner.kind == "counted" and is_gate(t.earner) and t.answer:
stamps[units_stamp(t.earner)] = {"date": today, "units": t.answer}
return stamps

View File

@ -6,7 +6,7 @@ accumulating indefinitely across days.
The base and every bonus come from the shared earner registry in force that
day (``earned_time``, see :mod:`screen_locker._earned`). Nothing here is
state: the file carries only stamps (``<name>_bonus_date`` for a flat
state: the file carries only stamps (``<name>_bonus_minutes`` for a flat
earner, ``<name>_bonus_units`` for a counted gate, :mod:`._gate_bonus`).
The reset re-derives what today has ALREADY earned and writes base plus that
@ -44,7 +44,13 @@ from screen_locker._earned import (
registry,
span,
)
from screen_locker._gate_bonus import apply_counted_bonus, date_stamp, reset_stamps
from screen_locker._earned_progress import term_minutes
from screen_locker._gate_bonus import (
applied_minutes,
apply_counted_bonus,
minutes_stamp,
reset_stamps,
)
from screen_locker._grace_floor import save_lift
from screen_locker._log_io import load_workout_log
from screen_locker._shutdown_target import gather
@ -193,20 +199,19 @@ def _apply_flat_bonus(
mixin: object,
earner: earned_time.Earner,
) -> bool:
"""Push shutdown later by one earner's once-per-day time, if it is earned.
"""Push shutdown later by what one earner's bonus has earned beyond its stamp.
The daily reset only sees a bonus earned before it ran; this is the live
counterpart for the usual case, where the solve or the reading lands
hours later and is picked up by the next timer tick. Idempotent through
the earner's stamp in *state_file*, which the reset sets as well when it
already included the bonus.
Returns True if the bonus was applied on this call.
What it has earned is ``earned_time``'s
(:func:`~screen_locker._earned_progress.term_minutes`); only the rise over
:func:`applied_minutes` goes out: never twice, never a claw-back.
Returns True if minutes were applied on this call.
"""
today = today_str()
day = date.fromisoformat(today)
state = _load_state(state_file)
stamp = date_stamp(earner)
if state.get(stamp) == today:
full = first_minutes(earner, day)
applied = applied_minutes(state, earner, today, full)
if applied >= full:
return False
answer = earned_today(earner)
if answer is None:
@ -214,14 +219,13 @@ def _apply_flat_bonus(
"%s state could not be checked; no shutdown time for it", earner.label
)
return False
if not answer:
pay_now = term_minutes(earner, day, answer=answer)
if (minutes := pay_now - applied) <= 0:
return False
day = date.fromisoformat(today)
minutes = first_minutes(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
state[minutes_stamp(earner)] = {"date": today, "minutes": pay_now}
_save_state(state_file, state)
_logger.info("%s bonus: +%s shutdown time today.", earner.label, span(minutes))
return True

View File

@ -18,11 +18,12 @@ earns. :func:`gather` reads today's real inputs; it writes nothing.
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
import earned_time
from screen_locker._earned import first_credits, gate_answers, registry
from screen_locker._earned_progress import progress_for
from screen_locker._grace_floor import first_done_at
from screen_locker._log_io import load_workout_log
from screen_locker._rest_day import is_rest_day
@ -91,6 +92,9 @@ class DayInputs:
first_credits: Each penalised gate's first real credit
(:func:`~screen_locker._earned.first_credits`); ``None`` resolves
on ``penalty_from`` alone, as before earned_time 0.6.
progress: Each gate's signed "done N of M" for the day
(:func:`~screen_locker._earned_progress.progress_for`); a no
then pays that share. ``None`` pays by yes/no, as before 0.24.
"""
day: date
@ -100,6 +104,7 @@ class DayInputs:
first_done: float | None = None
sick_day: bool = False
first_credits: Mapping[str, date | None] | None = None
progress: Mapping[str, earned_time.Progress] | None = None
def derive(inputs: DayInputs) -> Target:
@ -114,11 +119,13 @@ def derive(inputs: DayInputs) -> Target:
earners = registry(day)
starts = inputs.first_credits
sick = inputs.sick_day
resolution = (
earned_time.resolve(answers, day, earners, sick=sick)
if starts is None
else earned_time.resolve(answers, day, earners, first_credits=starts, sick=sick)
)
# Only what is set is passed: an older earned_time has no such keyword.
extra: dict[str, Any] = {}
if starts is not None:
extra["first_credits"] = starts
if inputs.progress:
extra["progress"] = inputs.progress
resolution = earned_time.resolve(answers, day, earners, sick=sick, **extra)
return Target(
resolution=resolution,
rest_day=inputs.rest_day,
@ -147,6 +154,7 @@ def gather_inputs(day: date, log_file: Path | None) -> DayInputs:
first_done=first_done_at(day, log_file, rest_day=rest_day),
sick_day=is_sick(day),
first_credits=first_credits(registry(day), day),
progress=progress_for(day),
)

View File

@ -0,0 +1,67 @@
"""Signed progress rows and a state file for the partial-bonus tests.
A progress row is the fact a gate signs, "done N of M for day D"
(``earned_time`` 0.24.0, DOCS-progress.md), written to the gate's own ledger
next to its credits. Like every ledger helper here it signs with
``_earned_fixtures.KEY`` and lands where screen-locker reads it, so the
tests read real signed ledgers, never a mock of the reader.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Final
import earned_time
from screen_locker._day import today_str
from screen_locker.tests._earned_fixtures import _any_credit, signed, write_ledger
if TYPE_CHECKING:
from unittest.mock import MagicMock
# A flat earner whose rung does not divide by 3 or 2, so a share rounds down.
ODD: Final = earned_time.Earner(
name="odd",
label="Odd",
gaming_minutes=50,
shutdown_minutes=50,
ledger=".local/share/odd_guard/ledger.json",
match=_any_credit,
progress_source="odd",
)
def progress_row(
earner: earned_time.Earner,
done: int,
target: int,
day: str | None = None,
) -> dict[str, Any]:
"""A signed progress row for ``earner``'s source (default today)."""
for_day = day or today_str()
return signed(
{
"kind": "progress",
"entry_id": f"progress:{for_day}:{done}:{target}",
"day": for_day,
"amount": 0,
"device": "test",
"created_at": f"{for_day}T12:00:00+00:00",
"detail": {
"source": earner.progress_source,
"for_day": for_day,
"done": str(done),
"target": str(target),
},
}
)
def put_progress(earner: earned_time.Earner, rows: list[tuple[int, int]]) -> None:
"""Replace ``earner``'s ledger with one progress row per (done, target)."""
write_ledger(earner, [progress_row(earner, d, t) for d, t in rows])
def paid(mixin: MagicMock) -> list[int]:
"""The minutes each ``_adjust_shutdown_time_by`` call pushed, in order."""
return [c.args[0] for c in mixin._adjust_shutdown_time_by.call_args_list]

View File

@ -196,7 +196,7 @@ class TestThroughTheShutdownBase:
terms = earned_time.resolve(answers, TODAY, registry(TODAY)).terms
stamps = reset_stamps(terms, today_str())
assert stamps == {
"leetcode_bonus_date": today_str(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
"blocks_bonus_units": {"date": today_str(), "units": 2},
}

View File

@ -0,0 +1,201 @@
"""The live pass and the reset pay a gate's bonus by its signed progress.
``earned_time`` 0.24.0 reads a gate's "done N of M" row; a day with no such
row pays exactly as before, and a credited answer always pays in full. The
live pass records what it applied in ``<name>_bonus_minutes`` so the next
pass pays only the difference (never a claw-back, never twice).
Real signed ledgers under the redirected home; only the shutdown writer is a
mock.
"""
from __future__ import annotations
from datetime import date, timedelta
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import earned_time
import pytest
from screen_locker._day import today_str
from screen_locker._shutdown_base import (
apply_flat_bonuses_if_new,
base_minutes,
)
from screen_locker.tests._earned_fixtures import (
credit,
register,
signing_key,
write_ledger,
)
from screen_locker.tests._progress_fixtures import (
ODD,
paid,
progress_row,
put_progress,
)
if TYPE_CHECKING:
from pathlib import Path
READING = earned_time.READING
_FULL = 60 # reading's rung today
def _mixin() -> MagicMock:
mixin = MagicMock()
mixin._read_shutdown_config.return_value = (base_minutes(), base_minutes(), 300)
mixin._write_shutdown_config.return_value = True
mixin._adjust_shutdown_time_by.return_value = True
return mixin
def _state(tmp_path: Path) -> Path:
"""An empty state file path: nothing stamped yet."""
return tmp_path / "state.json"
def _stamped(state: Path) -> dict[str, object]:
loaded: dict[str, object] = json.loads(state.read_text())
return loaded
class TestSeededPasses:
"""The brief's scratch-state evidence, one signed ledger per step."""
def test_half_then_the_rest_then_nothing(self, tmp_path: Path) -> None:
"""1/2 pays half, a later 2/2 pays only the remainder, a third pays 0."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
put_progress(READING, [(1, 2), (2, 2)])
apply_flat_bonuses_if_new(state, mixin)
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL // 2, _FULL - _FULL // 2]
assert _stamped(state)["reading_bonus_minutes"] == {
"date": today_str(),
"minutes": _FULL,
}
def test_no_progress_row_pays_nothing_until_credited(self, tmp_path: Path) -> None:
"""No fact and no credit: still a plain no, nothing stamped."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
write_ledger(READING, [])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == []
assert not state.exists()
def test_a_credit_pays_full_whatever_the_row_says(self, tmp_path: Path) -> None:
"""A true answer is full pay even beside a 1/4 progress row."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
write_ledger(READING, [credit(READING), progress_row(READING, 1, 4)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL]
def test_credit_after_partial_pays_the_remainder(self, tmp_path: Path) -> None:
"""Half paid, then the credit lands: the other half, once."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
write_ledger(READING, [credit(READING), progress_row(READING, 1, 2)])
apply_flat_bonuses_if_new(state, mixin)
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL // 2, _FULL // 2]
def test_legacy_date_stamp_pays_nothing_more(self, tmp_path: Path) -> None:
"""A bonus_date of today means the full bonus is in: a mid-day deploy
never pays twice, even with a complete progress row."""
state, mixin = _state(tmp_path), _mixin()
state.write_text(json.dumps({"reading_bonus_date": today_str()}))
with signing_key(tmp_path):
write_ledger(READING, [credit(READING), progress_row(READING, 2, 2)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == []
assert _stamped(state) == {"reading_bonus_date": today_str()}
def test_uneven_bonus_rounds_down_and_the_credit_pays_the_exact_rest(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""50 min at 1/3 is 16 (floor); the final credit pays 34, not 33."""
register(monkeypatch, ODD)
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
put_progress(ODD, [(1, 3)])
apply_flat_bonuses_if_new(state, mixin)
write_ledger(ODD, [credit(ODD), progress_row(ODD, 1, 3)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [16, 34]
def test_a_lost_row_never_claws_back(self, tmp_path: Path) -> None:
"""Progress that vanishes pays less than applied: nothing, stamp kept."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
put_progress(READING, [(2, 2)])
apply_flat_bonuses_if_new(state, mixin)
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL]
assert _stamped(state)["reading_bonus_minutes"] == {
"date": today_str(),
"minutes": _FULL,
}
def test_yesterdays_minutes_stamp_counts_for_nothing(self, tmp_path: Path) -> None:
"""A stamp dated another day is stale: today pays from zero."""
yesterday = (date.fromisoformat(today_str()) - timedelta(days=1)).isoformat()
state, mixin = _state(tmp_path), _mixin()
state.write_text(
json.dumps({"reading_bonus_minutes": {"date": yesterday, "minutes": 60}})
)
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL // 2]
@pytest.mark.parametrize(
"junk", ["x", {"date": today_str(), "minutes": "7"}, {"date": today_str()}]
)
def test_a_malformed_minutes_stamp_counts_as_zero(
self, tmp_path: Path, junk: object
) -> None:
"""A hand-edited stamp earns nothing extra and never raises."""
state, mixin = _state(tmp_path), _mixin()
state.write_text(json.dumps({"reading_bonus_minutes": junk}))
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL // 2]
def test_a_forged_row_pays_nothing(self, tmp_path: Path) -> None:
"""A progress row edited after signing is not a fact."""
state, mixin = _state(tmp_path), _mixin()
row = progress_row(READING, 1, 2)
row["detail"]["done"] = "2"
with signing_key(tmp_path):
write_ledger(READING, [row])
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == []
def test_a_failed_write_stamps_nothing(self, tmp_path: Path) -> None:
"""If the config write fails the next pass pays the whole share."""
state, mixin = _state(tmp_path), _mixin()
mixin._adjust_shutdown_time_by.return_value = False
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.return_value = True
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == [_FULL // 2, _FULL // 2]
def test_an_unreadable_ledger_pays_nothing(self, tmp_path: Path) -> None:
"""No ledger file at all is "could not check": nothing, and no stamp."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
apply_flat_bonuses_if_new(state, mixin)
assert paid(mixin) == []

View File

@ -0,0 +1,143 @@
"""The daily reset and the derived target pay a gate's bonus by its progress.
``earned_time`` 0.24.0 reads a gate's "done N of M" row; a day with no such
row pays exactly as before, and a credited answer always pays in full. The
live pass records what it applied in ``<name>_bonus_minutes`` so the next
pass pays only the difference (never a claw-back, never twice).
Real signed ledgers under the redirected home; only the shutdown writer is a
mock.
"""
from __future__ import annotations
from datetime import date
import json
import logging
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import earned_time
import pytest
from screen_locker import _earned_progress
from screen_locker._day import today_str
from screen_locker._shutdown_base import (
apply_flat_bonuses_if_new,
base_minutes,
reset_to_base_if_new_day,
)
from screen_locker._shutdown_target import DayInputs, derive, gather_inputs
from screen_locker.tests._earned_fixtures import (
credit,
signing_key,
write_ledger,
)
from screen_locker.tests._progress_fixtures import (
paid,
progress_row,
put_progress,
)
if TYPE_CHECKING:
from pathlib import Path
READING = earned_time.READING
_FULL = 60 # reading's rung today
def _mixin() -> MagicMock:
mixin = MagicMock()
mixin._read_shutdown_config.return_value = (base_minutes(), base_minutes(), 300)
mixin._write_shutdown_config.return_value = True
mixin._adjust_shutdown_time_by.return_value = True
return mixin
def _state(tmp_path: Path) -> Path:
"""An empty state file path: nothing stamped yet."""
return tmp_path / "state.json"
def _stamped(state: Path) -> dict[str, object]:
loaded: dict[str, object] = json.loads(state.read_text())
return loaded
class TestResetAndTarget:
"""The daily reset and the derived target use the same partial pay."""
def test_reset_pays_the_share_and_stamps_minutes_not_the_date(
self, tmp_path: Path
) -> None:
"""Stamping bonus_date here would freeze a half for the whole day."""
state, mixin = _state(tmp_path), _mixin()
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
assert reset_to_base_if_new_day(state, mixin) is True
write_ledger(READING, [credit(READING), progress_row(READING, 1, 2)])
apply_flat_bonuses_if_new(state, mixin)
base = base_minutes()
mixin._write_shutdown_config.assert_called_once_with(
base + _FULL // 2, base + _FULL // 2, 300, restore=True
)
assert paid(mixin) == [_FULL // 2]
assert "reading_bonus_date" not in _stamped(state)
def test_derive_pays_a_share_for_a_no(self) -> None:
"""A no with progress pays done/target of the rung; a yes pays full."""
day = date.fromisoformat(today_str())
flat = {"leetcode": False, "reading": True}
none = derive(DayInputs(day, flat))
half = derive(
DayInputs(day, flat, progress={"leetcode": earned_time.Progress(1, 2)})
)
full = derive(
DayInputs(day, flat, progress={"reading": earned_time.Progress(1, 2)})
)
assert half.minutes - none.minutes == _FULL // 2
assert full.minutes == none.minutes
def test_gather_reads_signed_progress_but_never_the_workouts(
self, tmp_path: Path
) -> None:
"""The workout is applied by its own mixin: its row never reaches resolve."""
day = date.fromisoformat(today_str())
with signing_key(tmp_path):
put_progress(READING, [(1, 2)])
write_ledger(earned_time.WORKOUT, [progress_row(earned_time.WORKOUT, 1, 2)])
inputs = gather_inputs(day, None)
assert inputs.progress == {"reading": earned_time.Progress(1, 2)}
def test_no_row_anywhere_passes_no_progress(self, tmp_path: Path) -> None:
"""An empty map is passed as None: resolve is called as before."""
day = date.fromisoformat(today_str())
with signing_key(tmp_path):
assert gather_inputs(day, None).progress is None
class TestWithoutTheReader:
"""An installed earned_time older than 0.24 pays by yes/no, loudly once."""
def test_progress_map_absent_means_no_progress_and_a_warning(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""No ``progress_map``: ``None``, logged at warning."""
monkeypatch.delattr(earned_time, "progress_map")
_earned_progress._warn_no_progress.cache_clear()
with caplog.at_level(logging.WARNING):
assert (
_earned_progress.progress_for(date.fromisoformat(today_str())) is None
)
assert "progress" in caplog.text
@pytest.mark.parametrize("missing", ["term_for", "read_progress"])
def test_no_term_pricer_pays_the_old_yes_no(
self, monkeypatch: pytest.MonkeyPatch, missing: str
) -> None:
"""Without ``term_for``/``read_progress``: a yes pays the rung, a no 0."""
monkeypatch.delattr(earned_time, missing)
day = date.fromisoformat(today_str())
assert _earned_progress.term_minutes(READING, day, answer=True) == _FULL
assert not _earned_progress.term_minutes(READING, day, answer=False)

View File

@ -0,0 +1,89 @@
"""The live pass prices the review through ``earned_time.term_for``, not here.
From ``REVIEW_PROGRESS_FROM`` (2026-11-24) a credited review with no verified
progress row pays 0 (the library logs it), a row pays ``20 * done // target``;
before that date the review ignores rows and pays the flat 20. The live pass
holds no pay formula, so each of these is the library's answer.
"""
from __future__ import annotations
from datetime import date
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import earned_time
import pytest
from screen_locker import _shutdown_base
from screen_locker.tests._earned_fixtures import answering, signing_key, write_ledger
from screen_locker.tests._progress_fixtures import paid, progress_row
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
REVIEW = earned_time.REVIEW
_BEFORE = "2026-11-23"
_FROM = earned_time.REVIEW_PROGRESS_FROM.isoformat()
@pytest.fixture(name="credited", autouse=True)
def credited_fixture() -> Iterator[None]:
"""The review gate answers yes (a backed review landed)."""
with answering({"review": True}):
yield
def _pass(tmp_path: Path, day: str, rows: list[tuple[int, int]]) -> list[int]:
"""One live pass for the review on ``day``; the minutes pushed."""
mixin = MagicMock()
mixin._adjust_shutdown_time_by.return_value = True
with signing_key(tmp_path), patch.object(_shutdown_base, "today_str", lambda: day):
write_ledger(REVIEW, [progress_row(REVIEW, d, t, day) for d, t in rows])
_shutdown_base._apply_flat_bonus(tmp_path / "state.json", mixin, REVIEW)
return paid(mixin)
def test_the_cutover_is_the_documented_day() -> None:
"""The brief's dates: rows count from 2026-11-24."""
assert _FROM == "2026-11-24"
assert date.fromisoformat(_BEFORE) < earned_time.REVIEW_PROGRESS_FROM
def test_credited_with_no_row_pays_nothing_from_the_cutover(tmp_path: Path) -> None:
"""No verified fact, no minutes: never the flat 20 any more."""
assert _pass(tmp_path, _FROM, []) == []
@pytest.mark.parametrize(("done", "target", "minutes"), [(1, 3, 6), (3, 3, 20)])
def test_a_row_pays_its_share_of_twenty(
tmp_path: Path, done: int, target: int, minutes: int
) -> None:
"""1/3 is 6, 3/3 is 20, even though the answer is a credited yes."""
assert _pass(tmp_path, _FROM, [(done, target)]) == [minutes]
@pytest.mark.parametrize("rows", [[], [(1, 3)], [(3, 3)]])
def test_before_the_cutover_a_credit_pays_the_flat_twenty(
tmp_path: Path, rows: list[tuple[int, int]]
) -> None:
"""Rows are ignored before 2026-11-24: 20 whatever they say."""
assert _pass(tmp_path, _BEFORE, rows) == [20]
def test_the_rest_is_paid_once_the_row_grows(tmp_path: Path) -> None:
"""6 now, then only the 14 that 3/3 adds, then nothing."""
mixin = MagicMock()
mixin._adjust_shutdown_time_by.return_value = True
state = tmp_path / "state.json"
with (
signing_key(tmp_path),
patch.object(_shutdown_base, "today_str", lambda: _FROM),
):
for rows in ([(1, 3)], [(1, 3), (3, 3)], [(3, 3)]):
write_ledger(REVIEW, [progress_row(REVIEW, d, t, _FROM) for d, t in rows])
_shutdown_base._apply_flat_bonus(state, mixin, REVIEW)
assert paid(mixin) == [6, 14]
assert json.loads(state.read_text())["review_bonus_minutes"]["minutes"] == 20

View File

@ -0,0 +1,33 @@
"""The preview's "done" earner is a finished gate: a yes plus a 1/1 fact.
From 2026-11-24 a credited review with no verified fact pays 0, so the
preview's simulated yes carries the fact a finished gate signs; otherwise its
derived target would not match the live add, which ``term_for`` prices alike.
"""
from __future__ import annotations
from datetime import date
import earned_time
from screen_locker._shutdown_target import DayInputs, derive
from scripts._preview_sim import finished
_DAY = date(2026, 11, 24)
def test_finished_marks_only_the_done_earners() -> None:
"""Each done earner gets 1 of 1; the rest get nothing."""
assert finished({"review": True, "leetcode": False}) == {
"review": earned_time.Progress(1, 1)
}
def test_a_simulated_review_pays_twenty_only_with_the_fact() -> None:
"""With ``finished`` the sim's review adds its 20; the bare yes adds 0."""
flat = {"review": True}
none = derive(DayInputs(_DAY, {"review": False})).minutes
bare = derive(DayInputs(_DAY, flat)).minutes
fact = derive(DayInputs(_DAY, flat, progress=finished(flat))).minutes
assert (bare - none, fact - none) == (0, 20)

View File

@ -8,7 +8,7 @@ day's registry, and reject a name not in force that day with a usage error.
from __future__ import annotations
from datetime import timedelta
from datetime import date, timedelta
import sys
import earned_time
@ -16,7 +16,7 @@ import pytest
from screen_locker import _earned, _grace_floor, _shutdown, _sick_floor
from screen_locker._earned import hhmm
from scripts import preview_shutdown
from scripts import _preview_sim, preview_shutdown
_REVIEW_DAY = earned_time.REVIEW_FROM.isoformat()
# The last day before the review joined the registry.
@ -103,3 +103,24 @@ def test_preview_review_sequence_before_review_from_is_a_usage_error(
assert _EVE in err
assert "Traceback" not in err
assert "KeyError" not in err
def test_preview_review_sequence_pays_a_partial_rows_share(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""C4: a half-done review row on 2026-11-24 adds ``term_for``'s share.
Live (``SimShutdown.credit``) and derived (``finished``) read the same
pinned row, so the share shows on both sides with no MISMATCH.
"""
day = date(2026, 11, 24)
half = earned_time.Progress(1, 2)
monkeypatch.setattr(_preview_sim, "ROWS", {"review": half})
review = earned_time.earner("review", _earned.registry(day))
share = earned_time.term_for(review, day, answer=True, progress=half)
assert share.shutdown_minutes != earned_time.REVIEW_SHUTDOWN_MINUTES
_run(monkeypatch, "--day", day.isoformat(), "--sequence", "review@21:00")
out = capsys.readouterr().out
want = hhmm(_start(out) + share.shutdown_minutes)
assert _lines(out) == {"review@21:00": f"{want} (derived {want})"}
assert "MISMATCH" not in out

View File

@ -77,8 +77,8 @@ class TestFlatBonuses:
apply_flat_bonuses_if_new(state, mixin)
assert mixin._adjust_shutdown_time_by.call_count == 2
assert json.loads(state.read_text()) == {
"leetcode_bonus_date": today_str(),
"reading_bonus_date": today_str(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
"reading_bonus_minutes": {"date": today_str(), "minutes": 60},
}
apply_flat_bonuses_if_new(state, mixin)
assert mixin._adjust_shutdown_time_by.call_count == 2
@ -93,7 +93,9 @@ class TestFlatBonuses:
mixin = _mixin()
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {"reading_bonus_date": today_str()}
assert json.loads(state.read_text()) == {
"reading_bonus_minutes": {"date": today_str(), "minutes": 60}
}
@pytest.mark.usefixtures("with_extra")
@ -113,7 +115,7 @@ class TestANewlyRegisteredEarner:
)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"extra_bonus_date": today_str(),
"extra_bonus_minutes": {"date": today_str(), "minutes": 60},
}
def test_live_pass_applies_it_once(
@ -126,7 +128,9 @@ class TestANewlyRegisteredEarner:
apply_flat_bonuses_if_new(state, mixin)
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.assert_called_once_with(60)
assert json.loads(state.read_text()) == {"extra_bonus_date": today_str()}
assert json.loads(state.read_text()) == {
"extra_bonus_minutes": {"date": today_str(), "minutes": 60}
}
def test_its_ledger_is_read_like_any_other(self, tmp_path: Path) -> None:
"""The new earner's signed ledger is read like any existing gate's."""
@ -175,8 +179,8 @@ class TestRealLedgers:
)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"leetcode_bonus_date": today_str(),
"reading_bonus_date": today_str(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
"reading_bonus_minutes": {"date": today_str(), "minutes": 60},
}

View File

@ -70,7 +70,7 @@ class TestResetIncludesTheHour:
)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"leetcode_bonus_date": today_str(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
}
def test_reset_without_solve_leaves_no_stamp(
@ -106,7 +106,7 @@ class TestLivePass:
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(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
}
def test_yesterdays_stamp_does_not_block_today(

View File

@ -105,7 +105,7 @@ class TestResetIncludesReading:
)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"reading_bonus_date": today_str(),
"reading_bonus_minutes": {"date": today_str(), "minutes": 60},
}
@pytest.mark.usefixtures("pre_ladder")
@ -123,8 +123,8 @@ class TestResetIncludesReading:
)
assert json.loads(state.read_text()) == {
"last_reset_date": today_str(),
"leetcode_bonus_date": today_str(),
"reading_bonus_date": today_str(),
"leetcode_bonus_minutes": {"date": today_str(), "minutes": 60},
"reading_bonus_minutes": {"date": today_str(), "minutes": 60},
}
apply_flat_bonuses_if_new(state, mixin)
mixin._adjust_shutdown_time_by.assert_not_called()

View File

@ -54,7 +54,7 @@ class TestReadingLivePass:
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(),
"reading_bonus_minutes": {"date": today_str(), "minutes": 60},
}
def test_stamped_today_never_reads_the_ledger(

View File

@ -15,12 +15,13 @@ import earned_time
import sickdays
from screen_locker._ceiling import HARD_CEILING_MINUTES as HELPER_CEILING
from screen_locker._earned import first_minutes, registry
from screen_locker._earned import registry
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
from screen_locker._shutdown import ShutdownMixin
from screen_locker._sick import is_sick
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
@ -72,6 +73,17 @@ class SimRunnerUp(RunnerUpVerificationMixin):
return sorted(str(p) for p in self.folder.glob(f"*{date_str}*.tcx"))
# The signed progress row each simulated gate writes, by earner name; absent
# means finished (1 of 1). One source for the live add and the derivation,
# so a partial row (pinned by a test) cannot print a false MISMATCH.
ROWS: dict[str, earned_time.Progress] = {}
def row(name: str) -> earned_time.Progress:
"""The progress row ``name``'s simulated gate signs."""
return ROWS.get(name, earned_time.Progress(1, 1))
class SimShutdown(ShutdownMixin):
"""The real add/absorb paths against an in-memory config."""
@ -101,13 +113,29 @@ class SimShutdown(ShutdownMixin):
elif name == earned_time.WORKOUT.name:
self._adjust_shutdown_time_later()
else:
# The registry in force on ``day``: the review joins it only from
# A credited gate, priced by its row as ``finished`` prices it. The
# registry in force on ``day``: the review joins it only from
# ``REVIEW_FROM``, so the static ``EARNERS`` tuple misses it.
minutes = first_minutes(earned_time.earner(name, registry(day)), day)
self._adjust_shutdown_time_by(minutes)
term = earned_time.term_for(
earned_time.earner(name, registry(day)),
day,
answer=True,
progress=row(name),
)
self._adjust_shutdown_time_by(term.shutdown_minutes)
self._apply_sick_floor()
def finished(done: Mapping[str, bool]) -> dict[str, earned_time.Progress]:
"""The fact each done earner's gate signs (:func:`row`, 1 of 1 by default).
``derive`` needs it beside the yes: from 2026-11-24 a credited review with
no verified fact pays 0, so a sim of "done" without it would not match the
live add (:meth:`SimShutdown.credit`), which is priced the same way.
"""
return {n: row(n) for n, v in done.items() if v}
# The --sequence step that marks the day sick instead of crediting an earner.
SICK_STEP = "sick"

View File

@ -51,6 +51,7 @@ from scripts._preview_sim import (
SICK_STEP,
SimRunnerUp,
SimShutdown,
finished,
sick_pool,
stamp,
use_temp_pool,
@ -111,6 +112,7 @@ def _simulate(args: argparse.Namespace, tmp: Path) -> None:
rest_day=is_rest_day(day, rest_file),
first_done=min(times, default=None),
sick_day=sick_pool(day, sick_day=args.sick_day),
progress=finished(flat),
)
)
_report("simulated", target)
@ -128,7 +130,9 @@ def _sequence(args: argparse.Namespace, tmp: Path) -> None:
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
derive(
DayInputs(d, done, workouts, sick_day=True, progress=finished(done))
).minutes
)
for step in args.sequence.split(","):
name, _, at = step.partition("@")
@ -140,7 +144,14 @@ def _sequence(args: argparse.Namespace, tmp: Path) -> None:
first = min(first or stamp(day, at), stamp(day, at))
sim.credit(name, day)
want = derive(
DayInputs(day, done, workouts, first_done=first, sick_day=is_sick(day))
DayInputs(
day,
done,
workouts,
first_done=first,
sick_day=is_sick(day),
progress=finished(done),
)
)
# Every credit adds to tonight (2026-11-18), so live must equal derived.
verdict = "" if sim.config[0] == want.minutes else " MISMATCH"