earned_time: add the LeetCode review top-up

A finished coach review pays 20 shutdown minutes, once a day, as a
top-up: never a rung, never in the floor, added last and capped at the
ceiling (sick days too). A row pays only if signed, sourced, first for
its slug ever, and backed by a signed non-manual accepted submission
in the guard ledger from the 14 days before. From 2026-11-23.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXLvi9aq4MxL4XHKJ4
This commit is contained in:
Krzysztof Rudnicki 2026-11-21 21:56:12 +01:00
parent 727d494883
commit 2f8cf7d6e5
13 changed files with 821 additions and 44 deletions

View File

@ -104,9 +104,22 @@ from earned_time._policy import (
from earned_time._quota import TUTOR_QUOTA_FROM, TUTOR_QUOTA_MINUTES, tutor_quota_for 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._registry import all_earners, earners_for, registries
from earned_time._resolve import Base, Resolution, Term, base_for, resolve from earned_time._resolve import Base, Resolution, Term, base_for, resolve
from earned_time._review import (
ACCEPTED_LOOKBACK_DAYS,
GUARD_LEDGER,
REVIEW,
REVIEW_FROM,
REVIEW_LEDGER,
REVIEW_SHUTDOWN_MINUTES,
REVIEW_SOURCE,
guard_ledger_for,
paid_reviews,
review_match,
)
from earned_time._sick import SICK_SHUTDOWN_FLOOR_MINUTES, sick_shutdown_from from earned_time._sick import SICK_SHUTDOWN_FLOOR_MINUTES, sick_shutdown_from
__all__ = [ __all__ = [
"ACCEPTED_LOOKBACK_DAYS",
"ANKI", "ANKI",
"ANKI_WAIVED_FROM", "ANKI_WAIVED_FROM",
"AUTOMATION", "AUTOMATION",
@ -115,6 +128,7 @@ __all__ = [
"GAMING_BASE_MINUTES", "GAMING_BASE_MINUTES",
"GAMING_CEILING_MINUTES", "GAMING_CEILING_MINUTES",
"GAMING_UNLIMITED_FROM", "GAMING_UNLIMITED_FROM",
"GUARD_LEDGER",
"LADDER", "LADDER",
"LADDER_FROM", "LADDER_FROM",
"LEETCODE", "LEETCODE",
@ -125,6 +139,11 @@ __all__ = [
"MATURE_MIN_AGE_DAYS", "MATURE_MIN_AGE_DAYS",
"MATURE_MIN_CREDIT_DAYS", "MATURE_MIN_CREDIT_DAYS",
"READING", "READING",
"REVIEW",
"REVIEW_FROM",
"REVIEW_LEDGER",
"REVIEW_SHUTDOWN_MINUTES",
"REVIEW_SOURCE",
"SHUTDOWN_BASE_MINUTES", "SHUTDOWN_BASE_MINUTES",
"SHUTDOWN_CEILING_MINUTES", "SHUTDOWN_CEILING_MINUTES",
"SICK_SHUTDOWN_FLOOR_MINUTES", "SICK_SHUTDOWN_FLOOR_MINUTES",
@ -160,15 +179,18 @@ __all__ = [
"gaming_base_minutes_for", "gaming_base_minutes_for",
"gaming_ceiling_minutes_for", "gaming_ceiling_minutes_for",
"gaming_enforced", "gaming_enforced",
"guard_ledger_for",
"ladder_for", "ladder_for",
"leisure_active", "leisure_active",
"leisure_from", "leisure_from",
"maturity", "maturity",
"on_ladder", "on_ladder",
"paid_reviews",
"penalty_start", "penalty_start",
"real_credit", "real_credit",
"registries", "registries",
"resolve", "resolve",
"review_match",
"shutdown_ceiling_for", "shutdown_ceiling_for",
"shutdown_minutes_for", "shutdown_minutes_for",
"sick_shutdown_from", "sick_shutdown_from",

View File

@ -133,7 +133,8 @@ def counting_rows(
today. ``gate_off`` defaults to False so a caller that forgets it fails today. ``gate_off`` defaults to False so a caller that forgets it fails
closed: no bonus for a part-paid day. closed: no bonus for a part-paid day.
``None`` when the key or the ledger cannot be read. ``None`` when the key or the ledger cannot be read. An earner with
``evidence`` (the review, 0.23.0) is decided by it instead, on all rows.
Raises: Raises:
ValueError: ``earner`` has no ``match``; its answer is the consumer's. ValueError: ``earner`` has no ``match``; its answer is the consumer's.
@ -147,6 +148,8 @@ def counting_rows(
rows = read_rows(ledger, earner) rows = read_rows(ledger, earner)
if rows is None: if rows is None:
return None return None
if earner.evidence is not None:
return earner.evidence(earner, ledger, key, rows, window)
match = earner.match match = earner.match
kinds = ROW_KINDS.get(match, _CREDIT_ONLY) kinds = ROW_KINDS.get(match, _CREDIT_ONLY)
if not gate_off: if not gate_off:

View File

@ -136,6 +136,8 @@ def _level(days: list[date], earner: Earner, today: date, reasons: list[str]) ->
def _penalty_reason( def _penalty_reason(
earner: Earner, start: date | None, first: date | None, *, checked: bool earner: Earner, start: date | None, first: date | None, *, checked: bool
) -> str: ) -> str:
if earner.topup:
return "a top-up: nothing to cut, never penalised"
if earner.penalty_from is None: if earner.penalty_from is None:
return "no penalty_from: a pure bonus" return "no penalty_from: a pure bonus"
if start is not None and first is None: if start is not None and first is None:

View File

@ -6,16 +6,10 @@ steam-backlog-enforcer (gaming) lives here, once. A consumer never hard-codes
an hour; it asks :func:`earned_time.resolve` and applies the answer. an hour; it asks :func:`earned_time.resolve` and applies the answer.
**Penalty, then reward.** A gate with ``penalty_from`` lowers the base by **Penalty, then reward.** A gate with ``penalty_from`` lowers the base by
exactly what it pays back, from that day on. Doing the thing restores the old exactly what it pays back, from that day on (never before the reward that
day; skipping it costs the full amount. The date is the gate's own start, so pays for it: a same-day loss on 2026-09-26). Ceilings stay put. From
the cut never lands before the reward that pays for it -- taking an hour a ``LADDER_FROM`` shutdown follows the sleep ladder (:mod:`earned_time._ladder`).
reader could not yet earn back was a same-day loss on 2026-09-26. The review top-up (``REVIEW``, 0.23.0) lives in :mod:`earned_time._review`.
**Ceilings stay put.** Adding a penalised earner leaves the best case
unchanged: the base drops by what the new earner adds.
From ``LADDER_FROM`` shutdown follows the sleep ladder instead
(:mod:`earned_time._ladder`); gaming keeps the penalty derivation unchanged.
**The registry is per day** (:func:`earners_for`). From ``TUTOR_FROM`` Anki **The registry is per day** (:func:`earners_for`). From ``TUTOR_FROM`` Anki
is retired -- neither penalised nor paid -- and the tutor (``TUTOR``) is the is retired -- neither penalised nor paid -- and the tutor (``TUTOR``) is the
@ -41,6 +35,8 @@ from earned_time._match import (
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
from earned_time._review import RowEvidence
Window = tuple[float, float] Window = tuple[float, float]
# Whether one HMAC-verified ``credit`` row counts for the window. # Whether one HMAC-verified ``credit`` row counts for the window.
CreditMatch = Callable[[dict[str, object], Window], bool] CreditMatch = Callable[[dict[str, object], Window], bool]
@ -103,6 +99,16 @@ class Earner:
max_units: int | None = None max_units: int | None = None
confirmed_on: date | None = None confirmed_on: date | None = None
@property
def topup(self) -> bool:
"""A top-up (0.23.0): no rung, no floor cut, added last and capped."""
return False
@property
def evidence(self) -> RowEvidence | None:
"""A reader that pays from all rows instead of ``match`` (``_review``)."""
return None
def capped(self, units: int) -> int: def capped(self, units: int) -> int:
"""``units`` clamped to ``[0, max_units]``.""" """``units`` clamped to ``[0, max_units]``."""
units = max(0, units) units = max(0, units)
@ -142,8 +148,7 @@ WORKOUT: Final = Earner(
ledger=".local/share/workout_locker/ledger.json", ledger=".local/share/workout_locker/ledger.json",
match=workout_match, match=workout_match,
missing_ledger_is_no=True, missing_ledger_is_no=True,
# The day of its first verified credit, read off the real ledger on # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
# 2026-10-09 (earned_time 0.6.0); kuhy had been using the gate for real.
confirmed_on=date(2026, 10, 1), confirmed_on=date(2026, 10, 1),
) )
LEETCODE: Final = Earner( LEETCODE: Final = Earner(
@ -153,8 +158,7 @@ LEETCODE: Final = Earner(
shutdown_minutes=60, shutdown_minutes=60,
ledger=".local/share/leetcode_guard/ledger.json", ledger=".local/share/leetcode_guard/ledger.json",
match=leetcode_match, match=leetcode_match,
# The day of its first verified credit, read off the real ledger on # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
# 2026-10-09 (earned_time 0.6.0); kuhy had been using the gate for real.
confirmed_on=date(2026, 8, 12), confirmed_on=date(2026, 8, 12),
) )
READING: Final = Earner( READING: Final = Earner(
@ -166,8 +170,7 @@ READING: Final = Earner(
ledger=".local/share/book_guard/ledger.json", ledger=".local/share/book_guard/ledger.json",
match=reading_match, match=reading_match,
missing_ledger_is_no=True, missing_ledger_is_no=True,
# The day of its first verified credit, read off the real ledger on # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
# 2026-10-09 (earned_time 0.6.0); kuhy had been using the gate for real.
confirmed_on=date(2026, 10, 2), confirmed_on=date(2026, 10, 2),
) )
ANKI: Final = Earner( ANKI: Final = Earner(
@ -195,18 +198,15 @@ AUTOMATION: Final = Earner(
) )
# From ``TUTOR_FROM``: the tutor pays per active minute (0.8.0; a 0.7.0 # From ``TUTOR_FROM``: the tutor pays per active minute (0.8.0; a 0.7.0
# 15-minute block row counts 15), 1 gaming minute each, up to 60 a day summed # 15-minute block row counts 15), up to 60 a day; Anki's 30 is folded in.
# across sessions. Anki's 30 is folded in, so the base drops by 60. Named # Named ``automation`` until 0.9.0 (rows carry no earner name).
# ``automation`` (``AUTOMATION_TUTOR``) until 0.9.0; rows carry no earner name,
# so the rename only moved the ledger (copied over, old rows included).
TUTOR: Final = Earner( TUTOR: Final = Earner(
name="tutor", name="tutor",
label="Tutor", label="Tutor",
gaming_minutes=1, gaming_minutes=1,
extra_gaming_minutes=1, extra_gaming_minutes=1,
max_units=60, max_units=60,
# Pre-ladder values, unused (TUTOR_FROM is not before LADDER_FROM); the # Pre-ladder values, unused: the ladder pays 1 per minute.
# ladder pays 1 per minute (``TUTOR_LADDER``).
shutdown_minutes=1, shutdown_minutes=1,
extra_shutdown_minutes=1, extra_shutdown_minutes=1,
kind="counted", kind="counted",

View File

@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Final
from earned_time._focus import FOCUS_WATCH, with_focus from earned_time._focus import FOCUS_WATCH, with_focus
from earned_time._ladder import ANKI_WAIVED_FROM, TUTOR_FROM from earned_time._ladder import ANKI_WAIVED_FROM, TUTOR_FROM
from earned_time._review import REVIEW, REVIEW_FROM
if TYPE_CHECKING: if TYPE_CHECKING:
from earned_time._policy import Earner from earned_time._policy import Earner
@ -41,17 +42,25 @@ def earners_for(day: date | None = None) -> tuple[Earner, ...]:
Between ``ANKI_WAIVED_FROM`` and ``TUTOR_FROM`` the old registry without Between ``ANKI_WAIVED_FROM`` and ``TUTOR_FROM`` the old registry without
Anki and the anki-backed Automation: neither penalised nor paid. From Anki and the anki-backed Automation: neither penalised nor paid. From
``TUTOR_FROM`` an active focus project swaps its replaced earners for one ``TUTOR_FROM`` an active focus project swaps its replaced earners for one
``focus`` earner (:mod:`earned_time._focus`, 0.19.0). ``focus`` earner (:mod:`earned_time._focus`, 0.19.0). From
``REVIEW_FROM`` the review top-up joins it (0.23.0).
""" """
target = day or datetime.now(tz=UTC).astimezone().date() target = day or datetime.now(tz=UTC).astimezone().date()
before, tutor = registries() before, tutor = registries()
if target >= TUTOR_FROM: if target >= TUTOR_FROM:
return with_focus(tutor, target) return with_focus(_with_review(tutor, target), target)
if target >= ANKI_WAIVED_FROM: if target >= ANKI_WAIVED_FROM:
return _without_waived(before) return _without_waived(before)
return before return before
def _with_review(registry: tuple[Earner, ...], day: date) -> tuple[Earner, ...]:
"""``registry`` plus ``REVIEW`` from ``REVIEW_FROM``, never twice."""
if day < REVIEW_FROM or REVIEW in registry:
return registry
return (*registry, REVIEW)
@cache @cache
def _without_waived(registry: tuple[Earner, ...]) -> tuple[Earner, ...]: def _without_waived(registry: tuple[Earner, ...]) -> tuple[Earner, ...]:
"""``registry`` minus the waived earners; one stable tuple per registry.""" """``registry`` minus the waived earners; one stable tuple per registry."""
@ -67,5 +76,6 @@ def all_earners() -> tuple[Earner, ...]:
seen: dict[Earner, None] = {} seen: dict[Earner, None] = {}
for registry in registries(): for registry in registries():
seen.update(dict.fromkeys(registry)) seen.update(dict.fromkeys(registry))
seen[REVIEW] = None
seen[FOCUS_WATCH] = None seen[FOCUS_WATCH] = None
return tuple(seen) return tuple(seen)

View File

@ -33,7 +33,7 @@ from earned_time._maturity import confirmed_start, penalty_start
from earned_time._policy import SHUTDOWN_BASE_MINUTES, Earner from earned_time._policy import SHUTDOWN_BASE_MINUTES, Earner
from earned_time._registry import all_earners, earners_for from earned_time._registry import all_earners, earners_for
from earned_time._resolution import Base, Resolution, Term from earned_time._resolution import Base, Resolution, Term
from earned_time._sick import sick_shutdown_from from earned_time._sick import sick_or
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Mapping from collections.abc import Mapping
@ -84,11 +84,13 @@ def _shutdown_floor(day: date, earners: tuple[Earner, ...], cut: list[Earner]) -
On the ladder: the ceiling minus the most each earner can pay (all of a 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 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 -- 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). Before gate whose penalty has not started cannot lower the floor (0.6.1), nor can
it: the old base minus the penalties in force. a top-up (0.23.0). Before it: the old base minus the penalties in force.
""" """
if on_ladder(day): if on_ladder(day):
rungs = (e for e in earners if e.penalty_from is None or e in cut) 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( return shutdown_ceiling_for(day) - sum(
e.shutdown_for(e.max_units or 1, day) for e in rungs e.shutdown_for(e.max_units or 1, day) for e in rungs
) )
@ -167,19 +169,6 @@ def _term(item: Earner, answers: Mapping[str, Answer], day: date) -> Term:
) )
def _sick_or(earned: int, terms: list[Term], day: date) -> int:
"""A sick day's shutdown: 20:00 plus the paid terms, never below ``earned``.
The terms are paid at gaming pay before ``GAMING_UNLIMITED_FROM`` and at
their shutdown (rung) pay from it: the gaming budget no longer exists.
"""
if gaming_enforced(day):
paid = sum(t.gaming_minutes for t in terms)
else:
paid = sum(t.shutdown_minutes for t in terms)
return max(earned, sick_shutdown_from(paid, day))
def resolve( def resolve(
answers: Mapping[str, Answer], answers: Mapping[str, Answer],
day: date | None = None, day: date | None = None,
@ -236,7 +225,7 @@ def resolve(
shutdown_ceiling_for(target), shutdown_ceiling_for(target),
base.shutdown_minutes + sum(t.shutdown_minutes for t in terms), base.shutdown_minutes + sum(t.shutdown_minutes for t in terms),
) )
shutdown = _sick_or(earned, terms, target) if sick else earned shutdown = sick_or(earned, terms, target) if sick else earned
return Resolution( return Resolution(
day=target, day=target,
base=base, base=base,

View File

@ -0,0 +1,234 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The LeetCode review top-up (0.23.0): which coach review rows pay.
The coach (``/leetcode review``) signs one ``credit`` row per finished review
in its own ledger. A row pays only if it is signed, its ``detail.source`` is
:data:`REVIEW_SOURCE`, it finished in the day's window, it is the earliest
signed review of its ``detail.title_slug`` (each slug pays once, ever), and
the LeetCode guard's ledger holds a signed, non-manual accepted submission of
that slug from the :data:`ACCEPTED_LOOKBACK_DAYS` before the review finished.
The review row alone proves nothing (the coach's flag rests on unsigned
heartbeats), so the guard's accepted submission is the evidence and the
once-per-slug rule is the cap on forgery (kuhy, 2026-11-21, Q14).
**Fail closed, logged.** An unreadable guard ledger is ``None`` ("could not
check", one warning from :func:`~earned_time._ledger.read_rows`); a row with
no slug or no usable ``finished_at`` pays nothing, with a warning. No review
row in the window is an honest "no" and never reads the guard ledger.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
from datetime import UTC, date, datetime
import logging
from pathlib import PurePosixPath
from typing import TYPE_CHECKING, Final
from earned_time._evidence import MANUAL_PREFIXES, MANUAL_SOURCES
from earned_time._ledger import read_rows, verified
from earned_time._policy import Earner
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
from pathlib import Path
from earned_time._policy import Window
# (earner, ledger, key, rows, window) -> the rows that pay, or ``None``.
RowEvidence = Callable[
[Earner, Path, bytes, list[object], Window],
Iterator[dict[str, object]] | None,
]
_logger: Final = logging.getLogger(__name__)
# The first day the review earner is in the registry: the day after the
# planned deploy (2026-11-22).
REVIEW_FROM: Final = date(2026, 11, 23)
# What the day's first paid review adds to shutdown, capped at the ceiling.
REVIEW_SHUTDOWN_MINUTES: Final = 20
REVIEW_SOURCE: Final = "leetcode-coach-review"
REVIEW_LEDGER: Final = ".local/share/leetcode-coach/review_ledger.json"
# The LeetCode guard's ledger (``LEETCODE.ledger``), relative to the home.
GUARD_LEDGER: Final = ".local/share/leetcode_guard/ledger.json"
GUARD_SOURCE: Final = "leetcode"
# How old the accepted submission may be when the review finishes.
ACCEPTED_LOOKBACK_DAYS: Final = 14
_LOOKBACK_SECONDS: Final = ACCEPTED_LOOKBACK_DAYS * 24 * 60 * 60
def _detail(row: dict[str, object]) -> dict[str, object]:
detail = row.get("detail")
return detail if isinstance(detail, dict) else {}
def _stamp(raw: object) -> float | None:
"""A unix-seconds stamp, or ``None`` when absent or unparsable."""
try:
return float(str(raw))
except ValueError:
return None
def review_match(row: dict[str, object], window: Window) -> bool:
"""A coach review row that finished in ``window``.
Like ``leetcode_match``: ``finished_at`` decides, the row's ``day`` is the
fallback for a row without a usable stamp (that row still pays nothing:
the lookback needs the stamp, :func:`paid_reviews`).
"""
detail = _detail(row)
if detail.get("source") != REVIEW_SOURCE:
return False
stamp = _stamp(detail.get("finished_at"))
if stamp is not None:
return window[0] <= stamp <= window[1]
local = datetime.fromtimestamp(window[0], tz=UTC).astimezone().date()
return row.get("day") == local.isoformat()
def _slug(row: dict[str, object]) -> str | None:
slug = _detail(row).get("title_slug")
return slug if isinstance(slug, str) and slug else None
def _manual(row: dict[str, object]) -> bool:
"""A guard row a human granted: manual source, id, or ``manual_grant`` note."""
detail = _detail(row)
return (
detail.get("source") in MANUAL_SOURCES
or "manual_grant" in detail
or str(row.get("entry_id")).startswith(MANUAL_PREFIXES)
)
def _accepted(rows: list[object], key: bytes) -> dict[str, list[float]]:
"""Each slug's signed, non-manual accepted-submission stamps in the guard."""
found: dict[str, list[float]] = {}
for row in rows:
if not isinstance(row, dict) or row.get("kind") != "credit":
continue
if not verified(row, key) or _manual(row):
continue
detail = _detail(row)
slug = _slug(row)
stamp = _stamp(detail.get("submitted_at"))
if detail.get("source") == GUARD_SOURCE and slug and stamp is not None:
found.setdefault(slug, []).append(stamp)
return found
def _order(row: dict[str, object]) -> float:
"""When a review happened, for "earliest": ``finished_at``, else ``created_at``."""
stamp = _stamp(_detail(row).get("finished_at"))
if stamp is not None:
return stamp
try:
return datetime.fromisoformat(str(row.get("created_at"))).timestamp()
except ValueError:
return float("inf")
def _firsts(rows: list[dict[str, object]]) -> dict[str, dict[str, object]]:
"""The earliest signed review row of each slug (a tie: the first written)."""
firsts: dict[str, dict[str, object]] = {}
for row in sorted(rows, key=_order):
slug = _slug(row)
if slug is not None:
firsts.setdefault(slug, row)
return firsts
def guard_ledger_for(ledger: Path, earner: Earner) -> Path:
"""The guard ledger under the same home as ``ledger`` (``earner.ledger``).
The consumer resolves only the review ledger (``home / earner.ledger``),
so the home is that path with ``earner.ledger``'s depth stripped: a test
that redirects the home redirects both ledgers.
"""
depth = len(PurePosixPath(str(earner.ledger)).parts)
return ledger.parents[depth - 1] / GUARD_LEDGER
def _pays(row: dict[str, object], accepted: dict[str, list[float]]) -> bool:
"""Whether a slug's first review is backed by an accepted submission."""
finished = _stamp(_detail(row).get("finished_at"))
if finished is None:
_logger.warning(
"LeetCode review %r has no usable finished_at; it pays nothing",
row.get("entry_id"),
)
return False
slug = str(_slug(row))
return any(
finished - _LOOKBACK_SECONDS <= t <= finished for t in accepted.get(slug, ())
)
def paid_reviews(
earner: Earner, ledger: Path, key: bytes, rows: list[object], window: Window
) -> Iterator[dict[str, object]] | None:
"""The review rows that pay in ``window``; ``None`` if the guard is unreadable.
``earner.evidence`` for :data:`~earned_time.REVIEW`, called by
:func:`~earned_time._ledger.counting_rows` with the review ledger's rows
already read and the key already loaded.
"""
reviews = [
row
for row in rows
if isinstance(row, dict)
and row.get("kind") == "credit"
and _detail(row).get("source") == REVIEW_SOURCE
and verified(row, key)
]
today = [row for row in reviews if review_match(row, window)]
if not today:
return iter(())
guard = replace(earner, label="LeetCode guard", missing_ledger_is_no=False)
guard_rows = read_rows(guard_ledger_for(ledger, earner), guard)
if guard_rows is None:
return None
accepted = _accepted(guard_rows, key)
firsts = _firsts(reviews)
paid: list[dict[str, object]] = []
for row in today:
slug = _slug(row)
if slug is None:
_logger.warning(
"LeetCode review %r has no title_slug; it pays nothing",
row.get("entry_id"),
)
elif firsts[slug] is row and _pays(row, accepted):
paid.append(row)
return iter(paid)
@dataclass(frozen=True)
class ReviewEarner(Earner):
"""The review's earner kind: a top-up paid by :func:`paid_reviews`."""
@property
def topup(self) -> bool:
"""Always: never a rung, never in the floor, added last and capped."""
return True
@property
def evidence(self) -> RowEvidence:
""":func:`paid_reviews`: the guard ledger backs each row."""
return paid_reviews
# A pure top-up: 0 gaming, no penalty, not on the ladder, not in the floor.
# ``confirmed_on`` stays unset until kuhy has seen a real review credited.
REVIEW: Final = ReviewEarner(
name="review",
label="LeetCode review",
gaming_minutes=0,
shutdown_minutes=REVIEW_SHUTDOWN_MINUTES,
ledger=REVIEW_LEDGER,
match=review_match,
missing_ledger_is_no=True,
)

View File

@ -20,11 +20,15 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Final from typing import TYPE_CHECKING, Final
from earned_time._gaming import gaming_enforced
from earned_time._ladder import shutdown_ceiling_for from earned_time._ladder import shutdown_ceiling_for
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence
from datetime import date from datetime import date
from earned_time._resolution import Term
# 20:00, minutes after local midnight. # 20:00, minutes after local midnight.
SICK_SHUTDOWN_FLOOR_MINUTES: Final = 20 * 60 SICK_SHUTDOWN_FLOOR_MINUTES: Final = 20 * 60
@ -40,3 +44,20 @@ def sick_shutdown_from(paid_minutes: int, day: date) -> int:
``min(ceiling, SICK_SHUTDOWN_FLOOR_MINUTES + paid_minutes)``. ``min(ceiling, SICK_SHUTDOWN_FLOOR_MINUTES + paid_minutes)``.
""" """
return min(shutdown_ceiling_for(day), SICK_SHUTDOWN_FLOOR_MINUTES + paid_minutes) return min(shutdown_ceiling_for(day), SICK_SHUTDOWN_FLOOR_MINUTES + paid_minutes)
def sick_or(earned: int, terms: Sequence[Term], day: date) -> int:
"""A sick day's shutdown: 20:00 plus the paid terms, never below ``earned``.
The terms are paid at gaming pay before ``GAMING_UNLIMITED_FROM`` and at
their shutdown (rung) pay from it: the gaming budget no longer exists.
A top-up adds its shutdown minutes last, capped (0.23.0).
"""
paying = [t for t in terms if not t.earner.topup]
if gaming_enforced(day):
paid = sum(t.gaming_minutes for t in paying)
else:
paid = sum(t.shutdown_minutes for t in paying)
topup = sum(t.shutdown_minutes for t in terms if t.earner.topup)
lifted = min(shutdown_ceiling_for(day), sick_shutdown_from(paid, day) + topup)
return max(earned, lifted)

View File

@ -0,0 +1,98 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""A fake home with a coach review ledger and a LeetCode guard ledger."""
from __future__ import annotations
from datetime import date, datetime, time
import json
from typing import TYPE_CHECKING
from earned_time import GUARD_LEDGER, REVIEW, entry_signature
from earned_time.tests._maturity_rows import KEY, at
if TYPE_CHECKING:
from pathlib import Path
# A day the review earner is registered on (REVIEW_FROM is 2026-11-23).
DAY = date(2026, 11, 24)
SLUG = "two-sum"
def sign(row: dict[str, object], key: bytes = KEY) -> dict[str, object]:
"""``row`` with its HMAC under ``key``."""
return {**row, "hmac": entry_signature(row, key)}
def review(
slug: str | None = SLUG, day: date = DAY, hour: int = 20, **detail: object
) -> dict[str, object]:
"""One signed coach row for a finished review, as the coach writes it."""
fields: dict[str, object] = {
"source": "leetcode-coach-review",
"cause": "slow-solve",
"finished_at": at(day, hour),
**detail,
}
if slug is not None:
fields["title_slug"] = slug
return sign(
{
"entry_id": f"review:{slug}",
"kind": "credit",
"day": day.isoformat(),
"created_at": datetime.combine(day, time(hour)).astimezone().isoformat(),
"amount": 1,
"device": "pc",
"detail": fields,
}
)
def accepted(
slug: str = SLUG,
day: date = DAY,
hour: int = 10,
entry: str | None = None,
**detail: object,
) -> dict[str, object]:
"""One signed LeetCode guard credit: an accepted submission of ``slug``."""
return sign(
{
"entry_id": entry or f"ac:{slug}:{day}:{hour}",
"kind": "credit",
"day": day.isoformat(),
"amount": 1,
"detail": {
"title_slug": slug,
"source": "leetcode",
"submitted_at": at(day, hour),
**detail,
},
}
)
def write(path: Path, rows: list[dict[str, object]]) -> Path:
"""Write ``rows`` as a ``{"version", "entries"}`` ledger at ``path``."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({"version": 1, "entries": rows}), encoding="utf-8")
return path
def home_with(
home: Path,
reviews: list[dict[str, object]],
guard: list[dict[str, object]] | None,
) -> Path:
"""Lay both ledgers out under ``home``; returns the review ledger path.
``guard=None`` leaves the guard ledger missing.
"""
if guard is not None:
write(home / GUARD_LEDGER, guard)
return write(home / str(REVIEW.ledger), reviews)
def evening(day: date = DAY) -> datetime:
"""``day`` at 22:00 local: every fixture row of the day lies before it."""
return datetime.combine(day, time(22)).astimezone()

View File

@ -58,9 +58,12 @@ def test_table(home: Path, capsys: pytest.CaptureFixture[str]) -> None:
"anki", "anki",
"automation", "automation",
"tutor", "tutor",
"review",
} }
assert rows["leetcode"].split()[1:5] == ["maturing", "1", str(DAY), str(DAY)] assert rows["leetcode"].split()[1:5] == ["maturing", "1", str(DAY), str(DAY)]
assert "not in the registry on 2026-10-09" in rows["anki"] assert "not in the registry on 2026-10-09" in rows["anki"]
assert "a top-up: nothing to cut, never penalised" in rows["review"]
assert "not in the registry on 2026-10-09" in rows["review"]
assert "could not check: ledger" not in rows["reading"] assert "could not check: ledger" not in rows["reading"]
assert rows["reading"].endswith( assert rows["reading"].endswith(
"no verified credit but confirmed_on 2026-10-02: " "no verified credit but confirmed_on 2026-10-02: "
@ -96,6 +99,7 @@ def test_default_day_and_unregistered_earners(
"workout", "workout",
"reading", "reading",
"tutor", "tutor",
"review",
] ]
@ -142,4 +146,4 @@ def test_a_name_shared_across_registries_gets_its_ledger_dir(
monkeypatch.setattr(earned_time, "TUTOR_EARNERS", (new,)) monkeypatch.setattr(earned_time, "TUTOR_EARNERS", (new,))
assert cli.main(["maturity", "--day", DAY.isoformat()]) == 0 assert cli.main(["maturity", "--day", DAY.isoformat()]) == 0
rows = [line.split()[0] for line in capsys.readouterr().out.splitlines()[2:-1]] rows = [line.split()[0] for line in capsys.readouterr().out.splitlines()[2:-1]]
assert rows == ["twin:a", "twin:b"] assert rows == ["twin:a", "twin:b", "review"]

View File

@ -0,0 +1,77 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Review evidence edges (0.23.0): odd rows on either ledger."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from earned_time import (
GUARD_LEDGER,
REVIEW,
day_window,
done_today,
guard_ledger_for,
review_match,
)
from earned_time.tests._review_rows import (
DAY,
accepted,
evening,
home_with,
review,
sign,
)
if TYPE_CHECKING:
from pathlib import Path
def _unsigned(row: dict[str, object]) -> dict[str, object]:
return {k: v for k, v in row.items() if k != "hmac"}
def test_the_matcher_wants_the_coach_source() -> None:
assert review_match(accepted(), day_window(DAY)) is False
assert review_match(review(), day_window(DAY)) is True
def test_a_guard_row_of_another_source_does_not_back_it(
tmp_path: Path, key_file: Path
) -> None:
ledger = home_with(tmp_path, [review()], [accepted(source="escape")])
assert done_today(REVIEW, ledger, key_file, now=evening()) is False
def test_a_guard_row_without_a_stamp_does_not_back_it(
tmp_path: Path, key_file: Path
) -> None:
ledger = home_with(tmp_path, [review()], [accepted(submitted_at="later")])
assert done_today(REVIEW, ledger, key_file, now=evening()) is False
def test_junk_guard_rows_are_skipped(tmp_path: Path, key_file: Path) -> None:
ledger = home_with(tmp_path, [review()], [])
guard = {"entries": ["junk", accepted()]}
(tmp_path / GUARD_LEDGER).write_text(json.dumps(guard), encoding="utf-8")
assert done_today(REVIEW, ledger, key_file, now=evening()) is True
def test_a_timeless_review_never_spends_the_slug(
tmp_path: Path, key_file: Path
) -> None:
timeless = sign({**_unsigned(review(finished_at="x")), "created_at": "never"})
ledger = home_with(tmp_path, [timeless, review()], [accepted()])
assert done_today(REVIEW, ledger, key_file, now=evening()) is True
def test_junk_review_rows_are_skipped(tmp_path: Path, key_file: Path) -> None:
ledger = home_with(tmp_path, [review()], [accepted()])
text = ledger.read_text(encoding="utf-8").replace('"entries": [', '"entries": [7, ')
ledger.write_text(text, encoding="utf-8")
assert done_today(REVIEW, ledger, key_file, now=evening()) is True
def test_the_guard_ledger_shares_the_review_ledgers_home(tmp_path: Path) -> None:
review_ledger = tmp_path / str(REVIEW.ledger)
assert guard_ledger_for(review_ledger, REVIEW) == tmp_path / GUARD_LEDGER

View File

@ -0,0 +1,194 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Which coach review rows pay (0.23.0): signed, sourced, backed, first per slug."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import TYPE_CHECKING
import pytest
from earned_time import (
ACCEPTED_LOOKBACK_DAYS,
GUARD_LEDGER,
LEETCODE,
REVIEW,
credit_units,
done_today,
)
from earned_time.tests._review_rows import (
DAY,
accepted,
evening,
home_with,
review,
sign,
)
if TYPE_CHECKING:
from pathlib import Path
def _done(home: Path, key_file: Path, reviews: list, guard: list | None) -> object:
ledger = home_with(home, reviews, guard)
return done_today(REVIEW, ledger, key_file, now=evening())
def test_the_guard_ledger_is_the_leetcode_earners() -> None:
assert LEETCODE.ledger == GUARD_LEDGER
def test_a_backed_review_pays(tmp_path: Path, key_file: Path) -> None:
assert _done(tmp_path, key_file, [review()], [accepted()]) is True
def test_two_reviews_in_a_day_are_one_unit(tmp_path: Path, key_file: Path) -> None:
reviews = [review(), review("add-two-numbers", hour=21)]
guard = [accepted(), accepted("add-two-numbers")]
ledger = home_with(tmp_path, reviews, guard)
assert done_today(REVIEW, ledger, key_file, now=evening()) is True
assert credit_units(REVIEW, ledger, key_file, DAY) == 2 # resolve pays it flat
def test_a_forged_row_pays_nothing(tmp_path: Path, key_file: Path) -> None:
forged = sign({k: v for k, v in review().items() if k != "hmac"}, b"other-key")
assert _done(tmp_path, key_file, [forged], [accepted()]) is False
def test_an_unsigned_row_pays_nothing(tmp_path: Path, key_file: Path) -> None:
row = {k: v for k, v in review().items() if k != "hmac"}
assert _done(tmp_path, key_file, [row], [accepted()]) is False
def test_another_source_pays_nothing(tmp_path: Path, key_file: Path) -> None:
row = review(source="leetcode-coach")
assert _done(tmp_path, key_file, [row], [accepted()]) is False
def test_no_accepted_submission_pays_nothing(tmp_path: Path, key_file: Path) -> None:
assert _done(tmp_path, key_file, [review()], [accepted("other")]) is False
def test_a_forged_guard_row_does_not_back_it(tmp_path: Path, key_file: Path) -> None:
fake = sign({k: v for k, v in accepted().items() if k != "hmac"}, b"x")
assert _done(tmp_path, key_file, [review()], [fake]) is False
@pytest.mark.parametrize(
("entry", "extra"),
[
("manual:2026-11-24", {}),
("manual_grant:two-sum", {}),
(None, {"source": "manual_grant"}),
(None, {"manual_grant": "ordered by hand"}),
],
)
def test_a_manual_grant_does_not_back_it(
tmp_path: Path, key_file: Path, entry: str | None, extra: dict[str, object]
) -> None:
guard = [accepted(entry=entry, **extra)]
assert _done(tmp_path, key_file, [review()], guard) is False
def test_a_charge_row_does_not_back_it(tmp_path: Path, key_file: Path) -> None:
row = {k: v for k, v in accepted().items() if k != "hmac"}
charge = sign({**row, "kind": "charge"})
assert _done(tmp_path, key_file, [review()], [charge]) is False
def test_a_submission_inside_the_lookback_backs_it(
tmp_path: Path, key_file: Path
) -> None:
old = DAY - timedelta(days=ACCEPTED_LOOKBACK_DAYS)
assert _done(tmp_path, key_file, [review()], [accepted(day=old, hour=21)]) is True
def test_a_submission_older_than_the_lookback_pays_nothing(
tmp_path: Path, key_file: Path
) -> None:
old = DAY - timedelta(days=ACCEPTED_LOOKBACK_DAYS + 1)
assert _done(tmp_path, key_file, [review()], [accepted(day=old)]) is False
def test_a_submission_after_the_review_pays_nothing(
tmp_path: Path, key_file: Path
) -> None:
assert _done(tmp_path, key_file, [review()], [accepted(hour=21)]) is False
def test_a_slug_pays_once_ever(tmp_path: Path, key_file: Path) -> None:
earlier = review(day=DAY - timedelta(days=3))
guard = [accepted(day=DAY - timedelta(days=4))]
assert _done(tmp_path, key_file, [earlier, review()], guard) is False
def test_an_unpaid_first_review_still_spends_the_slug(
tmp_path: Path, key_file: Path
) -> None:
earlier = review(day=DAY - timedelta(days=20))
assert _done(tmp_path, key_file, [review(), earlier], [accepted()]) is False
def test_a_review_of_another_day_pays_nothing(tmp_path: Path, key_file: Path) -> None:
row = review(day=DAY - timedelta(days=1))
assert _done(
tmp_path, key_file, [row], [accepted(day=DAY - timedelta(days=1))]
) is (False)
def test_a_future_stamp_pays_nothing_today(tmp_path: Path, key_file: Path) -> None:
assert _done(tmp_path, key_file, [review(hour=23)], [accepted()]) is False
def test_a_bad_stamp_pays_nothing_and_warns(
tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.WARNING)
row = review(finished_at="soon")
assert _done(tmp_path, key_file, [row], [accepted()]) is False
assert "finished_at" in caplog.text
def test_a_missing_slug_pays_nothing_and_warns(
tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.WARNING)
assert _done(tmp_path, key_file, [review(None)], [accepted()]) is False
assert "title_slug" in caplog.text
def test_a_missing_guard_ledger_cannot_check(
tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.WARNING)
assert _done(tmp_path, key_file, [review()], None) is None
assert len(caplog.records) == 1
assert "guard" in caplog.text
def test_an_unreadable_guard_ledger_cannot_check(
tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.WARNING)
ledger = home_with(tmp_path, [review()], [])
(tmp_path / GUARD_LEDGER).write_text("{not json", encoding="utf-8")
assert done_today(REVIEW, ledger, key_file, now=evening()) is None
assert len(caplog.records) == 1
def test_no_review_today_never_reads_the_guard(tmp_path: Path, key_file: Path) -> None:
assert _done(tmp_path, key_file, [], None) is False
def test_a_missing_review_ledger_is_an_honest_no(
tmp_path: Path, key_file: Path
) -> None:
ledger = tmp_path / str(REVIEW.ledger)
assert done_today(REVIEW, ledger, key_file, now=evening()) is False
def test_a_big_amount_still_pays_one_unit(tmp_path: Path, key_file: Path) -> None:
row = {k: v for k, v in review().items() if k != "hmac"}
ledger = home_with(tmp_path, [sign({**row, "amount": 1000})], [accepted()])
assert credit_units(REVIEW, ledger, key_file, DAY) == 1

View File

@ -0,0 +1,123 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The review top-up in the day (0.23.0): added last, capped, never a rung."""
from __future__ import annotations
from datetime import date, timedelta
from typing import TYPE_CHECKING
from earned_time import (
REVIEW,
REVIEW_FROM,
REVIEW_SHUTDOWN_MINUTES,
all_earners,
base_for,
earners_for,
maturity,
resolve,
shutdown_ceiling_for,
shutdown_minutes_for,
)
from earned_time.tests._review_rows import DAY, accepted, home_with, review
if TYPE_CHECKING:
from pathlib import Path
NOTHING: dict[str, int | bool | None] = {
"workout": 0,
"leetcode": False,
"reading": False,
"tutor": 0,
}
EVERYTHING: dict[str, int | bool | None] = {
"workout": 1,
"leetcode": True,
"reading": True,
"tutor": 60,
}
def _day(answers: dict[str, int | bool | None], **kwargs: bool) -> int:
return resolve(answers, DAY, **kwargs).shutdown_minutes
def test_the_constants() -> None:
assert REVIEW_SHUTDOWN_MINUTES == 20
assert date(2026, 11, 23) == REVIEW_FROM
assert REVIEW.gaming_minutes == 0
assert REVIEW.topup
assert REVIEW.penalty_from is None
assert REVIEW.confirmed_on is None
def test_the_review_pays_twenty_flat() -> None:
with_review = _day({**NOTHING, "review": True})
assert with_review - _day({**NOTHING, "review": False}) == REVIEW_SHUTDOWN_MINUTES
assert shutdown_minutes_for(REVIEW, DAY) == REVIEW_SHUTDOWN_MINUTES
def test_two_units_still_pay_twenty() -> None:
assert _day({**NOTHING, "review": 2}) == _day({**NOTHING, "review": 1})
assert resolve({**NOTHING, "review": 2}, DAY).term("review").shutdown_minutes == 20
def test_it_is_capped_at_the_ceiling() -> None:
near = {**EVERYTHING, "tutor": 50}
assert _day(near) == shutdown_ceiling_for(DAY) - 10
assert _day({**near, "review": True}) == shutdown_ceiling_for(DAY)
def test_it_is_worth_nothing_on_a_full_day() -> None:
full = _day({**EVERYTHING, "review": False})
assert full == shutdown_ceiling_for(DAY)
assert _day({**EVERYTHING, "review": True}) == full
def test_the_floor_does_not_move() -> None:
without = tuple(e for e in earners_for(DAY) if e is not REVIEW)
assert base_for(DAY) == base_for(DAY, without)
assert _day({**NOTHING, "review": False}) == base_for(DAY).shutdown_minutes
assert _day({**NOTHING, "review": None}) == base_for(DAY).shutdown_minutes
def test_could_not_check_earns_nothing_but_says_so() -> None:
term = resolve({**NOTHING, "review": None}, DAY).term("review")
assert term.answer is None
assert term.shutdown_minutes == 0
def test_not_registered_before_the_start_date() -> None:
before = REVIEW_FROM - timedelta(days=1)
assert REVIEW not in earners_for(before)
assert REVIEW in earners_for(REVIEW_FROM)
assert resolve({**NOTHING, "review": True}, before).shutdown_minutes == (
resolve(NOTHING, before).shutdown_minutes
)
def test_every_registry_view_watches_its_ledger() -> None:
assert REVIEW in all_earners()
def test_a_sick_day_adds_it_on_top() -> None:
sick = _day({**NOTHING, "review": False}, sick=True)
assert _day({**NOTHING, "review": True}, sick=True) == sick + 20
def test_a_full_sick_day_stays_at_the_ceiling() -> None:
assert _day({**EVERYTHING, "review": True}, sick=True) == shutdown_ceiling_for(DAY)
def test_a_sick_day_before_unlimited_gaming_adds_it_too() -> None:
old = date(2026, 11, 1)
registry = (*earners_for(old), REVIEW)
base = resolve({**NOTHING, "review": False}, old, registry, sick=True)
paid = resolve({**NOTHING, "review": True}, old, registry, sick=True)
assert paid.shutdown_minutes == base.shutdown_minutes + 20
def test_maturity_never_penalises_it(tmp_path: Path, key_file: Path) -> None:
ledger = home_with(tmp_path, [review()], [accepted()])
verdict = maturity(REVIEW, ledger, key_file, DAY)
assert verdict.penalty_start is None
assert any("top-up" in reason for reason in verdict.reasons)