diff --git a/earned_time/DOCS-progress.md b/earned_time/DOCS-progress.md new file mode 100644 index 0000000..6648e21 --- /dev/null +++ b/earned_time/DOCS-progress.md @@ -0,0 +1,89 @@ +# Progress: partial pay (0.24.0) + +kuhy's rule (2026-11-22): a gate pays its bonus in proportion to progress, in +equal slices, nothing held back. Half the pages is half the bonus. It covers the +shutdown bonus, its gaming twin and sick days. + +earned_time cannot derive a gate's plan, so the gate signs a fact, "done N of +target M for day D", and earned_time only reads it. A day with no such row +resolves exactly as 0.23.0 did, for every registry and day. + +## The row + +One signed ledger row, in the gate's own ledger (`Earner.ledger`): + +```json +{"kind": "progress", "entry_id": "progress:::", + "day": "", "amount": 0, "device": "...", "created_at": "...", + "detail": {"source": "", "for_day": "YYYY-MM-DD", + "done": "", "target": ""}, + "hmac": ""} +``` + +All four `detail` values are strings. The sources: `workout`, `leetcode`, +`reading`, `review` (`Earner.progress_source`; the tutor and the focus earner +have none and never pay by share). + +## The reader + +`read_progress(earner, ledger, key_file, day, *, gate_off=False)` returns a +`Progress(done, target)` or `None`. A row counts only when all of this holds: + +- its HMAC verifies with the shared key; +- `kind` is `progress`; +- `detail.source` is the earner's `progress_source`; +- `detail.for_day` is the day asked; +- `done` and `target` are strings of ASCII digits 0-9, at most nine of them + (no int, float, sign, space, empty string or other script's digits); +- `target` is at least 1. + +`done` is capped at `target`. Over the matching rows the largest `done` and the +largest `target` win, so a replayed or deleted row can only lower the share +while the target stays the same. + +`progress_map(day, home, key_file, *, earners=None, gate_off=())` does this for +every earner of `earners_for(day)` (or the registry given) and returns +`{earner name: Progress}`, holding only earners that have a fact. Pass the names +of the earners whose gate is off today as `gate_off`, as for `done_today`. + +## The pay + +`resolve(answers, day, ..., progress=progress_map(...))`. A term uses its +progress only when its answer is `0` or `False`, and then pays +`full * done // target`, floored, where `full` is what a yes pays that day: the +ladder rung for shutdown (`shutdown_minutes_for`), the earner's first-unit pay +for gaming. A true answer pays full exactly as before, whatever the row says. +An answer of `None` ("could not check") and a missing answer still earn nothing, +even beside a complete row. `Term.progress` holds the fact a term was paid from +(`None` otherwise), so a view can show why. A sick day adds each term's pay +to 20:00, so a partial pays its share at rung pay, capped at the ceiling. + +The focus earner already paid N/M floored; it now calls the same arithmetic +(`_share.share_minutes`), with the same floor. + +## Every failure is fail-closed + +`None` means "pays by today's yes/no rule", never more. Each of these is `None`: + +- no row for the earner and day: the gate has said nothing; +- a bad or missing signature, or a row edited after signing: a forged claim; +- another day or another gate's source: a fact about something else; +- bad integers (typed as numbers, signed, padded, empty, too long): unreadable; +- a zero target: no plan, so no share; +- an unreadable or empty key, an unreadable or malformed ledger: logged at + warning, never raised; +- `gate_off`: the gate has no price today, so there is nothing to split; +- an earner without a `progress_source`. + +A bad row among good rows is skipped, not fatal. + +## Not credits + +A `progress` row has `amount` 0 and its own kind. `done_today`, `credit_units`, +`first_credit_at` and `maturity` never see it, so it cannot earn a bonus, mature +a gate or start a penalty. + +## Open question + +What a paid review pays when no progress row exists is unchanged (the full 20 +minutes, today's rule); kuhy has not decided otherwise. diff --git a/earned_time/DOCS-tutor.md b/earned_time/DOCS-tutor.md new file mode 100644 index 0000000..61d52a6 --- /dev/null +++ b/earned_time/DOCS-tutor.md @@ -0,0 +1,31 @@ +# The tutor row contract (0.8.0) + +Moved out of the README (0.24.0) to keep it under the line cap; unchanged. + +**Mixed-day safe.** `credit_units` sums what +each counting row pays instead of counting rows (`_credits.row_units`, the +per-matcher reader `_match.ROW_UNITS`): + +- `detail.minutes` (a positive JSON int, never a bool/float/string) is the + active minutes the row pays. A row **without** it is a 0.7.0 15-minute + block and pays 15 (`LEGACY_TUTOR_MINUTES`), so a day that mixes block rows + and minute rows sums both, and an all-block day resolves exactly as 0.7.0 + did (min(15 n, 60) = 15 min(n, 4)). A row whose `minutes` is present but + invalid is refused by `tutor_match` (logged) and pays nothing anywhere. +- An `entry_id` pays once; rows repeated under one id pay the **smallest** + of their counts, so a replay or a rewrite can never raise a credit. +- What the writer ([kuhyx/tutor](https://github.com/kuhyx/tutor) `tutor/credit.py`) must guarantee: every + new row carries `detail.minutes`; one row per credited minute, + `entry_id = f"{session_id}-m{n}"` with `n` the session's n-th credited + active minute (deterministic, so a retry rewrites the same id; never the + `-b{n}` form); ids never cover overlapping minutes (no cumulative "total so + far" rows); `detail.ended_at` is when the last paid minute ended (it picks + the day, so a multi-minute row must never span local midnight); its own + daily cap sums minutes (block rows as 15) up to 60. N-minute rows (e.g. + every 5 minutes) are allowed under the same rules; each write fires + screen-locker's `earner-bonus.path`, so per-minute rows rewrite the + shutdown schedule once a minute. + +Days before `TUTOR_FROM` resolve on `EARNERS` exactly as before. Consumers must +iterate `earners_for(day)`, never `EARNERS`; `resolve`/`base_for` default to +it, and ignore answers for an earner of another day's registry. diff --git a/earned_time/README.md b/earned_time/README.md index f4f0f70..0e1f455 100644 --- a/earned_time/README.md +++ b/earned_time/README.md @@ -92,33 +92,9 @@ penalty has started, the gaming base drops by the full 60 done is 3 h / 18:50 and everything done is still 8 h / 23:00. Until then (given `first_credits`, see below) it costs nothing: 4 h / 19:50. -**The tutor row contract (0.8.0, mixed-day safe).** `credit_units` sums what -each counting row pays instead of counting rows (`_credits.row_units`, the -per-matcher reader `_match.ROW_UNITS`): - -- `detail.minutes` (a positive JSON int, never a bool/float/string) is the - active minutes the row pays. A row **without** it is a 0.7.0 15-minute - block and pays 15 (`LEGACY_TUTOR_MINUTES`), so a day that mixes block rows - and minute rows sums both, and an all-block day resolves exactly as 0.7.0 - did (min(15 n, 60) = 15 min(n, 4)). A row whose `minutes` is present but - invalid is refused by `tutor_match` (logged) and pays nothing anywhere. -- An `entry_id` pays once; rows repeated under one id pay the **smallest** - of their counts, so a replay or a rewrite can never raise a credit. -- What the writer ([kuhyx/tutor](https://github.com/kuhyx/tutor) `tutor/credit.py`) must guarantee: every - new row carries `detail.minutes`; one row per credited minute, - `entry_id = f"{session_id}-m{n}"` with `n` the session's n-th credited - active minute (deterministic, so a retry rewrites the same id; never the - `-b{n}` form); ids never cover overlapping minutes (no cumulative "total so - far" rows); `detail.ended_at` is when the last paid minute ended (it picks - the day, so a multi-minute row must never span local midnight); its own - daily cap sums minutes (block rows as 15) up to 60. N-minute rows (e.g. - every 5 minutes) are allowed under the same rules; each write fires - screen-locker's `earner-bonus.path`, so per-minute rows rewrite the - shutdown schedule once a minute. - -Days before `TUTOR_FROM` resolve on `EARNERS` exactly as before. Consumers must -iterate `earners_for(day)`, never `EARNERS`; `resolve`/`base_for` default to -it, and ignore answers for an earner of another day's registry. +**The tutor row contract (0.8.0, mixed-day safe)** — `detail.minutes`, one row per +credited minute, the legacy 15-minute block, an `entry_id` paying once and what +the writer must guarantee: [DOCS-tutor.md](DOCS-tutor.md). **Gap waiver** (`ANKI_WAIVED_FROM`, 2026-10-09): no anki/automation earner. @@ -145,6 +121,14 @@ From 2026-11-23 a finished, backed coach review adds 20 shutdown minutes once a day, capped at the ceiling; never a rung, never in the floor. The row contract and the rules are in [DOCS-review.md](DOCS-review.md). +## Partial pay (0.24.0) + +A gate signs "done N of target M for day D" and `resolve(..., progress=)` pays a +no that share of a yes (`60 * 1 // 3 = 20`), for shutdown, gaming and sick +days. A yes pays full and "could not check" nothing, as ever; with no row +anywhere every output is 0.23.0's. The row, the reader and every fail-closed +case are in [DOCS-progress.md](DOCS-progress.md). + ## Gate maturity (0.6.0) How far to trust a gate, computed from its ledger by `maturity()`, is in @@ -153,7 +137,7 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in ## API - `resolve(answers, day=None, earners=None, *, first_credits=None, sick=False, - leisure=None) -> Resolution` — the one sum. `sick_shutdown_from(paid_minutes, + leisure=None, progress=None) -> Resolution` — the one sum. `sick_shutdown_from(paid_minutes, day) -> int`. `base_for(day=None, earners=None, *, first_credits=None, leisure=None) -> Base` — the day's floors. `gaming_base_minutes_for(day)`, `gaming_ceiling_minutes_for(day) -> int` — the gaming base and cap. @@ -179,6 +163,10 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in `REVIEW_SOURCE`, `GUARD_LEDGER`, `ACCEPTED_LOOKBACK_DAYS`, `review_match`, `paid_reviews`, `guard_ledger_for(ledger, earner) -> Path | None`; `Earner.topup` and `Earner.evidence` (0.23.0). +- `progress_map(day, home, key_file, *, earners=None, gate_off=()) -> + dict[str, Progress]`, `read_progress(earner, ledger, key_file, day, *, + gate_off=False) -> Progress | None`, `Progress(done, target)`, + `Earner.progress_source`, `Term.progress` (0.24.0). ## The workout ledger @@ -242,7 +230,7 @@ Unbacked timer time pays 0 from 2026-11-08 (focus_project 0.10.0). ## Install ```console -pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time" +pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time" ``` The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy` and imports from diff --git a/earned_time/earned_time/__init__.py b/earned_time/earned_time/__init__.py index 6ea1204..cf3d3e7 100644 --- a/earned_time/earned_time/__init__.py +++ b/earned_time/earned_time/__init__.py @@ -26,6 +26,10 @@ A consumer's whole integration:: gaming budget; shutdown is the only carrot. ``Resolution.gaming_enforced`` carries it; a consumer that applies a budget lifts the limit on ``False``. +``progress`` (0.24.0): a gate signs "done N of M"; ``progress_map(day, home, +key_file)`` reads it, ``resolve(..., progress=...)`` pays a no that share of a +yes (``DOCS-progress.md``). No row anywhere resolves exactly as 0.23.0. + ``sick`` (0.11.0) only raises shutdown to at least 20:00; gaming is unchanged. ``leisure`` (0.16.0): ``None`` follows the switch file on ``day``, ``True`` prices gaming with the leisure base and cap (the shadow budget), ``False`` @@ -101,6 +105,7 @@ from earned_time._policy import ( Earner, earner, ) +from earned_time._progress import Progress, progress_map, read_progress from earned_time._quota import TUTOR_QUOTA_FROM, TUTOR_QUOTA_MINUTES, tutor_quota_for from earned_time._registry import all_earners, earners_for, registries from earned_time._resolve import Base, Resolution, Term, base_for, resolve @@ -162,6 +167,7 @@ __all__ = [ "FocusEarner", "Level", "Maturity", + "Progress", "Resolution", "Rung", "Term", @@ -187,6 +193,8 @@ __all__ = [ "on_ladder", "paid_reviews", "penalty_start", + "progress_map", + "read_progress", "real_credit", "registries", "resolve", diff --git a/earned_time/earned_time/_floor.py b/earned_time/earned_time/_floor.py new file mode 100644 index 0000000..f17452f --- /dev/null +++ b/earned_time/earned_time/_floor.py @@ -0,0 +1,71 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""The floor's parts: what a penalty cuts, when it bites, the shutdown floor. + +Split from :mod:`earned_time._resolve` (0.24.0) to keep both under the line +cap; :func:`earned_time.base_for` is still defined there. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from earned_time._focus import FocusEarner +from earned_time._ladder import on_ladder, shutdown_ceiling_for +from earned_time._maturity import confirmed_start, penalty_start +from earned_time._policy import SHUTDOWN_BASE_MINUTES + +if TYPE_CHECKING: + from collections.abc import Mapping + from datetime import date + + from earned_time._policy import Earner + + +def gaming_cut(item: Earner) -> int: + """What a penalty in force takes off the gaming base: all ``item`` can pay. + + A focus earner cuts what the gates it replaced paid; it pays more (0.21.0). + """ + if isinstance(item, FocusEarner): + return item.cut_gaming_minutes + return item.max_gaming_minutes + + +def is_penalised( + item: Earner, day: date, first_credits: Mapping[str, date | None] | None +) -> bool: + """Whether ``item``'s cut is in force on ``day``. + + Without ``first_credits``: ``penalty_from`` alone, as in 0.5.0. With it: + :func:`penalty_start` of the earner's first real credit (``None`` -- never + paid out, or could not check -- is not penalised unless ``confirmed_on`` + is set: fail closed); an earner missing from it still waits for the day + after its ``confirmed_on``. + """ + if first_credits is None: + return item.penalised_on(day) + start = ( + penalty_start(item, first_credits[item.name]) + if item.name in first_credits + else confirmed_start(item) + ) + return start is not None and day >= start + + +def shutdown_floor(day: date, earners: tuple[Earner, ...], cut: list[Earner]) -> int: + """Shutdown of a day that earned nothing; ``cut``: the penalties in force. + + On the ladder: the ceiling minus the most each earner can pay (all of a + capped earner's units), so doing everything lands exactly on the ceiling + -- but only a pure bonus (no ``penalty_from``) or an earner in ``cut``: a + gate whose penalty has not started cannot lower the floor (0.6.1), nor can + a top-up (0.23.0). Before it: the old base minus the penalties in force. + """ + if on_ladder(day): + rungs = ( + e for e in earners if not e.topup and (e.penalty_from is None or e in cut) + ) + return shutdown_ceiling_for(day) - sum( + e.shutdown_for(e.max_units or 1, day) for e in rungs + ) + return SHUTDOWN_BASE_MINUTES - sum(e.shutdown_minutes for e in cut) diff --git a/earned_time/earned_time/_focus.py b/earned_time/earned_time/_focus.py index 779ea74..d54e6c3 100644 --- a/earned_time/earned_time/_focus.py +++ b/earned_time/earned_time/_focus.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Final, Protocol from earned_time._ladder import shutdown_units_minutes from earned_time._match import focus_match from earned_time._policy import Earner +from earned_time._share import share_minutes if TYPE_CHECKING: from collections.abc import Iterable @@ -53,7 +54,9 @@ class FocusEarner(Earner): def gaming_for(self, units: int) -> int: """Gaming minutes of ``units`` focused minutes, floored.""" - return self.capped(units) * self.gaming_minutes // (self.max_units or 1) + return share_minutes( + self.gaming_minutes, self.capped(units), self.max_units or 1 + ) def shutdown_for( self, @@ -62,7 +65,9 @@ class FocusEarner(Earner): ) -> int: """Shutdown minutes of ``units`` focused minutes, floored.""" del day # the base signature takes it; focus pay is the same every day - return self.capped(units) * self.shutdown_minutes // (self.max_units or 1) + return share_minutes( + self.shutdown_minutes, self.capped(units), self.max_units or 1 + ) def _active(day: date) -> _Project | None: diff --git a/earned_time/earned_time/_policy.py b/earned_time/earned_time/_policy.py index 4ddfb40..463135f 100644 --- a/earned_time/earned_time/_policy.py +++ b/earned_time/earned_time/_policy.py @@ -8,8 +8,8 @@ an hour; it asks :func:`earned_time.resolve` and applies the answer. **Penalty, then reward.** A gate with ``penalty_from`` lowers the base by exactly what it pays back, from that day on (never before the reward that pays for it: a same-day loss on 2026-09-26). Ceilings stay put. From -``LADDER_FROM`` shutdown follows the sleep ladder (:mod:`earned_time._ladder`). -The review top-up (``REVIEW``, 0.23.0) lives in :mod:`earned_time._review`. +``LADDER_FROM`` shutdown follows the sleep ladder (:mod:`earned_time._ladder`); +the review top-up (0.23.0) is in :mod:`earned_time._review`. **The registry is per day** (:func:`earners_for`). From ``TUTOR_FROM`` Anki is retired -- neither penalised nor paid -- and the tutor (``TUTOR``) is the @@ -61,24 +61,23 @@ class Earner: label: Human name, for logs and reason strings. gaming_minutes: Gaming time the first unit earns. shutdown_minutes: How much later shutdown moves for the first unit. - kind: ``"flat"`` earns once per day from a yes/no answer; - ``"counted"`` earns per unit (the workout), and its live credit is - applied by the consumer that counts the units. + kind: ``"flat"`` earns once a day from a yes/no answer; ``"counted"`` + per unit (the workout), its live credit applied by the consumer. extra_shutdown_minutes: Each further unit, for ``"counted"`` earners. extra_gaming_minutes: Gaming time each further unit earns (``"counted"``); the workout's are 0, the tutor's 1 (per minute). max_units: The most units one day can pay; ``None`` is unbounded. penalty_from: From this day the gaming base drops by the most the - earner can pay (:attr:`max_gaming_minutes`). ``None`` means a pure - bonus. - ledger: The gate's HMAC-signed ledger, relative to the home directory. - ``None`` means no shared reader: the consumer supplies the answer. + earner can pay (:attr:`max_gaming_minutes`); ``None``: a pure bonus. + ledger: The gate's HMAC-signed ledger, relative to the home directory; + ``None``: no shared reader, the consumer supplies the answer. match: Which verified ``credit`` rows count for today. missing_ledger_is_no: A ledger that does not exist yet is an honest "no" (the gate never ran), not a fault. - confirmed_on: The day kuhy confirmed a real working session; set by - hand, never derived. ``None`` keeps the gate "new" - (:func:`earned_time.maturity`). + confirmed_on: The day kuhy confirmed a real working session, by hand; + ``None`` keeps the gate "new" (:func:`earned_time.maturity`). + progress_source: ``detail.source`` of the gate's signed ``progress`` + rows (0.24.0, ``_progress``); ``None``: the yes/no answer alone. ``shutdown_minutes`` and ``extra_shutdown_minutes`` are the pre-ladder values; from ``LADDER_FROM`` the earner's :class:`Rung` in ``LADDER`` @@ -98,6 +97,7 @@ class Earner: extra_gaming_minutes: int = 0 max_units: int | None = None confirmed_on: date | None = None + progress_source: str | None = None @property def topup(self) -> bool: @@ -106,7 +106,7 @@ class Earner: @property def evidence(self) -> RowEvidence | None: - """A reader that pays from all rows instead of ``match`` (``_review``).""" + """A reader that pays from all rows instead of ``match``.""" return None def capped(self, units: int) -> int: @@ -143,13 +143,13 @@ WORKOUT: Final = Earner( shutdown_minutes=2 * 60, kind="counted", extra_shutdown_minutes=60, - # screen-locker writes one signed row per credited unit (a verified - # RunnerUp TCX, or a rest day); ``credit_units`` counts them. + # One signed row per credited unit (a verified TCX, or a rest day). ledger=".local/share/workout_locker/ledger.json", match=workout_match, missing_ledger_is_no=True, # First verified credit, read off the real ledger (0.6.0, 2026-10-09). confirmed_on=date(2026, 10, 1), + progress_source="workout", ) LEETCODE: Final = Earner( name="leetcode", @@ -160,6 +160,7 @@ LEETCODE: Final = Earner( match=leetcode_match, # First verified credit, read off the real ledger (0.6.0, 2026-10-09). confirmed_on=date(2026, 8, 12), + progress_source="leetcode", ) READING: Final = Earner( name="reading", @@ -172,6 +173,7 @@ READING: Final = Earner( missing_ledger_is_no=True, # First verified credit, read off the real ledger (0.6.0, 2026-10-09). confirmed_on=date(2026, 10, 2), + progress_source="reading", ) ANKI: Final = Earner( name="anki", @@ -183,9 +185,8 @@ ANKI: Final = Earner( match=anki_match, missing_ledger_is_no=True, ) -# Same gate, same row shape: anki-guard's ``automation`` quota (the Automation -# deck only) writes its own ledger, so the Anki day matcher applies unchanged. -# Days before ``TUTOR_FROM`` only; from then on see TUTOR. +# anki-guard's ``automation`` quota (its own ledger, same row shape): the Anki +# day matcher applies unchanged. Days before ``TUTOR_FROM`` only; then TUTOR. AUTOMATION: Final = Earner( name="automation", label="Automation", @@ -197,9 +198,8 @@ AUTOMATION: Final = Earner( missing_ledger_is_no=True, ) -# From ``TUTOR_FROM``: the tutor pays per active minute (0.8.0; a 0.7.0 -# 15-minute block row counts 15), up to 60 a day; Anki's 30 is folded in. -# Named ``automation`` until 0.9.0 (rows carry no earner name). +# From ``TUTOR_FROM``: the tutor pays per active minute (a 0.7.0 15-minute +# block row counts 15), up to 60 a day; Anki's 30 is folded in. TUTOR: Final = Earner( name="tutor", label="Tutor", @@ -214,9 +214,8 @@ TUTOR: Final = Earner( ledger=".local/share/tutor/ledger.json", match=tutor_match, missing_ledger_is_no=True, - # Confirmed by kuhy on 2026-10-10 before any block had paid out, dated the - # day before so the -60 gaming penalty applies on TUTOR_FROM itself - # (penalty starts at confirmed_on + 1). + # Confirmed 2026-10-10 before any block paid; dated a day early so the -60 + # penalty applies on TUTOR_FROM itself (it starts at confirmed_on + 1). confirmed_on=date(2026, 10, 9), ) diff --git a/earned_time/earned_time/_progress.py b/earned_time/earned_time/_progress.py new file mode 100644 index 0000000..8434a54 --- /dev/null +++ b/earned_time/earned_time/_progress.py @@ -0,0 +1,136 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""The signed progress fact (0.24.0): "done N of target M for day D". + +earned_time cannot derive a gate's plan, so each gate signs the fact in its own +ledger and this module only reads it (DOCS-progress.md). The row:: + + {"kind": "progress", "entry_id": "progress:::", + "day": "", "amount": 0, "device": ..., "created_at": ..., + "detail": {"source": , "for_day": "YYYY-MM-DD", + "done": "", "target": ""}, "hmac": ...} + +**Fail closed.** Everything but a verified, well-formed, same-day row is +``None``, and ``None`` means "pays by today's yes/no rule", never more. +Unreadable inputs are logged at warning; nothing here raises. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Final + +from earned_time._ledger import read_key, read_rows, verified +from earned_time._registry import earners_for + +if TYPE_CHECKING: + from collections.abc import Container + from datetime import date + from pathlib import Path + + from earned_time._policy import Earner + +_KIND: Final = "progress" +# Digits a count may have: far beyond any real plan, below int()'s own limit. +_MAX_DIGITS: Final = 9 + + +@dataclass(frozen=True) +class Progress: + """``done`` units of a ``target``-unit plan, as the gate signed it.""" + + done: int + target: int + + +def _count(raw: object) -> int | None: + """A count from ASCII digits only (never an int, float, sign or space).""" + if not (isinstance(raw, str) and raw.isascii() and raw.isdigit()): + return None + return int(raw) if len(raw) <= _MAX_DIGITS else None + + +def _fact(row: dict[str, object], source: str, day: date) -> Progress | None: + """One row's fact, if it is for ``source`` and ``day`` and well formed.""" + if row.get("kind") != _KIND: + return None + detail = row.get("detail") + if not isinstance(detail, dict): + return None + if detail.get("source") != source or detail.get("for_day") != day.isoformat(): + return None + done, target = _count(detail.get("done")), _count(detail.get("target")) + if done is None or not target: + return None + return Progress(min(done, target), target) + + +def read_progress( + earner: Earner, + ledger: Path, + key_file: Path, + day: date, + *, + gate_off: bool = False, +) -> Progress | None: + """``earner``'s signed progress for ``day``, or ``None``. + + Over the rows that verify and match, the largest ``done`` and the largest + ``target`` (a replay or a lost row can only lower the share, never raise + it at one target). ``None`` for: no such row, a bad signature, another day + or source, bad integers, a zero target, an unreadable ledger or key + (logged), ``gate_off`` (the gate has no price today), or an earner with no + ``progress_source``. + """ + source = earner.progress_source + if gate_off or source is None: + return None + key = read_key(key_file) + rows = None if key is None else read_rows(ledger, earner) + if key is None or rows is None: + return None + facts = [ + f + for r in rows + if isinstance(r, dict) and (f := _fact(r, source, day)) and verified(r, key) + ] + if not facts: + return None + return Progress(max(f.done for f in facts), max(f.target for f in facts)) + + +def progress_map( + day: date, + home: Path, + key_file: Path, + *, + earners: tuple[Earner, ...] | None = None, + gate_off: Container[str] = frozenset(), +) -> dict[str, Progress]: + """Every registered earner's progress on ``day``, for ``resolve(progress=)``. + + Args: + day: The day; also picks the registry (:func:`earners_for`). + home: The home the earners' ``ledger`` paths are relative to. + key_file: The shared HMAC key. + earners: A registry to read instead of ``earners_for(day)``. + gate_off: Names of the earners whose gate is off today, as the consumer + passes ``gate_off`` to ``done_today`` (they get no progress). + + Returns: + ``{earner name: Progress}``, only for earners with a fact: empty means + every term pays by its yes/no answer, exactly as in 0.23.0. + """ + found: dict[str, Progress] = {} + for item in earners_for(day) if earners is None else earners: + if item.ledger is None: + continue + fact = read_progress( + item, + home / item.ledger, + key_file, + day, + gate_off=item.name in gate_off, + ) + if fact is not None: + found[item.name] = fact + return found diff --git a/earned_time/earned_time/_resolution.py b/earned_time/earned_time/_resolution.py index c9aa65a..7e62404 100644 --- a/earned_time/earned_time/_resolution.py +++ b/earned_time/earned_time/_resolution.py @@ -14,6 +14,7 @@ if TYPE_CHECKING: from datetime import date from earned_time._policy import Earner + from earned_time._progress import Progress @dataclass(frozen=True) @@ -39,12 +40,15 @@ class Term: "could not check" (and for no answer at all). gaming_minutes: Gaming minutes earned. shutdown_minutes: Shutdown minutes earned. + progress: The signed progress the pay is a share of (0.24.0): set only + when the answer was a no and a row paid; ``None`` otherwise. """ earner: Earner answer: int | None gaming_minutes: int shutdown_minutes: int + progress: Progress | None = None @dataclass(frozen=True) diff --git a/earned_time/earned_time/_resolve.py b/earned_time/earned_time/_resolve.py index 01723f3..eb741f4 100644 --- a/earned_time/earned_time/_resolve.py +++ b/earned_time/earned_time/_resolve.py @@ -25,19 +25,21 @@ from datetime import UTC, date, datetime import logging from typing import TYPE_CHECKING, Final -from earned_time._focus import FocusEarner +from earned_time._floor import gaming_cut, is_penalised, shutdown_floor from earned_time._gaming import gaming_enforced -from earned_time._ladder import on_ladder, shutdown_ceiling_for +from earned_time._ladder import shutdown_ceiling_for from earned_time._leisure import base_minutes, ceiling_minutes, is_leisure -from earned_time._maturity import confirmed_start, penalty_start -from earned_time._policy import SHUTDOWN_BASE_MINUTES, Earner from earned_time._registry import all_earners, earners_for from earned_time._resolution import Base, Resolution, Term +from earned_time._share import gaming_share, shutdown_share from earned_time._sick import sick_or if TYPE_CHECKING: from collections.abc import Mapping + from earned_time._policy import Earner + from earned_time._progress import Progress + _logger: Final = logging.getLogger(__name__) Answer = int | bool | None @@ -47,56 +49,6 @@ def _today() -> date: return datetime.now(tz=UTC).astimezone().date() -def _gaming_cut(item: Earner) -> int: - """What a penalty in force takes off the gaming base: all ``item`` can pay. - - A focus earner cuts what the gates it replaced paid; it pays more (0.21.0). - """ - if isinstance(item, FocusEarner): - return item.cut_gaming_minutes - return item.max_gaming_minutes - - -def _penalised( - item: Earner, day: date, first_credits: Mapping[str, date | None] | None -) -> bool: - """Whether ``item``'s cut is in force on ``day``. - - Without ``first_credits``: ``penalty_from`` alone, as in 0.5.0. With it: - :func:`penalty_start` of the earner's first real credit (``None`` -- never - paid out, or could not check -- is not penalised unless ``confirmed_on`` - is set: fail closed); an earner missing from it still waits for the day - after its ``confirmed_on``. - """ - if first_credits is None: - return item.penalised_on(day) - start = ( - penalty_start(item, first_credits[item.name]) - if item.name in first_credits - else confirmed_start(item) - ) - return start is not None and day >= start - - -def _shutdown_floor(day: date, earners: tuple[Earner, ...], cut: list[Earner]) -> int: - """Shutdown of a day that earned nothing; ``cut``: the penalties in force. - - On the ladder: the ceiling minus the most each earner can pay (all of a - capped earner's units), so doing everything lands exactly on the ceiling - -- but only a pure bonus (no ``penalty_from``) or an earner in ``cut``: a - gate whose penalty has not started cannot lower the floor (0.6.1), nor can - a top-up (0.23.0). Before it: the old base minus the penalties in force. - """ - if on_ladder(day): - rungs = ( - e for e in earners if not e.topup and (e.penalty_from is None or e in cut) - ) - return shutdown_ceiling_for(day) - sum( - e.shutdown_for(e.max_units or 1, day) for e in rungs - ) - return SHUTDOWN_BASE_MINUTES - sum(e.shutdown_minutes for e in cut) - - def base_for( day: date | None = None, earners: tuple[Earner, ...] | None = None, @@ -107,7 +59,7 @@ def base_for( """The floor for ``day`` (default today) under ``earners`` (default its own). Gaming: every penalty in force, the most each earner can pay, taken off - the gaming base. Shutdown: see :func:`_shutdown_floor` -- the two are + the gaming base. Shutdown: see ``_floor.shutdown_floor`` -- the two are derived separately so the ladder can never move a gaming minute. ``first_credits`` (per earner name) delays each penalty, and the ladder rung, to :func:`penalty_start`; omitted, 0.5.0's ``penalty_from`` applies. @@ -128,11 +80,10 @@ def _base( *, on: bool, ) -> Base: - penalised = [e for e in registry if _penalised(e, target, first_credits)] + penalised = [e for e in registry if is_penalised(e, target, first_credits)] return Base( - gaming_minutes=base_minutes(leisure=on) - - sum(_gaming_cut(e) for e in penalised), - shutdown_minutes=_shutdown_floor(target, registry, penalised), + gaming_minutes=base_minutes(leisure=on) - sum(gaming_cut(e) for e in penalised), + shutdown_minutes=shutdown_floor(target, registry, penalised), ) @@ -153,13 +104,32 @@ def _check_registered( raise KeyError(msg) -def _term(item: Earner, answers: Mapping[str, Answer], day: date) -> Term: - """``item``'s term on ``day``; no answer at all is logged and earns nothing.""" +def _term( + item: Earner, + answers: Mapping[str, Answer], + day: date, + progress: Mapping[str, Progress] | None, +) -> Term: + """``item``'s term on ``day``; no answer at all is logged and earns nothing. + + Progress pays only a no (``0``/``False``): a yes pays in full as ever and + ``None`` ("could not check") earns nothing, row or no row. + """ if item.name not in answers: _logger.warning( "No answer for the %s earner; it earns nothing today", item.label ) units = _units(answers.get(item.name)) + no = units is not None and units < 1 + share = (progress or {}).get(item.name) if no else None + if share is not None: + return Term( + item, + units, + gaming_share(item, share), + shutdown_share(item, share, day), + share, + ) count = units or 0 return Term( earner=item, @@ -177,6 +147,7 @@ def resolve( first_credits: Mapping[str, date | None] | None = None, sick: bool = False, leisure: bool | None = None, + progress: Mapping[str, Progress] | None = None, ) -> Resolution: """Sum the base and every earned term, each capped at its ceiling. @@ -205,6 +176,10 @@ def resolve( shutdown are unchanged. From ``GAMING_UNLIMITED_FROM`` (0.22.0) ``None`` is always the old base: read ``Resolution.gaming_enforced``, the budget is not a limit. + progress: Per earner name, its signed progress (0.24.0, + :func:`~earned_time.progress_map`). A term uses it only when its + answer is ``0``/``False``, and then pays that share of a yes; a + true answer pays full and ``None`` nothing. Omitted: 0.23.0 exactly. Returns: The resolution, with a term for every registered earner. @@ -219,7 +194,7 @@ def resolve( # One switch-file read per resolve, so base and cap can never disagree. on = is_leisure(target, leisure=leisure) base = _base(target, registry, first_credits, on=on) - terms = [_term(item, answers, target) for item in registry] + terms = [_term(item, answers, target, progress) for item in registry] gaming = base.gaming_minutes + sum(t.gaming_minutes for t in terms) earned = min( shutdown_ceiling_for(target), diff --git a/earned_time/earned_time/_review.py b/earned_time/earned_time/_review.py index 1443599..2217f6f 100644 --- a/earned_time/earned_time/_review.py +++ b/earned_time/earned_time/_review.py @@ -243,4 +243,5 @@ REVIEW: Final = ReviewEarner( ledger=REVIEW_LEDGER, match=review_match, missing_ledger_is_no=True, + progress_source="review", ) diff --git a/earned_time/earned_time/_share.py b/earned_time/earned_time/_share.py new file mode 100644 index 0000000..444d498 --- /dev/null +++ b/earned_time/earned_time/_share.py @@ -0,0 +1,45 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""Proportional pay (0.24.0): ``done`` of ``target`` units pays that share. + +Equal slices, floored, nothing held back (kuhy, 2026-11-22: "50% of pages you +get 50% of bonus"). One piece of arithmetic for every earner that pays by +share: the focus earner's minutes and the gates' signed progress alike. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from earned_time._ladder import shutdown_minutes_for + +if TYPE_CHECKING: + from datetime import date + + from earned_time._policy import Earner + from earned_time._progress import Progress + + +def share_minutes(full: int, done: int, target: int) -> int: + """``full * done // target``, ``done`` clamped to ``[0, target]``. + + A ``target`` below 1 has no share to pay: ``0``, never a division error. + """ + if target < 1: + return 0 + return full * min(max(done, 0), target) // target + + +def gaming_share(item: Earner, progress: Progress) -> int: + """The gaming minutes ``progress`` earns ``item``: a share of its first unit.""" + return share_minutes(item.gaming_for(1), progress.done, progress.target) + + +def shutdown_share(item: Earner, progress: Progress, day: date) -> int: + """The shutdown minutes ``progress`` earns ``item`` on ``day``. + + A share of what :func:`~earned_time.shutdown_minutes_for` says a yes pays + that day, so the ladder rung (not the pre-ladder number) is what is split. + """ + return share_minutes( + shutdown_minutes_for(item, day), progress.done, progress.target + ) diff --git a/earned_time/earned_time/tests/_golden_0_23_0.json b/earned_time/earned_time/tests/_golden_0_23_0.json new file mode 100644 index 0000000..b5b517e --- /dev/null +++ b/earned_time/earned_time/tests/_golden_0_23_0.json @@ -0,0 +1,118 @@ +{ + "default|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5", + "default|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8", + "default|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497", + "default|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f", + "default|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3", + "default|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b", + "default|2026-10-09": "1035a892e1dc16b4857d455a51ecc1e9ad2544ff196e2fb2f0c923155ea9269c", + "default|2026-10-10": "20621ebccd4ac601d85acc22f07126fe566103b5b19967116991a9289991d6b7", + "default|2026-10-17": "590d3ec70bf86126cab0344beb8be26a0c4b6370119375095fd7c363c13f6470", + "default|2026-10-18": "3d896c49e432f4f084da7e641a7ad6b41b62a583f587c3047a112ae4dc554372", + "default|2026-11-01": "fa00273b89a31779a1984941eb7d982e40970be8c440e93c38bcb2117d52d36d", + "default|2026-11-08": "82ff6c26f6d0c354852f8c3e7c0b3a28f0bc7fbd33af001b992b6c374b937ed4", + "default|2026-11-14": "95bbfcb5bf25f9f49f8487efad5cbb52cce9282251f283f54d3266647a24e6fa", + "default|2026-11-15": "de061cd23f3aca9e5683f7407be497bcb635d63e39c2c521206ef51874531e45", + "default|2026-11-16": "f9f4203012c609f443a555a54a992bdb49bab735ab9cbdb5dd2038458e038283", + "default|2026-11-17": "416630114779c76670126c8b72e9cd58f4b7b72f20c6481fbd6ac4034e9b72e4", + "default|2026-11-18": "71d8dba9daa713f36eb39dd8cb0da68dd41b6e92fd0b26bc7ce4f9f1513daac4", + "default|2026-11-19": "89de5b7902c05a1fe76803606d5dd427af26de0574fa9478c3741de7ac4f9f5e", + "default|2026-11-20": "43f2bcc8ed42ee51a2709be1ca5e538d8f3aac7d390279f540f95ee17af9473e", + "default|2026-11-21": "39fd48906c41982b4cbf1508c19680e13296e11135586cae7bb5bfd003d271da", + "default|2026-11-22": "90442925d88982f99ac7cf13256d33d677f8e43d73d1c680a5f99b37d2ddbcb7", + "default|2026-11-23": "6606c5fbd9b5e74431a6a9ba6b58f09ca1c71eb1c37e960d68cbd65b075617f3", + "default|2026-11-24": "0fab42a2f77a5f2bb821263b4e518274d3e674747654ca8a1bb22aac862e3e5d", + "default|2026-11-25": "17db03c1e31139f0b3dbbfa958e41367404853e90ed79a9c88feef427507ac12", + "default|2026-11-26": "fb390158553c04ad578667f1564e5fd6ebba8e2b23f5df04bd35b77fc3e1f85c", + "default|2026-11-27": "a45fc6e3b6c14a9bdfbf80f262f5d33b025965ff93803f60e959a18bc959cde4", + "default|2026-12-25": "c59ddad74c85b8e5169e4ba4ffae26c89cfe94732c701df45ed1d9babd0c0a64", + "default|2027-01-01": "2db1833cec98ff85dc0e3ff808c9ef193e42af23ffc9913a689d60e63fc4c387", + "default|2027-01-02": "f27171dbcb0afed62c3c3dea013fbfb5c3b3baeb56eadf734e6ad0b4b1cdc972", + "focus|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5", + "focus|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8", + "focus|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497", + "focus|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f", + "focus|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3", + "focus|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b", + "focus|2026-10-09": "1035a892e1dc16b4857d455a51ecc1e9ad2544ff196e2fb2f0c923155ea9269c", + "focus|2026-10-10": "bd737f83f7fa5e4102f7569b3a7fb812eaa0bcf40962f8574c3113e340a79e70", + "focus|2026-10-17": "c7ff06df21447e99a5b294518dfd5894daa0849eb3070ea3410a6bf2bd484111", + "focus|2026-10-18": "123a39d01c7357dec4619727b2bf73c26b124a474dc617941846b5215bd06cc5", + "focus|2026-11-01": "ecdc41b29f7f9080786cb381b635741d59986809dd0704f30883fa332ded4360", + "focus|2026-11-08": "6f04e00b4d78fc09ab04f30be5be5183e8027bf8c9fcc13f59a1538bbdee2b3b", + "focus|2026-11-14": "3a4f25853003afce725ba6fad82b70c3215f5f6b4e1c5cf8d30bc9ac56244fa0", + "focus|2026-11-15": "16ace51d54a9061bf46774f1e68bc6645368e5a840be7e7872564dc29e6465c0", + "focus|2026-11-16": "bf6f84c43b9151df924e256bc3428bb9bbb89d3955f53bad4805280370b09a2a", + "focus|2026-11-17": "266ea63e52649e8c99f0303cd4b62822d9bb959f11c70b164d1c0b269a89f5ea", + "focus|2026-11-18": "80810b3477afa7d451602bf6c069bc2b6e5899554f1860098f581051f6d6dc2a", + "focus|2026-11-19": "db9eee4e86164768f3490ea87f3227b8a650dcc5115e8f6c2343314bbd6ce3a5", + "focus|2026-11-20": "19ad7d5b809ff2e45b24c0210c7d646685c9603a6571f910f0164841f5602c37", + "focus|2026-11-21": "601f04bbd20441e3e6698a34f8ae33e010f8500123a1df6870d8582f7d64e447", + "focus|2026-11-22": "9c8817239021615b856eca46d84af0b62cf4a35285857aa959700b004ac4f45e", + "focus|2026-11-23": "e9404c84795b66c5b17728feb99e4570820e17cbffcb4d11a081cfa4e20521d9", + "focus|2026-11-24": "61825a9809de16d8bf59e2e70cc9d7f0944ba763cd8ea6559e7ea84eee991475", + "focus|2026-11-25": "b3fa9185f5dee9df052186a4a68afe1d996f0e9706e2de1625a5317130bc5059", + "focus|2026-11-26": "8019bcfb6b4c34882f13a25cc51e50a3938f32411a9c9f7137815be7e84157d7", + "focus|2026-11-27": "31795afe07f6b6a88baaf89f3812ac6394a869aa034ea7e505bd99706401e636", + "focus|2026-12-25": "db50479ffa793c333baa983cb4753d72cc4247f81542dd9948c3a72779ce0c53", + "focus|2027-01-01": "e902b44a24ac77e50789b0d460c095e6763ca508797ad2731708fa14f7a5d384", + "focus|2027-01-02": "ad21a2539e50303a3c28f329bcd19aa1b3cdc88d01a25de721c92096dae1ce99", + "legacy|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5", + "legacy|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8", + "legacy|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497", + "legacy|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f", + "legacy|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3", + "legacy|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b", + "legacy|2026-10-09": "2b5fb5c0f9bf3a4631c80ae2efb2cdc594763ec570cc094704ae2739cf3df150", + "legacy|2026-10-10": "cbc35da122acec19a7eee1ab0e37fa70924ff39b8ded4e0b7e4d7fd8c2cbe459", + "legacy|2026-10-17": "d687d087d85206e909b8b2deb466abf673147df23b428eeeebd38a7ae2ac59ad", + "legacy|2026-10-18": "4514f9d56c4a811724ba9713773e13a2af5074819ad20a1c3a79261dfb21e242", + "legacy|2026-11-01": "61a3161ddd39183f4951aae7b6918ab4e0ccf9462391a9e3c752c5adb9b081d5", + "legacy|2026-11-08": "34e0d74573b635f080299a072fc11456fd9448ab420f2a15b8cf9b85d83434b9", + "legacy|2026-11-14": "520bf1f006cafe0314ecb66e8ff2efcee5d333a2460c5a106c48d473c97b4b80", + "legacy|2026-11-15": "128309ec209bea89907880b4917adaeff4349df297789adf46cdec1dd365c0f8", + "legacy|2026-11-16": "2fe908c5f4f5e3dea92e53f88adbc5c44292b23f6166d8d2211657be543592cc", + "legacy|2026-11-17": "68a378804b51e74f93eb8e9cea737f17bafaf4d8b3582bbb0cda1f587183a39c", + "legacy|2026-11-18": "f8638a6b302d430813afe1500ee2d1c583deb5fb3710bca201f2551e5868b09d", + "legacy|2026-11-19": "23f219575fcc0227a3065d972b5f5777d02867f8b7d1722f7480496c21281fcb", + "legacy|2026-11-20": "83405fea6c8bd58a9756a027207edcd2f9cda37253a36ecda771ce375c469d9e", + "legacy|2026-11-21": "ccefec48376ec2983f70b48eefb03bf4c7858dd5ecf89d6ea68c6caf4eebce52", + "legacy|2026-11-22": "74fa20db1b9ad54034ae331e8e383afe49cd325c9c0c2123e41ad81188ed6704", + "legacy|2026-11-23": "b280ae281fc74d0ff3c6cca3ac720b39f16f286711ce0558d7bd9cd666064514", + "legacy|2026-11-24": "d10b1c62a9b3108601375b51bcb19a6171e404b4d787a724ce7819aba9dee127", + "legacy|2026-11-25": "0dd2c361c31809bb7ad45db247bd87c11858e2baaa0c76e307f17b5799c06cc4", + "legacy|2026-11-26": "ab64833e0624ab99018d4d947ec6a07d59f515b6f7ca71b5d82b66eeb6df60a8", + "legacy|2026-11-27": "3f115a8b773aac85f714b36aae4fdb988d1d939a81d5c7d9474c2d0825092774", + "legacy|2026-12-25": "351426011def5d7f18c1605ec9baa549dcce76a2c5f360f7598330b71d38313d", + "legacy|2027-01-01": "d8a36c6bea32939787ba42144cc4e8eb2eb7837e109f5efd649f3e877f9f954e", + "legacy|2027-01-02": "fb7b2bee44f6a2c32f38ef7b911e1cee4ca8dd6d78fba626c1724b3ab78b81ec", + "tutor|2026-09-25": "20bef4cc33e99150b682c1d95b875c9cfd28f91ceee98e1ef535b836c3c4f52f", + "tutor|2026-09-26": "63d8533206bd4f0bf5cbcfae1f2616415a761ec47517bd886354ec423d9833c1", + "tutor|2026-10-01": "5e77e89e108d380d50aa0cc18cf8959c9531bb653c378f969bbebcb68e7b43cc", + "tutor|2026-10-05": "e552a8f912ffaf3ac701bc6c43bd793a35bfe12d222e00120ac6aa77e1e81762", + "tutor|2026-10-06": "696c340c5c86e107439f6dc3fbe61bea226f2593f31f0a5785f0822e395493e3", + "tutor|2026-10-08": "c49cb68a23e92411738664e4010c7f7870b0e14bf7a8e56bce82a637b9ce62c5", + "tutor|2026-10-09": "ac727597998ffca9f78fe122546f1d4e3caaa9b71161b061137b469cc536ba67", + "tutor|2026-10-10": "20621ebccd4ac601d85acc22f07126fe566103b5b19967116991a9289991d6b7", + "tutor|2026-10-17": "590d3ec70bf86126cab0344beb8be26a0c4b6370119375095fd7c363c13f6470", + "tutor|2026-10-18": "3d896c49e432f4f084da7e641a7ad6b41b62a583f587c3047a112ae4dc554372", + "tutor|2026-11-01": "fa00273b89a31779a1984941eb7d982e40970be8c440e93c38bcb2117d52d36d", + "tutor|2026-11-08": "82ff6c26f6d0c354852f8c3e7c0b3a28f0bc7fbd33af001b992b6c374b937ed4", + "tutor|2026-11-14": "95bbfcb5bf25f9f49f8487efad5cbb52cce9282251f283f54d3266647a24e6fa", + "tutor|2026-11-15": "de061cd23f3aca9e5683f7407be497bcb635d63e39c2c521206ef51874531e45", + "tutor|2026-11-16": "f9f4203012c609f443a555a54a992bdb49bab735ab9cbdb5dd2038458e038283", + "tutor|2026-11-17": "416630114779c76670126c8b72e9cd58f4b7b72f20c6481fbd6ac4034e9b72e4", + "tutor|2026-11-18": "71d8dba9daa713f36eb39dd8cb0da68dd41b6e92fd0b26bc7ce4f9f1513daac4", + "tutor|2026-11-19": "89de5b7902c05a1fe76803606d5dd427af26de0574fa9478c3741de7ac4f9f5e", + "tutor|2026-11-20": "43f2bcc8ed42ee51a2709be1ca5e538d8f3aac7d390279f540f95ee17af9473e", + "tutor|2026-11-21": "39fd48906c41982b4cbf1508c19680e13296e11135586cae7bb5bfd003d271da", + "tutor|2026-11-22": "90442925d88982f99ac7cf13256d33d677f8e43d73d1c680a5f99b37d2ddbcb7", + "tutor|2026-11-23": "6679f84c03a5fe1aaf32dc17f70a2dc80a47212deb980d9d3b5179b8448007c6", + "tutor|2026-11-24": "4959850db79e70ebe57b4fa02d278367c0da6f0acf3f9025804bdfa6912b1b6f", + "tutor|2026-11-25": "047a58fcacabdeecf6807aa9425cd01bf10f1bf9e81787894031597647f16bd2", + "tutor|2026-11-26": "51bfd3b993519a766dc80b970619318955f27d739b14220f59e8af060c8380a0", + "tutor|2026-11-27": "5382d19c7635caa6b285de2820baf70df320f42764e282eb57267340afaad471", + "tutor|2026-12-25": "786053a1c98d38984ee5a8a4d6140f6f5e0d38f53df4f1ee09ef1e9569693442", + "tutor|2027-01-01": "af65fe00513b98a604671a3980085bbcfaffb9365e35c5594357829f671c5bc1", + "tutor|2027-01-02": "699ab7775e270d33585fb01ede7596834a39e4aac4b2d53156e47b1fcdb99436" +} diff --git a/earned_time/earned_time/tests/_grid_dump.py b/earned_time/earned_time/tests/_grid_dump.py new file mode 100644 index 0000000..9800a1a --- /dev/null +++ b/earned_time/earned_time/tests/_grid_dump.py @@ -0,0 +1,117 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""One digest per (registry, day) of everything ``resolve`` answers. + +Standalone on purpose: it imports only ``earned_time``, so the same file runs +in-process against the working tree and, as ``python -P _grid_dump.py`` from +another directory, against whatever ``earned_time`` the interpreter installed +(the 0.23.0 oracle of ``test_progress_dark``). It touches no live state: the +leisure switch file and the focus project are stood in for. +""" + +from __future__ import annotations + +from datetime import date, timedelta +import hashlib +import itertools +import json +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +from types import SimpleNamespace + +import earned_time + +FOCUS = SimpleNamespace( + start=date(2026, 11, 1), daily_minutes=120, replaces=("book", "leetcode") +) +# Around every dated switch: the ladder, the tutor, the waiver, unified pay, +# the focus start, no gaming budget, the review top-up, the parked leisure day. +SPOTS = ( + date(2026, 9, 25), + date(2026, 9, 26), + date(2026, 10, 1), + date(2026, 10, 5), + date(2026, 10, 6), + date(2026, 10, 8), + date(2026, 10, 9), + date(2026, 10, 10), + date(2026, 10, 17), + date(2026, 10, 18), + date(2026, 11, 1), + date(2026, 11, 8), + date(2026, 11, 15), + date(2026, 11, 16), + date(2026, 11, 22), + date(2026, 11, 23), + date(2026, 11, 24), + date(2026, 12, 25), + date(2027, 1, 1), + date(2027, 1, 2), +) +DAYS = tuple( + sorted({*SPOTS, *(date(2026, 11, 14) + timedelta(days=n) for n in range(14))}) +) +OPTIONS: tuple[int | None, ...] = (None, 0, 1, 60) + + +def _registry(mode: str, day: date) -> tuple[earned_time.Earner, ...]: + if mode == "legacy": + return earned_time.EARNERS + if mode == "tutor": + return earned_time.TUTOR_EARNERS + return earned_time.earners_for(day) + + +def _lines(mode: str, day: date, extra: dict[str, object]) -> list[str]: + registry = _registry(mode, day) + names = [e.name for e in registry] + explicit = None if mode == "default" else registry + out = [repr(earned_time.base_for(day, explicit))] + for values in itertools.product(OPTIONS, repeat=len(names)): + answers = dict(zip(names, values, strict=True)) + for sick, leisure in ((False, None), (True, None), (False, True)): + res = earned_time.resolve( + answers, day, explicit, sick=sick, leisure=leisure, **extra + ) + terms = [ + (t.earner.name, t.answer, t.gaming_minutes, t.shutdown_minutes) + for t in res.terms + ] + out.append( + repr( + ( + res.day, + res.base, + terms, + res.gaming_minutes, + res.shutdown_minutes, + res.sick, + res.sick_lift_minutes, + res.gaming_enforced, + ) + ) + ) + return out + + +def dump(**extra: object) -> dict[str, str]: + """``"mode|day"`` -> sha256 of every resolution of that registry and day. + + ``extra`` is passed to every ``resolve`` (the new ``progress=``). + """ + digests: dict[str, str] = {} + with TemporaryDirectory() as tmp: + earned_time._leisure.LEISURE_FROM_PATH = Path(tmp) / "missing" + for mode in ("default", "legacy", "tutor", "focus"): + sys.modules["focus_project"] = SimpleNamespace( + active=lambda _d, on=mode == "focus": FOCUS if on else None + ) + for day in DAYS: + name = "default" if mode == "focus" else mode + body = "\n".join(_lines(name, day, extra)) + digests[f"{mode}|{day}"] = hashlib.sha256(body.encode()).hexdigest() + return digests + + +if __name__ == "__main__": + sys.stdout.write(json.dumps(dump(), indent=0, sort_keys=True) + "\n") diff --git a/earned_time/earned_time/tests/_progress_rows.py b/earned_time/earned_time/tests/_progress_rows.py new file mode 100644 index 0000000..85edefa --- /dev/null +++ b/earned_time/earned_time/tests/_progress_rows.py @@ -0,0 +1,65 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""Signed ``progress`` rows and ledger files for the partial-pay tests.""" + +from __future__ import annotations + +from datetime import date +import json +from typing import TYPE_CHECKING + +from earned_time.tests._maturity_rows import signed + +if TYPE_CHECKING: + from pathlib import Path + + from earned_time import Earner + +# A day on the unified ladder, with the review top-up registered. +DAY = date(2026, 11, 24) + + +def progress( + source: str = "leetcode", + done: object = "1", + target: object = "3", + day: date = DAY, + **detail: object, +) -> dict[str, object]: + """One signed progress row, exactly as the gates write it.""" + fields: dict[str, object] = { + "source": source, + "for_day": day.isoformat(), + "done": done, + "target": target, + **detail, + } + return signed( + { + "kind": "progress", + "entry_id": f"progress:{day.isoformat()}:{done}:{target}", + "day": day.isoformat(), + "amount": 0, + "device": "pc", + "created_at": f"{day.isoformat()}T12:00:00+00:00", + "detail": fields, + } + ) + + +def write(path: Path, rows: list[object]) -> Path: + """A ledger file at ``path`` holding ``rows``.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"entries": rows}), encoding="utf-8") + return path + + +def home_ledger(home: Path, earner: Earner) -> Path: + """Where a consumer finds ``earner``'s ledger under ``home``.""" + return home / str(earner.ledger) + + +def tampered(row: dict[str, object], **detail: object) -> dict[str, object]: + """``row`` with its detail edited after signing (the old HMAC kept).""" + old = row["detail"] + assert isinstance(old, dict) + return {**row, "detail": {**old, **detail}} diff --git a/earned_time/earned_time/tests/test_progress_dark.py b/earned_time/earned_time/tests/test_progress_dark.py new file mode 100644 index 0000000..817c032 --- /dev/null +++ b/earned_time/earned_time/tests/test_progress_dark.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""Dark by default: with no progress row every answer is 0.23.0's, bit for bit. + +``_golden_0_23_0.json`` pins a digest per (registry, day) of every resolution +over a grid of answers, sick and leisure switches, produced by 0.23.0 itself +(``_grid_dump.py``). The live oracle re-derives it from an installed 0.23.0 +when the interpreter has one, in a subprocess so ``sys.path`` stays untouched. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from earned_time.tests._grid_dump import dump + +HERE = Path(__file__).parent +GOLDEN = json.loads((HERE / "_golden_0_23_0.json").read_text(encoding="utf-8")) +OLD = "0.23.0" + + +def _differing(got: dict[str, str]) -> list[str]: + return sorted(k for k in GOLDEN if got.get(k) != GOLDEN[k]) + sorted( + set(got) - set(GOLDEN) + ) + + +def test_no_progress_resolve_equals_the_0_23_0_result_for_every_registry() -> None: + assert _differing(dump()) == [] + + +def test_an_empty_progress_map_resolves_as_no_map() -> None: + assert _differing(dump(progress={})) == [] + assert _differing(dump(progress=None)) == [] + + +def test_the_installed_0_23_0_agrees_with_the_pin(tmp_path: Path) -> None: + env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"} + probe = subprocess.run( + [ + sys.executable, + "-P", + "-c", + "import importlib.metadata as m; print(m.version('earned-time'))", + ], + capture_output=True, + text=True, + check=False, + cwd=tmp_path, + env=env, + ) + if probe.stdout.strip() != OLD: + pytest.skip(f"no installed earned-time {OLD} to ask") + oracle = subprocess.run( + [sys.executable, "-P", str(HERE / "_grid_dump.py")], + capture_output=True, + text=True, + check=True, + cwd=tmp_path, + env=env, + ) + assert json.loads(oracle.stdout) == GOLDEN diff --git a/earned_time/earned_time/tests/test_progress_read.py b/earned_time/earned_time/tests/test_progress_read.py new file mode 100644 index 0000000..b3961ba --- /dev/null +++ b/earned_time/earned_time/tests/test_progress_read.py @@ -0,0 +1,224 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""The progress reader: one signed fact, every other state is ``None``.""" + +from __future__ import annotations + +from datetime import timedelta +from itertools import combinations +import logging +from typing import TYPE_CHECKING + +import pytest + +from earned_time import ( + LEETCODE, + READING, + REVIEW, + TUTOR, + WORKOUT, + Earner, + Progress, + entry_signature, + progress_map, + read_progress, +) +from earned_time.tests._maturity_rows import KEY +from earned_time.tests._progress_rows import ( + DAY, + home_ledger, + progress, + tampered, + write, +) + +if TYPE_CHECKING: + from collections.abc import Callable + from pathlib import Path + + Reader = Callable[..., Progress | None] + + +@pytest.fixture +def read(tmp_path: Path, key_file: Path) -> Reader: + """Read LeetCode progress for ``DAY`` out of a ledger holding ``rows``.""" + + def reader(rows: list[object], *, gate_off: bool = False) -> Progress | None: + ledger = write(tmp_path / "ledger.json", rows) + return read_progress(LEETCODE, ledger, key_file, DAY, gate_off=gate_off) + + return reader + + +def test_a_signed_matching_row_reads_as_progress(read: Reader) -> None: + assert read([progress(done="1", target="3")]) == Progress(1, 3) + + +def test_no_row_reads_as_none(read: Reader) -> None: + assert read([]) is None + + +def test_a_credit_row_is_not_progress(read: Reader) -> None: + row = {**progress(), "kind": "credit"} + assert read([{**row, "hmac": entry_signature(row, KEY)}]) is None + + +def test_a_wrong_day_row_reads_as_none(read: Reader) -> None: + assert read([progress(day=DAY - timedelta(days=1))]) is None + assert read([progress(day=DAY + timedelta(days=1))]) is None + + +def test_another_gates_source_reads_as_none(read: Reader) -> None: + assert read([progress(source="reading")]) is None + + +def test_an_unsigned_row_reads_as_none(read: Reader) -> None: + row = progress() + del row["hmac"] + assert read([row]) is None + + +def test_an_edited_row_reads_as_none(read: Reader) -> None: + assert read([tampered(progress(done="1", target="3"), done="3")]) is None + + +def test_a_row_signed_with_another_key_reads_as_none(read: Reader) -> None: + row = progress() + row["hmac"] = entry_signature(row, b"someone else") + assert read([row]) is None + + +ARABIC_ONE = chr(0x661) +ARABIC_THREE = chr(0x663) + + +@pytest.mark.parametrize( + "bad", + [1, 1.0, True, None, "", " 1", "1 ", "+1", "-1", "1.0", "1e1", "0x1", ARABIC_ONE], +) +def test_done_must_be_ascii_digits(read: Reader, bad: object) -> None: + assert read([progress(done=bad, target="3")]) is None + + +@pytest.mark.parametrize( + "bad", + [3, 3.0, True, None, "", " 3", "3 ", "+3", "-3", "3.0", "0", "00", ARABIC_THREE], +) +def test_target_must_be_ascii_digits_and_positive(read: Reader, bad: object) -> None: + assert read([progress(done="1", target=bad)]) is None + + +def test_absurdly_long_digit_strings_read_as_none(read: Reader) -> None: + assert read([progress(done="1", target="9" * 5000)]) is None + + +def test_done_over_target_is_capped(read: Reader) -> None: + assert read([progress(done="7", target="3")]) == Progress(3, 3) + + +def test_zero_done_is_a_valid_zero(read: Reader) -> None: + assert read([progress(done="0", target="3")]) == Progress(0, 3) + + +def test_the_max_done_and_the_max_target_win(read: Reader) -> None: + rows = [progress(done="1", target="3"), progress(done="2", target="4")] + assert read(rows) == Progress(2, 4) + assert read(rows[::-1]) == Progress(2, 4) + + +def test_a_bad_row_beside_a_good_one_is_ignored(read: Reader) -> None: + rows = [progress(done="x", target="3"), progress(done="2", target="3")] + assert read(rows) == Progress(2, 3) + + +def test_gate_off_ignores_progress(read: Reader) -> None: + assert read([progress()], gate_off=True) is None + assert read([progress()], gate_off=False) == Progress(1, 3) + + +def test_an_earner_without_a_progress_source_reads_as_none( + tmp_path: Path, key_file: Path +) -> None: + ledger = write(tmp_path / "t.json", [progress(source="tutor")]) + assert TUTOR.progress_source is None + assert read_progress(TUTOR, ledger, key_file, DAY) is None + + +def test_every_gate_with_a_fact_names_its_source() -> None: + sources = {e.name: e.progress_source for e in (WORKOUT, LEETCODE, READING, REVIEW)} + assert sources == { + "workout": "workout", + "leetcode": "leetcode", + "reading": "reading", + "review": "review", + } + + +def test_an_unreadable_key_reads_as_none_and_is_logged( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + ledger = write(tmp_path / "ledger.json", [progress()]) + with caplog.at_level(logging.WARNING): + assert read_progress(LEETCODE, ledger, tmp_path / "no.key", DAY) is None + assert "integrity key" in caplog.text + + +def test_an_unreadable_ledger_reads_as_none_and_is_logged( + tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture +) -> None: + bad = tmp_path / "ledger.json" + bad.write_text("not json", encoding="utf-8") + with caplog.at_level(logging.WARNING): + assert read_progress(LEETCODE, bad, key_file, DAY) is None + assert "not valid JSON" in caplog.text + + +def test_a_missing_ledger_reads_as_none(tmp_path: Path, key_file: Path) -> None: + assert read_progress(READING, tmp_path / "gone.json", key_file, DAY) is None + + +def test_deleting_rows_never_raises_the_share_at_one_target(read: Reader) -> None: + rows: list[object] = [progress(done=str(n), target="5") for n in (0, 1, 2, 4, 5)] + full = read(rows) + assert full == Progress(5, 5) + for size in range(len(rows) + 1): + for kept in combinations(rows, size): + got = read(list(kept)) + assert got is None or got.done <= full.done + + +def test_progress_map_holds_only_earners_with_a_fact( + tmp_path: Path, key_file: Path +) -> None: + write( + home_ledger(tmp_path, WORKOUT), + [progress(source="workout", done="1", target="2")], + ) + write(home_ledger(tmp_path, LEETCODE), [progress(done="2", target="3")]) + found = progress_map(DAY, tmp_path, key_file) + assert found == {"workout": Progress(1, 2), "leetcode": Progress(2, 3)} + + +def test_progress_map_skips_a_gate_that_is_off(tmp_path: Path, key_file: Path) -> None: + write(home_ledger(tmp_path, LEETCODE), [progress()]) + assert progress_map(DAY, tmp_path, key_file, gate_off={"leetcode"}) == {} + + +def test_progress_map_over_an_explicit_registry(tmp_path: Path, key_file: Path) -> None: + write(home_ledger(tmp_path, LEETCODE), [progress()]) + assert progress_map(DAY, tmp_path, key_file, earners=(WORKOUT,)) == {} + assert progress_map(DAY, tmp_path, key_file, earners=(LEETCODE,)) == { + "leetcode": Progress(1, 3) + } + + +def test_a_row_without_a_detail_object_reads_as_none(read: Reader) -> None: + for junk in (None, "x", ["done"]): + row = {**progress(), "detail": junk} + assert read([{**row, "hmac": entry_signature(row, KEY)}, 7, "x"]) is None + + +def test_progress_map_skips_an_earner_with_no_ledger( + tmp_path: Path, key_file: Path +) -> None: + bare = Earner(name="bare", label="bare", gaming_minutes=1, shutdown_minutes=1) + assert progress_map(DAY, tmp_path, key_file, earners=(bare,)) == {} diff --git a/earned_time/earned_time/tests/test_progress_resolve.py b/earned_time/earned_time/tests/test_progress_resolve.py new file mode 100644 index 0000000..4684495 --- /dev/null +++ b/earned_time/earned_time/tests/test_progress_resolve.py @@ -0,0 +1,227 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""Partial pay: a share of the full pay for a no, never more than a yes.""" + +from __future__ import annotations + +from datetime import date, datetime, time +from itertools import product +from typing import TYPE_CHECKING + +import pytest + +from earned_time import ( + LEETCODE, + REVIEW, + Earner, + FocusEarner, + Progress, + credit_units, + done_today, + maturity, + progress_map, + resolve, + shutdown_minutes_for, +) +from earned_time._share import share_minutes +from earned_time.tests._maturity_rows import solve +from earned_time.tests._progress_rows import DAY, home_ledger, progress, write + +if TYPE_CHECKING: + from pathlib import Path + +# A day on the unified ladder: LeetCode pays 60 and shuts down 60 later. +LADDER = date(2026, 11, 22) +NOTHING: dict[str, int | bool | None] = { + "workout": 0, + "leetcode": False, + "reading": False, + "tutor": 0, +} + + +def test_sixty_times_one_over_three_is_twenty_through_resolve() -> None: + day = resolve(NOTHING, LADDER, progress={"leetcode": Progress(1, 3)}) + term = day.term("leetcode") + assert (term.gaming_minutes, term.shutdown_minutes) == (20, 20) + assert day.shutdown_minutes == resolve(NOTHING, LADDER).shutdown_minutes + 20 + + +def test_a_true_answer_pays_full_whatever_the_row_says() -> None: + answers = {**NOTHING, "leetcode": True} + plain = resolve(answers, LADDER) + shown = resolve(answers, LADDER, progress={"leetcode": Progress(1, 3)}) + assert shown == plain + assert shown.term("leetcode").progress is None + + +def test_an_answer_of_none_earns_nothing_even_with_a_full_row() -> None: + answers = {**NOTHING, "leetcode": None} + shown = resolve(answers, LADDER, progress={"leetcode": Progress(3, 3)}) + assert shown == resolve(answers, LADDER) + assert shown.term("leetcode").shutdown_minutes == 0 + + +def test_a_missing_answer_earns_nothing_even_with_a_full_row() -> None: + answers = {k: v for k, v in NOTHING.items() if k != "leetcode"} + shown = resolve(answers, LADDER, progress={"leetcode": Progress(3, 3)}) + assert shown.term("leetcode").shutdown_minutes == 0 + + +def test_a_complete_row_with_a_no_answer_pays_in_full() -> None: + shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(3, 3)}) + assert shown.term("leetcode").shutdown_minutes == 60 + assert shown.term("leetcode").gaming_minutes == 60 + + +def test_the_share_floors() -> None: + shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(1, 7)}) + assert shown.term("leetcode").shutdown_minutes == 60 // 7 + + +def test_term_progress_says_why() -> None: + shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(2, 3)}) + assert shown.term("leetcode").progress == Progress(2, 3) + assert shown.term("leetcode").answer == 0 + assert shown.term("reading").progress is None + + +def test_a_counted_workout_pays_a_share_of_its_rung() -> None: + shown = resolve(NOTHING, LADDER, progress={"workout": Progress(1, 2)}) + assert shown.term("workout").shutdown_minutes == 120 // 2 + assert shown.term("workout").gaming_minutes == 120 // 2 + + +def test_a_pre_ladder_day_shares_the_old_pay() -> None: + day = date(2026, 10, 4) + shown = resolve(NOTHING, day, progress={"reading": Progress(1, 4)}) + assert shown.term("reading").shutdown_minutes == 60 // 4 + + +def test_the_share_uses_the_ladder_rung_not_the_old_pay() -> None: + day = date(2026, 10, 16) + assert shutdown_minutes_for(LEETCODE, day) == 50 + shown = resolve(NOTHING, day, progress={"leetcode": Progress(1, 2)}) + assert shown.term("leetcode").shutdown_minutes == 25 + assert shown.term("leetcode").gaming_minutes == 30 + + +def test_the_review_pays_a_share_of_its_top_up() -> None: + answers = {**NOTHING, "review": False} + shown = resolve(answers, DAY, progress={"review": Progress(1, 2)}) + assert shown.term("review").shutdown_minutes == 10 + paid = resolve( + {**NOTHING, "review": True}, DAY, progress={"review": Progress(1, 2)} + ) + assert paid.term("review").shutdown_minutes == 20 + + +def test_a_progress_for_an_earner_not_in_the_registry_is_ignored() -> None: + answers = {k: v for k, v in NOTHING.items() if k != "tutor"} + got = resolve(answers, date(2026, 10, 4), progress={"tutor": Progress(1, 2)}) + assert got == resolve(answers, date(2026, 10, 4)) + + +def test_a_sick_day_pays_the_partial_on_top_of_eight_pm() -> None: + day = resolve(NOTHING, LADDER, sick=True, progress={"leetcode": Progress(1, 3)}) + assert day.shutdown_minutes == 20 * 60 + 20 + + +def test_a_sick_day_partials_stack_and_stop_at_the_ceiling() -> None: + both = {"leetcode": Progress(3, 3), "reading": Progress(3, 3)} + day = resolve({**NOTHING, "workout": 1}, LADDER, sick=True, progress=both) + assert day.shutdown_minutes == 23 * 60 + + +def test_a_sick_day_with_a_none_answer_gets_no_partial() -> None: + answers = {**NOTHING, "leetcode": None} + day = resolve(answers, LADDER, sick=True, progress={"leetcode": Progress(3, 3)}) + assert day.shutdown_minutes == 20 * 60 + + +@pytest.mark.parametrize("answers", [NOTHING, {**NOTHING, "leetcode": True}]) +def test_a_progress_row_never_pays_more_than_a_yes( + answers: dict[str, int | bool | None], +) -> None: + yes = resolve({**NOTHING, "leetcode": True}, LADDER) + for done, target in product(range(6), range(1, 6)): + got = resolve(answers, LADDER, progress={"leetcode": Progress(done, target)}) + assert got.shutdown_minutes <= yes.shutdown_minutes + assert got.gaming_minutes <= yes.gaming_minutes + + +def test_deleting_rows_never_raises_the_pay_at_one_target( + tmp_path: Path, key_file: Path +) -> None: + rows = [progress(done=str(n), target="4") for n in (0, 1, 2, 3)] + full = _pay(tmp_path, key_file, rows) + for mask in product((False, True), repeat=len(rows)): + kept: list[object] = [r for r, keep in zip(rows, mask, strict=True) if keep] + assert _pay(tmp_path, key_file, kept) <= full + + +def _pay(tmp_path: Path, key_file: Path, rows: list[object]) -> int: + write(home_ledger(tmp_path, LEETCODE), rows) + found = progress_map(DAY, tmp_path, key_file) + return resolve(NOTHING, DAY, progress=found).shutdown_minutes + + +def test_gate_off_keeps_progress_out_of_the_pay(tmp_path: Path, key_file: Path) -> None: + write(home_ledger(tmp_path, LEETCODE), [progress(done="2", target="3")]) + on = progress_map(DAY, tmp_path, key_file) + off = progress_map(DAY, tmp_path, key_file, gate_off={"leetcode"}) + assert resolve(NOTHING, DAY, progress=on).term("leetcode").shutdown_minutes == 40 + assert resolve(NOTHING, DAY, progress=off).term("leetcode").shutdown_minutes == 0 + + +def test_a_progress_row_is_not_a_credit_for_maturity( + tmp_path: Path, key_file: Path +) -> None: + today = date(2026, 10, 9) + solves: list[object] = [solve(date(2026, 10, 1)), solve(date(2026, 10, 5))] + extra = [progress(day=today, done="3", target="3"), progress(done="1")] + bare = write(tmp_path / "bare.json", solves) + mixed = write(tmp_path / "mixed.json", [*solves, *extra]) + assert maturity(LEETCODE, mixed, key_file, today) == maturity( + LEETCODE, bare, key_file, today + ) + alone = write(tmp_path / "alone.json", extra) + seen = maturity(LEETCODE, alone, key_file, today) + assert (seen.credit_days, seen.credit_rows, seen.first_credit) == (0, 0, None) + + +def test_a_progress_row_is_not_a_done_answer(tmp_path: Path, key_file: Path) -> None: + ledger = write(home_ledger(tmp_path, LEETCODE), [progress(done="3", target="3")]) + assert done_today(LEETCODE, ledger, key_file, now=_noon(DAY)) is False + assert credit_units(LEETCODE, ledger, key_file, DAY) == 0 + + +def _noon(day: date) -> datetime: + return datetime.combine(day, time(12)).astimezone() + + +@pytest.mark.parametrize("pay", [0, 1, 7, 60, 100, 120, 180, 240]) +@pytest.mark.parametrize("target", [1, 2, 3, 7, 60, 120]) +def test_the_focus_share_floors_exactly_as_before(pay: int, target: int) -> None: + earner = FocusEarner( + name="focus", + label="Focus", + gaming_minutes=pay, + shutdown_minutes=pay, + kind="counted", + max_units=target, + ) + for units in range(-2, target + 3): + clamped = min(max(units, 0), target) + assert earner.gaming_for(units) == clamped * pay // target + assert earner.shutdown_for(units, DAY) == clamped * pay // target + assert share_minutes(pay, units, target) == clamped * pay // target + + +def test_the_share_of_a_zero_target_is_nothing() -> None: + assert share_minutes(60, 5, 0) == 0 + assert share_minutes(60, -1, 3) == 0 + + +def test_progress_source_defaults_to_none() -> None: + assert Earner("x", "x", 1, 1).progress_source is None + assert REVIEW.progress_source == "review" diff --git a/earned_time/pyproject.toml b/earned_time/pyproject.toml index b580714..f0fd53a 100644 --- a/earned_time/pyproject.toml +++ b/earned_time/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "earned-time" -version = "0.23.0" +version = "0.24.0" description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time" requires-python = ">=3.14" dependencies = [] @@ -35,7 +35,7 @@ unfixable = [] [tool.ruff.lint.pylint] # Same as [tool.pylint.design] max-args: resolve()'s keyword-only switches. -max-args = 6 +max-args = 7 [tool.ruff.lint.pydocstyle] convention = "google" @@ -111,10 +111,10 @@ disable = [] min-public-methods = 0 max-module-lines = 1000 # Earner is a frozen registry record: its fields are the policy (cf. music_theory). -max-attributes = 13 +max-attributes = 14 # resolve()'s keyword-only switches (first_credits, sick, leisure) are the # public API every consumer calls; bundling them would break each caller. -max-args = 6 +max-args = 7 [tool.pylint.typecheck] generated-members = [