Compare commits

..

12 Commits

Author SHA1 Message Date
c06f2daa9a Export term_for: one derivation of a term
Some checks are pending
earned_time pre-commit / pre-commit (push) Waiting to run
earned_time tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
term_for(earner, day, *, answer, progress=None) returns the Term an
earner pays: the ladder rung, the share of a row, the full-pay cap and
the review's dated rule. resolve builds every term through it, so a
consumer pricing one earner cannot disagree with resolve and never
re-derives a share.

A grid test pins term_for == resolve's term for every earner, answer,
row and day either side of REVIEW_PROGRESS_FROM, and a second test
checks the minutes against the written rules, not the library code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZLyjnLjB1THD6ckou
2026-11-22 18:55:54 +01:00
77827e9abb Write a progress row with each review credit
Some checks are pending
earned_time pre-commit / pre-commit (push) Waiting to run
earned_time tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
leetcode-coach pre-commit / pre-commit (push) Waiting to run
leetcode-coach tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZLyjnLjB1THD6ckou
2026-11-22 18:50:44 +01:00
80f0ca13ca Pay the review by its row from 2026-11-24
From REVIEW_PROGRESS_FROM a credited review pays bonus * done // target
of its signed progress row, never more than 20, and with no verified row
pays 0 (logged); a row that fails verification is no row. A no or
unknown pays 0 whatever a row says, since the guard's accepted
submission is the evidence. Before that date the review pays as in
0.23.0 and ignores progress. Other earners are unchanged.

The 0.23.0 golden grid asks the review only no or unknown from the
switch, since a credited review without a row now differs by design.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZLyjnLjB1THD6ckou
2026-11-22 18:50:09 +01:00
644d372625 Read progress from the last good row
The day's last verified progress row for the source wins, and both done
and target come from that one row. max(done) with max(target) could pair
a stale target with a new done when a gate re-derives its target within
a day (book-guard does). The rule reads neither created_at nor device,
which the workout ledger does not write.

A later row that fails verification, has the wrong kind, source or day,
or has unreadable numbers is skipped; no good row is still None. The
public API, the version and every other behaviour are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZLyjnLjB1THD6ckou
2026-11-22 18:44:20 +01:00
e5e457d8a9 Pay partial progress in earned_time 0.24.0
A gate can now sign "done N of target M for day D" and resolve() pays a
no-answer that share of a yes (60 * 1 // 3 = 20), floored, for shutdown,
gaming and sick days. A yes still pays full; "could not check" still pays
nothing. With no progress row anywhere every output is 0.23.0's, pinned by
a digest grid and, when installed, the real 0.23.0 as oracle.

Every failure reads as no progress, so the day pays by its yes/no rule and
never more:
- no row, a bad or missing signature, an edited row
- another day or another gate's source
- numbers typed as ints, floats, signed, padded, empty, non-ASCII or huge
- a zero target (no plan, no share)
- an unreadable key or ledger (logged, never raised)
- the gate being off today
- an earner with no progress source (tutor, focus)
A bad row beside a good one is skipped. Done above target is capped.

The focus earner now uses the same share arithmetic, same floor. A progress
row is not a credit: maturity and the done answers never see it. The floor
helpers moved to _floor.py and the tutor row contract to DOCS-tutor.md to
stay under the 250-line cap.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVfmEXxPymCs5bo3Zs
2026-11-22 18:24:22 +01:00
eddd1a38f8 Give the coach kuhy's submission history
Some checks are pending
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
leetcode-coach pre-commit / pre-commit (push) Waiting to run
leetcode-coach tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
history.py prints the guard's per-problem mirror (every status, code
cut at 1500 chars, newest 12); SKILL.md reads it at the start, for the
coach only. Read-only context, never a gate input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:36:33 +01:00
41af578702 crdt_sync_flutter 0.9.2, sync_settings_ui 0.8.6: crdt_sync 0.14.2
Some checks are pending
crdt_sync_dart tests / test (push) Waiting to run
crdt_sync_flutter tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
sync_settings_ui tests / test (push) Waiting to run
Both pick up the per-instance temp file name, so an app's UI and
headless engines stop losing writes to each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:08:10 +01:00
171a7f8ae3 crdt_sync_dart 0.14.2: per-instance temp file name
Two FileLogPersistence instances on one file in one process (a Flutter
UI engine and a headless engine) shared <file>.<pid>.tmp, so one rename
moved the other's temp away and that write threw PathNotFoundException:
wake_alarm's bypass publish was lost to it on the emulator, 2026-11-22.
A random per-instance token now goes beside the pid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:05:54 +01:00
ceb6e42c27 dep_freshness: test gate path, not folder name
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:57:00 +01:00
14f0f47c56 dep_freshness: add pacman-repo lock adapter
Some checks are pending
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
A key=value *.lock file (name/repo/version/sha256) pins one package out of
an Arch-style repo .db. The adapter reads the db (gzip or zstd tar) via a
new http.get_bytes, matches %NAME% in each desc, and the judge compares
with a port of pacman's vercmp (epoch:pkgver-pkgrel), not PEP 440. A right
version with a wrong sha256 is a lock mismatch.

Locks are recognised by content (a repo= line ending in .db in the first
4 KB of a *.lock), so explicit paths from pre-commit and --all both work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:43:40 +01:00
7917d70b97 Release freedays 0.4.4, sickdays 0.5.9, gatelock 0.16.1
Some checks are pending
file length / file-length (push) Waiting to run
freedays pre-commit / pre-commit (push) Waiting to run
freedays tests / test (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
sickdays pre-commit / pre-commit (push) Waiting to run
sickdays tests / test (push) Waiting to run
Moves all three onto kuhy-credit 0.3.2 and onto each other's new
tags, so a consumer can pin the newest of each without the resolver
conflicting. gatelock 0.16.1 also ships the 2026-11-21 lock-order
check and the earned-time 0.23.0 pin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 12:40:34 +01:00
abfb596d7c sync_settings_ui 0.8.5: data_transfer_flutter 0.2.4
Some checks are pending
data_transfer_flutter tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
sync_settings_ui tests / test (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:40:36 +01:00
54 changed files with 3316 additions and 219 deletions

View File

@ -1,4 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'dart:math';
import 'store.dart'; import 'store.dart';
@ -7,10 +8,12 @@ import 'store.dart';
/// Writes atomically -- to a per-process temp file, then `rename`d over the /// Writes atomically -- to a per-process temp file, then `rename`d over the
/// real path -- so a concurrent reader (e.g. a background sync isolate writing /// real path -- so a concurrent reader (e.g. a background sync isolate writing
/// while the foreground app also writes) never observes a half-written file. /// while the foreground app also writes) never observes a half-written file.
/// The pid in the temp name keeps two processes from colliding; within one /// The pid plus a random per-instance token in the temp name keep two
/// instance, writes are serialized in issue order (last issued wins), so /// writers from colliding: two processes, and two instances in one process
/// overlapping calls (e.g. per-keystroke saves) never share the temp file /// (a Flutter app's UI engine and a headless engine share a pid -- wake_alarm
/// mid-flight. This generalizes diet_guard's hand-rolled `LogStorageService` /// lost a publish to exactly that, 2026-11-22). Within one instance, writes
/// are serialized in issue order (last issued wins), so overlapping calls
/// (e.g. per-keystroke saves) never share the temp file mid-flight. This generalizes diet_guard's hand-rolled `LogStorageService`
/// write scheme. /// write scheme.
/// ///
/// Lives behind the `package:crdt_sync/crdt_sync_io.dart` entrypoint, not the /// Lives behind the `package:crdt_sync/crdt_sync_io.dart` entrypoint, not the
@ -19,10 +22,14 @@ import 'store.dart';
class FileLogPersistence implements LogPersistence { class FileLogPersistence implements LogPersistence {
/// Persists to [file]. The app chooses the path (e.g. via `path_provider`); /// Persists to [file]. The app chooses the path (e.g. via `path_provider`);
/// the library takes no dependency on where app documents live. /// the library takes no dependency on where app documents live.
FileLogPersistence(this._file); FileLogPersistence(this._file)
: _token = Random.secure().nextInt(1 << 32).toRadixString(36);
final File _file; final File _file;
/// Tells this instance's temp file apart from another's in this process.
final String _token;
/// Completes when the most recently issued write has settled. Never /// Completes when the most recently issued write has settled. Never
/// rejects, so one failed write cannot block the ones queued after it. /// rejects, so one failed write cannot block the ones queued after it.
Future<void> _tail = Future<void>.value(); Future<void> _tail = Future<void>.value();
@ -47,7 +54,7 @@ class FileLogPersistence implements LogPersistence {
Future<void> _writeNow(String text) async { Future<void> _writeNow(String text) async {
await _file.parent.create(recursive: true); await _file.parent.create(recursive: true);
final tmp = File('${_file.path}.$pid.tmp'); final tmp = File('${_file.path}.$pid.$_token.tmp');
await tmp.writeAsString(text); await tmp.writeAsString(text);
await tmp.rename(_file.path); await tmp.rename(_file.path);
} }

View File

@ -2,7 +2,7 @@ name: crdt_sync
description: >- description: >-
Shared CRDT merge scheme + GitHub-Contents-API sync transport for Shared CRDT merge scheme + GitHub-Contents-API sync transport for
cross-device apps. Pure Dart, no Flutter dependency. cross-device apps. Pure Dart, no Flutter dependency.
version: 0.14.1 version: 0.14.2
publish_to: 'none' publish_to: 'none'
environment: environment:

View File

@ -149,6 +149,30 @@ void main() {
}, },
); );
test(
'two instances on one file in one process never share a temp file',
() async {
// Regression (wake_alarm, 2026-11-22): a Flutter app's UI engine and
// a headless engine each hold a FileLogPersistence for the same log
// in one process, so one pid. Both wrote `<file>.<pid>.tmp`; the
// first rename moved it away and the other publish died with
// PathNotFoundException.
final file = File('${dir.path}/log.json');
final a = FileLogPersistence(file);
final b = FileLogPersistence(file);
await Future.wait([
for (var i = 0; i < 25; i++) ...[
a.write('{"a":$i}'),
b.write('{"b":$i}'),
],
]);
expect(await a.read(), anyOf('{"a":24}', '{"b":24}'));
expect(dir.listSync().map((e) => e.uri.pathSegments.last), [
'log.json',
]);
},
);
test( test(
'a failed write rejects its caller but does not block later writes', 'a failed write rejects its caller but does not block later writes',
() async { () async {

View File

@ -61,11 +61,11 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: crdt_sync_dart path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.1" ref: "crdt_sync_dart-v0.14.2"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.14.1" version: "0.14.2"
crypto: crypto:
dependency: "direct main" dependency: "direct main"
description: description:

View File

@ -4,7 +4,7 @@ description: >-
persisted per-install device id, and a one-call bootstrap. Removes the persisted per-install device id, and a one-call bootstrap. Removes the
~150 lines of firebase_backend.dart every consuming app was copying. ~150 lines of firebase_backend.dart every consuming app was copying.
publish_to: 'none' publish_to: 'none'
version: 0.9.1 version: 0.9.2
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2
@ -13,7 +13,7 @@ dependencies:
crdt_sync: crdt_sync:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.1 ref: crdt_sync_dart-v0.14.2
path: crdt_sync_dart path: crdt_sync_dart
crypto: 3.0.8 crypto: 3.0.8
flutter: flutter:

View File

@ -23,6 +23,10 @@ MAVEN: Final = "maven"
# wait for, so the only reading of "current" it admits is "at HEAD". # wait for, so the only reading of "current" it admits is "at HEAD".
GITCOMMIT: Final = "gitcommit" GITCOMMIT: Final = "gitcommit"
TOOLCHAIN: Final = "toolchain" TOOLCHAIN: Final = "toolchain"
# One package out of an Arch-style repo db (`<repo>.db`), pinned by a small
# `key=value` lock file. Versions are `epoch:pkgver-pkgrel` and compare with
# pacman's vercmp, never PEP 440 (see registries/pacman_repo.py).
PACMAN_REPO: Final = "pacman-repo"
# The constraint a workflow parser writes for a version MATRIX. Standing # The constraint a workflow parser writes for a version MATRIX. Standing
# decision (kuhy, 2026-08-28): one toolchain version per repo, always newest, # decision (kuhy, 2026-08-28): one toolchain version per repo, always newest,
# so a matrix is a finding to delete rather than a range to satisfy. # so a matrix is a finding to delete rather than a range to satisfy.
@ -38,6 +42,7 @@ ECOSYSTEMS: Final = (
MAVEN, MAVEN,
GITCOMMIT, GITCOMMIT,
TOOLCHAIN, TOOLCHAIN,
PACMAN_REPO,
) )
# --- Registry endpoints ----------------------------------------------------- # --- Registry endpoints -----------------------------------------------------
@ -134,6 +139,12 @@ MANIFEST_GLOBS: Final = (
"gradle-wrapper.properties", "gradle-wrapper.properties",
) )
REQUIREMENTS_PATTERN: Final = r"^requirements.*\.txt$" REQUIREMENTS_PATTERN: Final = r"^requirements.*\.txt$"
# A pacman-repo lock has no fixed filename (`proton-native.lock` is one), so
# it is recognised by content instead of a glob: a `*.lock` file whose first
# few KB hold a `repo=` line ending in `.db`. The read is bounded because
# `--all` sniffs every Cargo.lock and pubspec.lock too.
PACMAN_LOCK_SUFFIX: Final = ".lock"
PACMAN_LOCK_SNIFF_BYTES: Final = 4096
# `.utils` is where every CI workflow checks the shared gate out, INSIDE the # `.utils` is where every CI workflow checks the shared gate out, INSIDE the
# repo being checked. Without it `--all` walks utils' own manifests and fails # repo being checked. Without it `--all` walks utils' own manifests and fails

View File

@ -19,6 +19,7 @@ from dep_freshness.parsers import (
golang, golang,
gradle, gradle,
javascript, javascript,
pacman_lock,
pubspec, pubspec,
python, python,
rust, rust,
@ -46,6 +47,7 @@ def is_manifest(path: Path) -> bool:
or bool(_REQUIREMENTS.match(path.name)) or bool(_REQUIREMENTS.match(path.name))
or workflow.is_workflow(path) or workflow.is_workflow(path)
or gradle.is_catalog(path) or gradle.is_catalog(path)
or pacman_lock.is_lock(path)
) )
@ -60,6 +62,8 @@ def parse_manifest(path: Path) -> list[Dep]:
return workflow.parse(path) return workflow.parse(path)
if gradle.is_catalog(path): if gradle.is_catalog(path):
return gradle.parse_catalog(path) return gradle.parse_catalog(path)
if pacman_lock.is_lock(path):
return pacman_lock.parse(path)
return [] return []

View File

@ -15,9 +15,10 @@ purpose:
from __future__ import annotations from __future__ import annotations
from dep_freshness._tables import GITCOMMIT, MATRIX, TOOLCHAIN from dep_freshness._tables import GITCOMMIT, MATRIX, PACMAN_REPO, TOOLCHAIN
from dep_freshness.constraints import lower_bound, satisfies from dep_freshness.constraints import lower_bound, satisfies
from dep_freshness.models import Dep, Finding, Severity from dep_freshness.models import Dep, Finding, Severity
from dep_freshness.registries.pacman_repo import vercmp
from dep_freshness.resolve import Answer from dep_freshness.resolve import Answer
from dep_freshness.versions import behind, google_api_key from dep_freshness.versions import behind, google_api_key
@ -46,6 +47,29 @@ def _commit(dep: Dep, heads: str) -> Finding | None:
) )
def _pacman(dep: Dep, answer: str) -> Finding | None:
"""A repo db lists ONE version per package; any other pin is undownloadable.
`answer` is `"<version> <sha256>"`. Compared with pacman's vercmp, so an
epoch outranks a bigger pkgver. The checksum goes into the detail so the
bump is a paste, and a right version with a wrong checksum is caught.
"""
version, _, sha = answer.partition(" ")
fix = f"version={version}" + (f" sha256={sha}" if sha else "")
if not dep.pinned:
return Finding(dep, Severity.UNPINNED, version, detail=f"pin {fix}")
if vercmp(dep.pinned, version) != 0:
return Finding(dep, Severity.STALE, version, detail=f"the repo serves {fix}")
if sha and dep.locked and dep.locked != sha.lower():
return Finding(
dep,
Severity.LOCK_MISMATCH,
version,
detail=f"lock sha256 {dep.locked} != the repo's {sha}",
)
return None
def _generation(dep: Dep, pin, latest: str) -> Finding | None: def _generation(dep: Dep, pin, latest: str) -> Finding | None:
"""A Google API client is judged inside its own generation only.""" """A Google API client is judged inside its own generation only."""
gen, rank = pin gen, rank = pin
@ -130,6 +154,8 @@ def judge(dep: Dep, answer: Answer) -> Finding | None:
return _toolchain(dep, latest) return _toolchain(dep, latest)
if dep.ecosystem == GITCOMMIT: if dep.ecosystem == GITCOMMIT:
return _commit(dep, latest) return _commit(dep, latest)
if dep.ecosystem == PACMAN_REPO:
return _pacman(dep, latest)
pin = google_api_key(dep.pinned or "") pin = google_api_key(dep.pinned or "")
if pin is not None: if pin is not None:
return _generation(dep, pin, latest) return _generation(dep, pin, latest)

View File

@ -0,0 +1,81 @@
"""A pacman-repo lock -> one package pinned out of an Arch-style repo db.
The format is one `key=value` per line, `#` comments allowed:
name=proton-cachyos-native
repo=https://mirror.cachyos.org/repo/x86_64/cachyos/cachyos.db
version=1:11.0.20261015-1
sha256=<hex>
There is no fixed filename, so `is_lock` recognises one by content: a
`*.lock` file whose first few KB hold a `repo=` line ending in `.db`. That
keeps Cargo.lock, pubspec.lock and friends out without a name list, and lets
pre-commit pass the file by name. `version` is kept verbatim: the epoch makes
it unreadable to `exact_pin`, and the judge compares it with pacman's vercmp.
`sha256` rides in `Dep.locked`, the field for "what the lock resolved to".
"""
from __future__ import annotations
import re
from pathlib import Path
from dep_freshness._tables import (
PACMAN_LOCK_SNIFF_BYTES,
PACMAN_LOCK_SUFFIX,
PACMAN_REPO,
)
from dep_freshness.models import Dep
from dep_freshness.registries.pacman_repo import qualified_name
_REPO_DB = re.compile(r"^\s*repo\s*=\s*\S+\.db\s*$", re.MULTILINE)
def is_lock(path: Path) -> bool:
"""True for a `*.lock` whose head names a repo `.db`."""
if not path.name.endswith(PACMAN_LOCK_SUFFIX):
return False
try:
with path.open("rb") as handle:
head = handle.read(PACMAN_LOCK_SNIFF_BYTES)
except OSError:
return False
return bool(_REPO_DB.search(head.decode("utf-8", errors="replace")))
def _fields(text: str) -> dict[str, tuple[str, int]]:
"""`key -> (value, 1-based line)`; the first occurrence of a key wins."""
fields: dict[str, tuple[str, int]] = {}
for number, line in enumerate(text.splitlines(), start=1):
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, _, value = stripped.partition("=")
fields.setdefault(key.strip(), (value.strip(), number))
return fields
def parse(path: Path) -> list[Dep]:
if not is_lock(path):
return []
try:
fields = _fields(path.read_text(encoding="utf-8", errors="replace"))
except OSError:
return []
name, name_line = fields.get("name", ("", 0))
repo, _ = fields.get("repo", ("", 0))
if not name or not repo:
return []
version, version_line = fields.get("version", ("", 0))
sha, _ = fields.get("sha256", ("", 0))
return [
Dep(
ecosystem=PACMAN_REPO,
name=qualified_name(repo, name),
constraint=version,
path=path,
line=version_line or name_line,
pinned=version or None,
locked=sha.lower() or None,
)
]

View File

@ -112,6 +112,20 @@ def get_text(url: str, accept: str | None = None) -> str | None:
Same contract as `get_json`; Maven metadata is XML, not JSON. Same contract as `get_json`; Maven metadata is XML, not JSON.
""" """
body = get_bytes(url, accept)
if body is None:
return None
try:
return body.decode("utf-8")
except UnicodeDecodeError as exc:
raise Offline(f"{url}: {exc}") from exc
def get_bytes(url: str, accept: str | None = None) -> bytes | None:
"""Fetch a raw body, or raise `Offline` / return None on 404.
Same contract as `get_json`; a pacman repo `.db` is a compressed tar.
"""
if not host_reachable(url): if not host_reachable(url):
raise Offline(url) raise Offline(url)
headers = {"User-Agent": USER_AGENT} headers = {"User-Agent": USER_AGENT}
@ -125,7 +139,7 @@ def get_text(url: str, accept: str | None = None) -> str | None:
attempt += 1 attempt += 1
try: try:
with urlopen(request, timeout=HTTP_TIMEOUT * attempt) as response: with urlopen(request, timeout=HTTP_TIMEOUT * attempt) as response:
return response.read().decode("utf-8") return response.read()
except HTTPError as exc: except HTTPError as exc:
if exc.code == 404: if exc.code == 404:
return None return None

View File

@ -0,0 +1,179 @@
"""Arch-style package repos: the one version a repo `.db` lists for a package.
A repo db (`cachyos.db`, `extra.db`) is a tar, gzip- or zstd-compressed, with
one `<name>-<version>/desc` entry per package. The desc file holds `%NAME%`,
`%VERSION%` and `%SHA256SUM%` blocks. A repo keeps exactly ONE version of each
package, so "newest stable" is simply whatever the db lists.
The repo URL travels inside the dep name as `<repo-url>#<package>`, because
the resolver and the cache only ever see the name (the gittag lesson). Arch
package names cannot contain `#`, so `rpartition` splits it unambiguously.
That string is also the cache key and the allowlist label.
The answer is `"<version> <sha256>"`, space-joined like gitcommit's heads:
the judge needs the version to compare and the checksum to check the lock's.
Versions compare with pacman's `vercmp` (a port of libalpm's version.c),
never PEP 440: `1:11.0.20261015-1` is not a version `packaging` can read.
"""
from __future__ import annotations
import io
import tarfile
from dep_freshness.registries.http import Offline, get_bytes
try: # stdlib since Python 3.14; tarfile's "r:*" reads zstd through it
import compression.zstd # noqa: F401
_HAS_ZSTD = True
except ImportError: # pragma: no cover - this machine runs 3.15
_HAS_ZSTD = False
_ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
_SEPARATOR = "#"
def qualified_name(repo: str, package: str) -> str:
"""The dep name for `package` out of the db at `repo`."""
return f"{repo.strip()}{_SEPARATOR}{package.strip()}"
def split_name(name: str) -> tuple[str, str]:
"""`(repo_url, package)` back out of a `qualified_name`."""
repo, _, package = name.rpartition(_SEPARATOR)
return repo, package
def _fields(desc: str) -> dict[str, str]:
"""`{"NAME": ..., "VERSION": ...}`: the first line under each `%KEY%`."""
fields: dict[str, str] = {}
lines = desc.splitlines()
for number, line in enumerate(lines[:-1]):
if len(line) > 2 and line.startswith("%") and line.endswith("%"):
fields.setdefault(line.strip("%"), lines[number + 1].strip())
return fields
def _open(url: str, body: bytes) -> tarfile.TarFile:
if body.startswith(_ZSTD_MAGIC) and not _HAS_ZSTD:
# `Offline`, not a bare error: `Resolver.latest` catches only that, so
# anything else would crash the gate instead of reporting UNKNOWN
# (exit 3 under --strict) with this message in the degraded banner.
raise Offline(
f"{url} is zstd-compressed; reading it needs Python 3.14+ "
"(compression.zstd)"
)
try:
return tarfile.open(fileobj=io.BytesIO(body), mode="r:*")
except tarfile.TarError as exc:
# A captive portal's HTML is a broken network, not an answer.
raise Offline(f"{url}: not a repo db ({exc})") from exc
def latest(name: str) -> str | None:
"""`"<version> <sha256>"` the repo lists for the package, or None.
Matched on `%NAME%`, not the directory name: `foo-` also prefixes
`foo-git-1.0-1/`. The tar is untrusted, so it is read, never extracted.
"""
repo, package = split_name(name)
body = get_bytes(repo)
if body is None:
return None
with _open(repo, body) as tar:
for member in tar:
if not (
member.isfile()
and member.name.startswith(f"{package}-")
and member.name.endswith("/desc")
):
continue
handle = tar.extractfile(member)
if handle is None:
continue
fields = _fields(handle.read().decode("utf-8", errors="replace"))
if fields.get("NAME") == package and fields.get("VERSION"):
sha = fields.get("SHA256SUM", "")
return f"{fields['VERSION']} {sha}".strip()
return None
# --- vercmp -----------------------------------------------------------------
def _alnum(char: str) -> bool:
return char.isascii() and char.isalnum()
def _rpmvercmp(a: str, b: str) -> int:
"""libalpm's `rpmvercmp`: segment-wise compare of one EVR component."""
if a == b:
return 0
i = j = 0
while i < len(a) and j < len(b):
sep_a, sep_b = i, j
while i < len(a) and not _alnum(a[i]):
i += 1
while j < len(b) and not _alnum(b[j]):
j += 1
if i >= len(a) or j >= len(b):
break
# A longer separator run sorts higher (`1.0..1` > `1.0.1`).
if i - sep_a != j - sep_b:
return -1 if i - sep_a < j - sep_b else 1
start_a, start_b = i, j
numeric = a[i].isdigit()
same_kind = str.isdigit if numeric else (lambda c: c.isascii() and c.isalpha())
while i < len(a) and same_kind(a[i]):
i += 1
while j < len(b) and same_kind(b[j]):
j += 1
seg_a, seg_b = a[start_a:i], b[start_b:j]
if not seg_b:
# Different segment kinds: a number beats letters.
return 1 if numeric else -1
if numeric:
seg_a, seg_b = seg_a.lstrip("0"), seg_b.lstrip("0")
if len(seg_a) != len(seg_b):
return 1 if len(seg_a) > len(seg_b) else -1
if seg_a != seg_b:
return 1 if seg_a > seg_b else -1
if i >= len(a) and j >= len(b):
return 0
# One side has more left: `1.0.a` > `1.0`, but `1.0a` < `1.0`.
if (i >= len(a) and not b[j].isalpha()) or (i < len(a) and a[i].isalpha()):
return -1
return 1
def _evr(text: str) -> tuple[str, str, str | None]:
"""`(epoch, pkgver, pkgrel)`; epoch defaults to "0", pkgrel may be None."""
digits = 0
while digits < len(text) and text[digits].isdigit():
digits += 1
if digits < len(text) and text[digits] == ":":
epoch, rest = text[:digits] or "0", text[digits + 1 :]
else:
epoch, rest = "0", text
version, dash, release = rest.rpartition("-")
if not dash:
return epoch, rest, None
return epoch, version, release
def vercmp(left: str, right: str) -> int:
"""-1, 0 or 1, exactly as pacman's `vercmp left right` prints.
A missing pkgrel on either side compares equal on pkgrel, so `1.0`
matches `1.0-7`.
"""
if left == right:
return 0
epoch_l, ver_l, rel_l = _evr(left)
epoch_r, ver_r, rel_r = _evr(right)
result = _rpmvercmp(epoch_l, epoch_r) or _rpmvercmp(ver_l, ver_r)
if result == 0 and rel_l is not None and rel_r is not None:
result = _rpmvercmp(rel_l, rel_r)
return result

View File

@ -18,6 +18,7 @@ from dep_freshness._tables import (
MAVEN, MAVEN,
MAX_WORKERS, MAX_WORKERS,
NPM, NPM,
PACMAN_REPO,
PUB, PUB,
PYPI, PYPI,
TOOLCHAIN, TOOLCHAIN,
@ -31,6 +32,7 @@ from dep_freshness.registries import (
gomod, gomod,
maven, maven,
npmjs, npmjs,
pacman_repo,
pub, pub,
pypi, pypi,
) )
@ -46,6 +48,7 @@ _LOOKUP = {
GITTAG: gittag.latest, GITTAG: gittag.latest,
MAVEN: maven.latest, MAVEN: maven.latest,
GITCOMMIT: gitcommit.latest, GITCOMMIT: gitcommit.latest,
PACMAN_REPO: pacman_repo.latest,
} }

View File

@ -9,6 +9,7 @@ a reason no commit can fix, which is why that combination is an error.
from __future__ import annotations from __future__ import annotations
from datetime import date, timedelta from datetime import date, timedelta
from pathlib import Path
import pytest import pytest
@ -123,7 +124,9 @@ def test_a_transitive_entry_may_not_carry_an_expiry(tmp_path):
load(tmp_path) load(tmp_path)
@pytest.mark.parametrize("field", ["ecosystem", "package", "pinned", "reason", "blocked_by"]) @pytest.mark.parametrize(
"field", ["ecosystem", "package", "pinned", "reason", "blocked_by"]
)
def test_every_required_field_is_required(tmp_path, field): def test_every_required_field_is_required(tmp_path, field):
# Blank the value rather than deleting the line: dropping `ecosystem:` # Blank the value rather than deleting the line: dropping `ecosystem:`
# would also drop the `-` that makes the entry a list item, and the test # would also drop the `-` that makes the entry a list item, and the test
@ -139,7 +142,10 @@ def test_every_required_field_is_required(tmp_path, field):
def test_a_malformed_transitive_blocker_is_an_error(tmp_path): def test_a_malformed_transitive_blocker_is_an_error(tmp_path):
_allowlist( _allowlist(
tmp_path, TRANSITIVE.replace("transitive:firebase_core@4.2.0", "transitive:firebase_core") tmp_path,
TRANSITIVE.replace(
"transitive:firebase_core@4.2.0", "transitive:firebase_core"
),
) )
with pytest.raises(AllowlistError, match="transitive:<package>@<version>"): with pytest.raises(AllowlistError, match="transitive:<package>@<version>"):
load(tmp_path) load(tmp_path)
@ -149,7 +155,8 @@ def test_a_bad_expiry_format_is_an_error(tmp_path):
_allowlist( _allowlist(
tmp_path, tmp_path,
_discretionary(30).replace( _discretionary(30).replace(
(date.today() + __import__("datetime").timedelta(days=30)).isoformat(), "next tuesday" (date.today() + __import__("datetime").timedelta(days=30)).isoformat(),
"next tuesday",
), ),
) )
with pytest.raises(AllowlistError, match="YYYY-MM-DD"): with pytest.raises(AllowlistError, match="YYYY-MM-DD"):
@ -184,7 +191,9 @@ def test_the_shared_allowlist_is_inherited(tmp_path, no_shared_allowlist):
"""A fleet-wide blocker must not have to be copied into forty repos.""" """A fleet-wide blocker must not have to be copied into forty repos."""
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8") no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
entries = load(tmp_path) entries = load(tmp_path)
assert [(e.ecosystem, e.package) for e in entries] == [("pub", "plugin_platform_interface")] assert [(e.ecosystem, e.package) for e in entries] == [
("pub", "plugin_platform_interface")
]
def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist): def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist):
@ -201,10 +210,15 @@ def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist):
assert entries[0].reason == "this repo has its own reason" assert entries[0].reason == "this repo has its own reason"
def test_shared_and_repo_entries_for_different_packages_both_apply(tmp_path, no_shared_allowlist): def test_shared_and_repo_entries_for_different_packages_both_apply(
tmp_path, no_shared_allowlist
):
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8") no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
_allowlist(tmp_path, _discretionary(30)) _allowlist(tmp_path, _discretionary(30))
assert {e.package for e in load(tmp_path)} == {"plugin_platform_interface", "abandoned"} assert {e.package for e in load(tmp_path)} == {
"plugin_platform_interface",
"abandoned",
}
def test_a_malformed_shared_allowlist_is_an_error(tmp_path, no_shared_allowlist): def test_a_malformed_shared_allowlist_is_an_error(tmp_path, no_shared_allowlist):
@ -217,5 +231,9 @@ def test_the_shared_path_defaults_to_the_gate_repo(monkeypatch):
from dep_freshness.allowlist import shared_path from dep_freshness.allowlist import shared_path
monkeypatch.delenv("DEP_FRESHNESS_SHARED_ALLOWLIST", raising=False) monkeypatch.delenv("DEP_FRESHNESS_SHARED_ALLOWLIST", raising=False)
import dep_freshness
# The gate repo is whatever checkout holds the package (~/src/utils, a
# worktree, a snapshot), so compare paths, not the folder's name.
assert shared_path().name == NAME assert shared_path().name == NAME
assert shared_path().parent.name == "utils" assert shared_path().parent == Path(dep_freshness.__file__).resolve().parent.parent

View File

@ -0,0 +1,135 @@
"""A pacman-repo lock: parsed, discovered, and judged end to end.
The consumer is steam-game-installer's `steam_installer/data/proton-native.lock`,
which pins one package out of the CachyOS repo. Pre-commit hands the gate the
file by name, so `is_manifest` must accept it on content, not on a glob.
"""
from __future__ import annotations
import json
import pytest
from dep_freshness import check, discover
from dep_freshness.models import Severity
from dep_freshness.parsers import pacman_lock
from dep_freshness.registries import pacman_repo
from dep_freshness.tests.conftest import write
from dep_freshness.tests.test_pacman_repo import SHA, build_db
REPO = "https://mirror.cachyos.org/repo/x86_64/cachyos/cachyos.db"
LOCK = f"""\
# pacman-repo lock: newest stable package from an Arch-style repo db
name=proton-cachyos-native
repo={REPO}
version=1:11.0.20261015-1
sha256={SHA}
"""
LOCK_PATH = "steam_installer/data/proton-native.lock"
def test_the_lock_parses_to_one_pinned_dep(repo):
path = write(repo, LOCK_PATH, LOCK)
[dep] = pacman_lock.parse(path)
assert dep.ecosystem == "pacman-repo"
assert pacman_repo.split_name(dep.name) == (REPO, "proton-cachyos-native")
assert dep.pinned == "1:11.0.20261015-1"
assert dep.locked == SHA
assert dep.line == 4 # the version= line is what a bump edits
@pytest.mark.parametrize(
("name", "body"),
[
("Cargo.lock", '[[package]]\nname = "serde"\nversion = "1.0.0"\n'),
("other.lock", "name=x\nrepo=https://example.org/not-a-db.json\n"),
("proton-native.txt", LOCK),
],
)
def test_other_files_are_not_pacman_locks(repo, name, body):
path = write(repo, name, body)
assert not discover.is_manifest(path)
assert discover.parse_manifest(path) == []
def test_the_lock_is_discovered_by_content(repo):
path = write(repo, LOCK_PATH, LOCK)
assert discover.is_manifest(path)
assert path in discover.find_manifests(repo)
def test_a_lock_without_a_version_is_unpinned(repo):
path = write(repo, "x.lock", LOCK.replace("version=1:11.0.20261015-1\n", ""))
[dep] = pacman_lock.parse(path)
assert dep.pinned is None
@pytest.fixture
def gate(repo, monkeypatch):
"""Run the CLI on the lock, with the repo db answering `served`."""
def invoke(lock_body, served, *flags):
name, version, sha = served
body = build_db({name: version}, sha=sha)
monkeypatch.setattr(pacman_repo, "get_bytes", lambda _url: body)
path = write(repo, LOCK_PATH, lock_body)
monkeypatch.chdir(repo)
return check.main([*flags, str(path)])
return invoke
CURRENT = ("proton-cachyos-native", "1:11.0.20261015-1", SHA)
def test_a_current_lock_passes(gate):
assert gate(LOCK, CURRENT, "--strict") == 0
def test_a_lock_behind_the_repo_fails(gate, capsys):
old = LOCK.replace("1:11.0.20261015-1", "1:10.0.20250101-1")
assert gate(old, CURRENT) == 1
out = capsys.readouterr()
text = out.out + out.err
assert "proton-cachyos-native" in text
assert "1:11.0.20261015-1" in text
assert SHA in text # the bump is copy-pasteable
def test_an_epoch_beats_a_bigger_pkgver(gate):
# PEP 440 would read `11.0` > `1:2.0` (or nothing at all); pacman says the
# epoch wins, so a lock on 11.0 is behind a repo on 1:2.0.
old = LOCK.replace("1:11.0.20261015-1", "11.0-1")
assert gate(old, ("proton-cachyos-native", "1:2.0-1", SHA)) == 1
def test_a_right_version_with_a_wrong_sha_is_a_mismatch(gate, capsys):
assert gate(LOCK, (*CURRENT[:2], "cd" * 32), "--json") == 1
payload = json.loads(capsys.readouterr().out)
assert Severity.LOCK_MISMATCH.value in json.dumps(payload)
def test_a_package_the_repo_dropped_is_undeterminable(gate):
assert gate(LOCK, ("something-else", "1.0-1", SHA), "--strict") == 3
def test_offline_with_a_cold_cache_is_undeterminable(repo, monkeypatch):
from dep_freshness.registries import http
http.force_offline(True)
path = write(repo, LOCK_PATH, LOCK)
monkeypatch.chdir(repo)
assert check.main(["--strict", str(path)]) == 3
assert check.main([str(path)]) == 0 # pre-commit degrades, never corners
def test_zstd_on_an_old_python_is_undeterminable_not_a_crash(
repo, monkeypatch, capsys
):
body = build_db({"proton-cachyos-native": "1:11.0.20261015-1"}, "zst")
monkeypatch.setattr(pacman_repo, "get_bytes", lambda _url: body)
monkeypatch.setattr(pacman_repo, "_HAS_ZSTD", False)
path = write(repo, LOCK_PATH, LOCK)
monkeypatch.chdir(repo)
assert check.main(["--strict", str(path)]) == 3
out = capsys.readouterr()
assert "compression.zstd" in out.out + out.err

View File

@ -0,0 +1,146 @@
"""The pacman-repo adapter: pacman `vercmp` order and reading a repo `.db`.
Versions here are `epoch:pkgver-pkgrel`, which PEP 440 cannot read at all:
`versions.behind` answers False for every pair, so a stale lock would read
as current. The ordering tests below come from the vercmp(8) man page, and
the differential test checks them against the real `/usr/bin/vercmp`.
"""
from __future__ import annotations
import io
import itertools
import shutil
import subprocess
import tarfile
import pytest
from dep_freshness.registries import pacman_repo
from dep_freshness.registries.http import Offline
REPO = "https://mirror.example.org/repo/x86_64/extra/extra.db"
SHA = "ab" * 32
# vercmp(8): "1.0a < 1.0b < 1.0beta < 1.0p < 1.0pre < 1.0rc < 1.0 < 1.0.a < 1.0.1"
MAN_ORDER = ["1.0a", "1.0b", "1.0beta", "1.0p", "1.0pre", "1.0rc", "1.0", "1.0.a",
"1.0.1"]
PAIRS = [
("1:1.0", "2.0", 1),
("0:2.0", "2.0", 0),
("1:11.0.20261015-1", "1:10.0.20250101-1", 1),
("1:11.0.20261015-1", "1:11.0.20261015-1", 0),
("1.0-1", "1.0-2", -1),
("1.0", "1.0-7", 0), # a missing pkgrel compares equal
("1.0.0", "1.0", 1),
("1.0_1", "1.0.1", 0), # any non-alphanumeric run is one separator
("1.0", "1.0.0.0", -1),
("2.0", "10.0", -1),
("1.001", "1.1", 0),
("r123", "r45", 1),
]
@pytest.mark.parametrize(("left", "right"), list(itertools.pairwise(MAN_ORDER)))
def test_vercmp_follows_the_man_page_order(left, right):
assert pacman_repo.vercmp(left, right) == -1
assert pacman_repo.vercmp(right, left) == 1
@pytest.mark.parametrize(("left", "right", "expected"), PAIRS)
def test_vercmp_epoch_and_pkgrel(left, right, expected):
assert pacman_repo.vercmp(left, right) == expected
@pytest.mark.skipif(not shutil.which("vercmp"), reason="pacman's vercmp absent")
@pytest.mark.parametrize(
("left", "right"),
[*itertools.pairwise(MAN_ORDER), *((a, b) for a, b, _ in PAIRS)],
)
def test_vercmp_agrees_with_pacman(left, right):
real = subprocess.run(
["vercmp", left, right], capture_output=True, text=True, check=True
).stdout.strip()
assert pacman_repo.vercmp(left, right) == int(real)
def _desc(name: str, version: str, sha: str = SHA) -> bytes:
return (
f"%FILENAME%\n{name}-{version}-x86_64.pkg.tar.zst\n\n%NAME%\n{name}\n\n"
f"%VERSION%\n{version}\n\n%SHA256SUM%\n{sha}\n\n"
).encode()
def build_db(
packages: dict[str, str], compression: str = "gz", sha: str = SHA
) -> bytes:
"""A repo db the way repo-add writes it: one `<name>-<ver>/desc` per package."""
raw = io.BytesIO()
with tarfile.open(fileobj=raw, mode=f"w:{compression}") as tar:
for name, version in packages.items():
body = _desc(name, version, sha)
info = tarfile.TarInfo(f"{name}-{version}/desc")
info.size = len(body)
tar.addfile(info, io.BytesIO(body))
return raw.getvalue()
@pytest.fixture
def serve(monkeypatch):
"""Answer the next `get_bytes` with `body`, recording the URL asked for."""
asked: list[str] = []
def install(body):
def fake(url):
asked.append(url)
return body
monkeypatch.setattr(pacman_repo, "get_bytes", fake)
return asked
return install
@pytest.mark.parametrize("compression", ["gz", "zst"])
def test_latest_reads_version_and_sha_from_the_db(serve, compression):
asked = serve(build_db({"proton-native": "1:11.0-1", "zlib": "1.3-1"},
compression))
name = pacman_repo.qualified_name(REPO, "proton-native")
assert pacman_repo.latest(name) == f"1:11.0-1 {SHA}"
assert asked == [REPO]
def test_a_sibling_sharing_the_name_prefix_is_not_the_package(serve):
serve(build_db({"proton-native-v3": "9:9.0-1", "proton-native": "1:2.0-1"}))
name = pacman_repo.qualified_name(REPO, "proton-native")
assert pacman_repo.latest(name).split()[0] == "1:2.0-1"
def test_a_package_the_db_does_not_list_is_none(serve):
serve(build_db({"zlib": "1.3-1"}))
assert pacman_repo.latest(pacman_repo.qualified_name(REPO, "nope")) is None
def test_a_missing_db_is_none(serve):
serve(None)
assert pacman_repo.latest(pacman_repo.qualified_name(REPO, "x")) is None
def test_a_db_that_is_not_a_tar_is_offline(serve):
serve(b"<html>captive portal</html>")
with pytest.raises(Offline):
pacman_repo.latest(pacman_repo.qualified_name(REPO, "x"))
def test_zstd_without_compression_zstd_names_the_missing_module(
serve, monkeypatch
):
serve(build_db({"x": "1.0-1"}, "zst"))
monkeypatch.setattr(pacman_repo, "_HAS_ZSTD", False)
with pytest.raises(Offline, match="compression.zstd"):
pacman_repo.latest(pacman_repo.qualified_name(REPO, "x"))
def test_qualified_name_round_trips():
assert pacman_repo.split_name(pacman_repo.qualified_name(REPO, "x")) == (
REPO,
"x",
)

View File

@ -0,0 +1,129 @@
# 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:<for_day>:<done>:<target>",
"day": "<for_day>", "amount": 0, "device": "...", "created_at": "...",
"detail": {"source": "<progress source>", "for_day": "YYYY-MM-DD",
"done": "<digits>", "target": "<digits>"},
"hmac": "<entry_signature>"}
```
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`. Among the matching rows that verify, the last one
in file order wins, and `done` and `target` both come from that one row. A gate
can re-derive its target within a day (book-guard does), so mixing rows would
pair a stale target with a new done. The rule reads neither `created_at` nor
`device` (the workout ledger writes neither). A later row that fails any check
above is skipped, so the last good row wins; no good row is `None`. A signed
row copied to the end of the file wins as it is: the key is the trust, not the
position.
`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.
## The review: no row, no pay (from `REVIEW_PROGRESS_FROM`)
kuhy's rule (2026-11-22): the review top-up pays in equal slices, `bonus * done
// target`, the writer freezing the target at the day's first review. From
`REVIEW_PROGRESS_FROM` (2026-11-24, the day after the 2026-11-23 release; a rule
that lowers pay never lands on its deploy day) the review differs from the other
earners:
- a credited review (a yes) pays only by its row: `done` of `target` of 20
minutes, never more than 20; the gaming twin is 0 as ever, and a sick day adds
the same minutes on top of 20:00;
- a credited review with no row pays **0**, not the flat 20, and logs a warning;
- a row that fails verification (bad signature, edited, wrong day or source,
unreadable numbers) is no row, so it pays 0 too. This is deliberate: fail
closed, visible in the log, never a flat 20 for a row nobody can vouch for;
- a no or `None` pays 0 whatever a row says: the guard's accepted submission, not
the row, is the evidence that a review happened (`DOCS-review.md`).
Before `REVIEW_PROGRESS_FROM` the review pays as in 0.23.0 (a yes pays 20, a no
0) and ignores every progress row.
## One derivation: `term_for`
`term_for(earner, day, *, answer, progress=None) -> Term` is the only place an
earner's pay for a day is derived, and `resolve` builds every one of its terms
through it. A consumer that prices one earner (the screen-locker's live pass)
reads the row with `read_progress` and calls it; it reads `shutdown_minutes`
and `gaming_minutes` off the `Term`. **Consumers never re-derive a share**: the
review's dated rule, the ladder rung, the floor and the cap at full all live
here, and a local `full * done // target` goes stale the day a rule changes.
```python
fact = earned_time.read_progress(earner, ledger, key_file, day, gate_off=off)
pay = earned_time.term_for(earner, day, answer=answer, progress=fact).shutdown_minutes
```
`answer` is the unit count (`True`/`False` are 1/0) or `None`; `progress` is the
verified row or `None`. A test pins that the two always agree for every earner,
answer, row and day either side of `REVIEW_PROGRESS_FROM`.
## 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.

31
earned_time/DOCS-tutor.md Normal file
View File

@ -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.

View File

@ -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 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. (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 **The tutor row contract (0.8.0, mixed-day safe)** — `detail.minutes`, one row per
each counting row pays instead of counting rows (`_credits.row_units`, the credited minute, the legacy 15-minute block, an `entry_id` paying once and what
per-matcher reader `_match.ROW_UNITS`): the writer must guarantee: [DOCS-tutor.md](DOCS-tutor.md).
- `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.
**Gap waiver** (`ANKI_WAIVED_FROM`, 2026-10-09): no anki/automation earner. **Gap waiver** (`ANKI_WAIVED_FROM`, 2026-10-09): no anki/automation earner.
@ -145,6 +121,18 @@ 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 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). 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, from the day's last good row. A yes pays full and "could not check"
nothing, as ever; with no row anywhere every output is 0.23.0's, the review
excepted. The row, the reader and every fail-closed case are in
[DOCS-progress.md](DOCS-progress.md). The review differs from `REVIEW_PROGRESS_FROM` (2026-11-24): a credited review
pays only by its row (`20 * done // target`), and with no verified row pays 0.
One earner's pay for a day is `term_for(earner, day, *, answer, progress=None)`,
the code `resolve` itself uses: consumers never re-derive a share.
## Gate maturity (0.6.0) ## Gate maturity (0.6.0)
How far to trust a gate, computed from its ledger by `maturity()`, is in How far to trust a gate, computed from its ledger by `maturity()`, is in
@ -153,7 +141,7 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in
## API ## API
- `resolve(answers, day=None, earners=None, *, first_credits=None, sick=False, - `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, day) -> int`. `base_for(day=None, earners=None, *, first_credits=None,
leisure=None) -> Base` — the day's floors. `gaming_base_minutes_for(day)`, leisure=None) -> Base` — the day's floors. `gaming_base_minutes_for(day)`,
`gaming_ceiling_minutes_for(day) -> int` — the gaming base and cap. `gaming_ceiling_minutes_for(day) -> int` — the gaming base and cap.
@ -179,6 +167,11 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in
`REVIEW_SOURCE`, `GUARD_LEDGER`, `ACCEPTED_LOOKBACK_DAYS`, `review_match`, `REVIEW_SOURCE`, `GUARD_LEDGER`, `ACCEPTED_LOOKBACK_DAYS`, `review_match`,
`paid_reviews`, `guard_ledger_for(ledger, earner) -> Path | None`; `paid_reviews`, `guard_ledger_for(ledger, earner) -> Path | None`;
`Earner.topup` and `Earner.evidence` (0.23.0). `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`, `REVIEW_PROGRESS_FROM`,
`term_for(earner, day, *, answer, progress=None) -> Term` (0.24.0).
## The workout ledger ## The workout ledger
@ -242,7 +235,7 @@ Unbacked timer time pays 0 from 2026-11-08 (focus_project 0.10.0).
## Install ## Install
```console ```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 The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy` and imports from

View File

@ -26,6 +26,10 @@ A consumer's whole integration::
gaming budget; shutdown is the only carrot. ``Resolution.gaming_enforced`` gaming budget; shutdown is the only carrot. ``Resolution.gaming_enforced``
carries it; a consumer that applies a budget lifts the limit on ``False``. 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. ``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`` ``leisure`` (0.16.0): ``None`` follows the switch file on ``day``, ``True``
prices gaming with the leisure base and cap (the shadow budget), ``False`` prices gaming with the leisure base and cap (the shadow budget), ``False``
@ -53,6 +57,7 @@ from earned_time._ladder import (
ANKI_WAIVED_FROM, ANKI_WAIVED_FROM,
LADDER, LADDER,
LADDER_FROM, LADDER_FROM,
REVIEW_PROGRESS_FROM,
SHUTDOWN_CEILING_MINUTES, SHUTDOWN_CEILING_MINUTES,
TUTOR_FROM, TUTOR_FROM,
TUTOR_LADDER, TUTOR_LADDER,
@ -101,6 +106,7 @@ from earned_time._policy import (
Earner, Earner,
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._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
@ -116,6 +122,7 @@ from earned_time._review import (
paid_reviews, paid_reviews,
review_match, review_match,
) )
from earned_time._share import term_for
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__ = [
@ -142,6 +149,7 @@ __all__ = [
"REVIEW", "REVIEW",
"REVIEW_FROM", "REVIEW_FROM",
"REVIEW_LEDGER", "REVIEW_LEDGER",
"REVIEW_PROGRESS_FROM",
"REVIEW_SHUTDOWN_MINUTES", "REVIEW_SHUTDOWN_MINUTES",
"REVIEW_SOURCE", "REVIEW_SOURCE",
"SHUTDOWN_BASE_MINUTES", "SHUTDOWN_BASE_MINUTES",
@ -162,6 +170,7 @@ __all__ = [
"FocusEarner", "FocusEarner",
"Level", "Level",
"Maturity", "Maturity",
"Progress",
"Resolution", "Resolution",
"Rung", "Rung",
"Term", "Term",
@ -187,6 +196,8 @@ __all__ = [
"on_ladder", "on_ladder",
"paid_reviews", "paid_reviews",
"penalty_start", "penalty_start",
"progress_map",
"read_progress",
"real_credit", "real_credit",
"registries", "registries",
"resolve", "resolve",
@ -194,6 +205,7 @@ __all__ = [
"shutdown_ceiling_for", "shutdown_ceiling_for",
"shutdown_minutes_for", "shutdown_minutes_for",
"sick_shutdown_from", "sick_shutdown_from",
"term_for",
"today_window", "today_window",
"tutor_quota_for", "tutor_quota_for",
"verified", "verified",

View File

@ -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)

View File

@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Final, Protocol
from earned_time._ladder import shutdown_units_minutes from earned_time._ladder import shutdown_units_minutes
from earned_time._match import focus_match from earned_time._match import focus_match
from earned_time._policy import Earner from earned_time._policy import Earner
from earned_time._share import share_minutes
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable from collections.abc import Iterable
@ -53,7 +54,9 @@ class FocusEarner(Earner):
def gaming_for(self, units: int) -> int: def gaming_for(self, units: int) -> int:
"""Gaming minutes of ``units`` focused minutes, floored.""" """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( def shutdown_for(
self, self,
@ -62,7 +65,9 @@ class FocusEarner(Earner):
) -> int: ) -> int:
"""Shutdown minutes of ``units`` focused minutes, floored.""" """Shutdown minutes of ``units`` focused minutes, floored."""
del day # the base signature takes it; focus pay is the same every day 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: def _active(day: date) -> _Project | None:

View File

@ -55,6 +55,11 @@ ANKI_WAIVED_FROM: Final = date(2026, 10, 9)
# screen-locker's late-credit rule shipped (46393fa, 2026-10-17): an 18:00 # screen-locker's late-credit rule shipped (46393fa, 2026-10-17): an 18:00
# floor without it locked out a credit landing after the shutdown. # floor without it locked out a credit landing after the shutdown.
UNIFIED_FROM: Final = date(2026, 10, 18) UNIFIED_FROM: Final = date(2026, 10, 18)
# From this day a credited LeetCode review with no verified progress row pays
# nothing, and with one pays ``bonus * done // target`` (0.24.0). It lowers
# pay, so it lands the day after the release (2026-11-23), never on it. Before
# it the review pays exactly as in 0.23.0, a row or not.
REVIEW_PROGRESS_FROM: Final = date(2026, 11, 24)
_SLEEP_MINUTES: Final = 8 * 60 _SLEEP_MINUTES: Final = 8 * 60
_DAY_MINUTES: Final = 24 * 60 _DAY_MINUTES: Final = 24 * 60

View File

@ -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 **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 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 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`). ``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`. 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 **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
@ -61,24 +61,23 @@ class Earner:
label: Human name, for logs and reason strings. label: Human name, for logs and reason strings.
gaming_minutes: Gaming time the first unit earns. gaming_minutes: Gaming time the first unit earns.
shutdown_minutes: How much later shutdown moves for the first unit. shutdown_minutes: How much later shutdown moves for the first unit.
kind: ``"flat"`` earns once per day from a yes/no answer; kind: ``"flat"`` earns once a day from a yes/no answer; ``"counted"``
``"counted"`` earns per unit (the workout), and its live credit is per unit (the workout), its live credit applied by the consumer.
applied by the consumer that counts the units.
extra_shutdown_minutes: Each further unit, for ``"counted"`` earners. extra_shutdown_minutes: Each further unit, for ``"counted"`` earners.
extra_gaming_minutes: Gaming time each further unit earns extra_gaming_minutes: Gaming time each further unit earns
(``"counted"``); the workout's are 0, the tutor's 1 (per minute). (``"counted"``); the workout's are 0, the tutor's 1 (per minute).
max_units: The most units one day can pay; ``None`` is unbounded. 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 penalty_from: From this day the gaming base drops by the most the
earner can pay (:attr:`max_gaming_minutes`). ``None`` means a pure earner can pay (:attr:`max_gaming_minutes`); ``None``: a pure bonus.
bonus. ledger: The gate's HMAC-signed ledger, relative to the home directory;
ledger: The gate's HMAC-signed ledger, relative to the home directory. ``None``: no shared reader, the consumer supplies the answer.
``None`` means no shared reader: the consumer supplies the answer.
match: Which verified ``credit`` rows count for today. match: Which verified ``credit`` rows count for today.
missing_ledger_is_no: A ledger that does not exist yet is an honest missing_ledger_is_no: A ledger that does not exist yet is an honest
"no" (the gate never ran), not a fault. "no" (the gate never ran), not a fault.
confirmed_on: The day kuhy confirmed a real working session; set by confirmed_on: The day kuhy confirmed a real working session, by hand;
hand, never derived. ``None`` keeps the gate "new" ``None`` keeps the gate "new" (:func:`earned_time.maturity`).
(: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 ``shutdown_minutes`` and ``extra_shutdown_minutes`` are the pre-ladder
values; from ``LADDER_FROM`` the earner's :class:`Rung` in ``LADDER`` values; from ``LADDER_FROM`` the earner's :class:`Rung` in ``LADDER``
@ -98,6 +97,7 @@ class Earner:
extra_gaming_minutes: int = 0 extra_gaming_minutes: int = 0
max_units: int | None = None max_units: int | None = None
confirmed_on: date | None = None confirmed_on: date | None = None
progress_source: str | None = None
@property @property
def topup(self) -> bool: def topup(self) -> bool:
@ -106,7 +106,7 @@ class Earner:
@property @property
def evidence(self) -> RowEvidence | None: 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 return None
def capped(self, units: int) -> int: def capped(self, units: int) -> int:
@ -143,13 +143,13 @@ WORKOUT: Final = Earner(
shutdown_minutes=2 * 60, shutdown_minutes=2 * 60,
kind="counted", kind="counted",
extra_shutdown_minutes=60, extra_shutdown_minutes=60,
# screen-locker writes one signed row per credited unit (a verified # One signed row per credited unit (a verified TCX, or a rest day).
# RunnerUp TCX, or a rest day); ``credit_units`` counts them.
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,
# First verified credit, read off the real ledger (0.6.0, 2026-10-09). # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
confirmed_on=date(2026, 10, 1), confirmed_on=date(2026, 10, 1),
progress_source="workout",
) )
LEETCODE: Final = Earner( LEETCODE: Final = Earner(
name="leetcode", name="leetcode",
@ -160,6 +160,7 @@ LEETCODE: Final = Earner(
match=leetcode_match, match=leetcode_match,
# First verified credit, read off the real ledger (0.6.0, 2026-10-09). # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
confirmed_on=date(2026, 8, 12), confirmed_on=date(2026, 8, 12),
progress_source="leetcode",
) )
READING: Final = Earner( READING: Final = Earner(
name="reading", name="reading",
@ -172,6 +173,7 @@ READING: Final = Earner(
missing_ledger_is_no=True, missing_ledger_is_no=True,
# First verified credit, read off the real ledger (0.6.0, 2026-10-09). # First verified credit, read off the real ledger (0.6.0, 2026-10-09).
confirmed_on=date(2026, 10, 2), confirmed_on=date(2026, 10, 2),
progress_source="reading",
) )
ANKI: Final = Earner( ANKI: Final = Earner(
name="anki", name="anki",
@ -183,9 +185,8 @@ ANKI: Final = Earner(
match=anki_match, match=anki_match,
missing_ledger_is_no=True, missing_ledger_is_no=True,
) )
# Same gate, same row shape: anki-guard's ``automation`` quota (the Automation # anki-guard's ``automation`` quota (its own ledger, same row shape): the Anki
# deck only) writes its own ledger, so the Anki day matcher applies unchanged. # day matcher applies unchanged. Days before ``TUTOR_FROM`` only; then TUTOR.
# Days before ``TUTOR_FROM`` only; from then on see TUTOR.
AUTOMATION: Final = Earner( AUTOMATION: Final = Earner(
name="automation", name="automation",
label="Automation", label="Automation",
@ -197,9 +198,8 @@ AUTOMATION: Final = Earner(
missing_ledger_is_no=True, missing_ledger_is_no=True,
) )
# 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 (a 0.7.0 15-minute
# 15-minute block row counts 15), up to 60 a day; Anki's 30 is folded in. # 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).
TUTOR: Final = Earner( TUTOR: Final = Earner(
name="tutor", name="tutor",
label="Tutor", label="Tutor",
@ -214,9 +214,8 @@ TUTOR: Final = Earner(
ledger=".local/share/tutor/ledger.json", ledger=".local/share/tutor/ledger.json",
match=tutor_match, match=tutor_match,
missing_ledger_is_no=True, missing_ledger_is_no=True,
# Confirmed by kuhy on 2026-10-10 before any block had paid out, dated the # Confirmed 2026-10-10 before any block paid; dated a day early so the -60
# day before so the -60 gaming penalty applies on TUTOR_FROM itself # penalty applies on TUTOR_FROM itself (it starts at confirmed_on + 1).
# (penalty starts at confirmed_on + 1).
confirmed_on=date(2026, 10, 9), confirmed_on=date(2026, 10, 9),
) )

View File

@ -0,0 +1,140 @@
# 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>:<done>:<target>",
"day": "<day>", "amount": 0, "device": ..., "created_at": ...,
"detail": {"source": <progress source>, "for_day": "YYYY-MM-DD",
"done": "<digits>", "target": "<digits>"}, "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``.
Of the rows that verify and match, the last one in file order wins, and
``done`` and ``target`` both come from it. A later row that fails
verification, is for another kind, source or day, or has unreadable numbers
is skipped, so the last good row wins. ``None`` for: no good row, 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
# The last good row in file order wins, as one (done, target) pair: a gate
# can re-derive its target within a day, so mixing rows would pair a stale
# target with a new done. Nothing here reads created_at or device (the
# workout ledger writes neither).
for row in reversed(rows):
if (
isinstance(row, dict)
and (f := _fact(row, source, day))
and verified(row, key)
):
return f
return None
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

View File

@ -14,6 +14,7 @@ if TYPE_CHECKING:
from datetime import date from datetime import date
from earned_time._policy import Earner from earned_time._policy import Earner
from earned_time._progress import Progress
@dataclass(frozen=True) @dataclass(frozen=True)
@ -39,12 +40,15 @@ class Term:
"could not check" (and for no answer at all). "could not check" (and for no answer at all).
gaming_minutes: Gaming minutes earned. gaming_minutes: Gaming minutes earned.
shutdown_minutes: Shutdown 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 earner: Earner
answer: int | None answer: int | None
gaming_minutes: int gaming_minutes: int
shutdown_minutes: int shutdown_minutes: int
progress: Progress | None = None
@dataclass(frozen=True) @dataclass(frozen=True)

View File

@ -25,19 +25,21 @@ from datetime import UTC, date, datetime
import logging import logging
from typing import TYPE_CHECKING, Final 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._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._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._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._share import term_for
from earned_time._sick import sick_or from earned_time._sick import sick_or
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Mapping from collections.abc import Mapping
from earned_time._policy import Earner
from earned_time._progress import Progress
_logger: Final = logging.getLogger(__name__) _logger: Final = logging.getLogger(__name__)
Answer = int | bool | None Answer = int | bool | None
@ -47,56 +49,6 @@ def _today() -> date:
return datetime.now(tz=UTC).astimezone().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( def base_for(
day: date | None = None, day: date | None = None,
earners: tuple[Earner, ...] | 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). """The floor for ``day`` (default today) under ``earners`` (default its own).
Gaming: every penalty in force, the most each earner can pay, taken off 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. derived separately so the ladder can never move a gaming minute.
``first_credits`` (per earner name) delays each penalty, and the ladder ``first_credits`` (per earner name) delays each penalty, and the ladder
rung, to :func:`penalty_start`; omitted, 0.5.0's ``penalty_from`` applies. rung, to :func:`penalty_start`; omitted, 0.5.0's ``penalty_from`` applies.
@ -128,20 +80,13 @@ def _base(
*, *,
on: bool, on: bool,
) -> Base: ) -> 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( return Base(
gaming_minutes=base_minutes(leisure=on) gaming_minutes=base_minutes(leisure=on) - sum(gaming_cut(e) for e in penalised),
- sum(_gaming_cut(e) for e in penalised), shutdown_minutes=shutdown_floor(target, registry, penalised),
shutdown_minutes=_shutdown_floor(target, registry, penalised),
) )
def _units(answer: Answer) -> int | None:
if answer is None:
return None
return max(0, int(answer))
def _check_registered( def _check_registered(
answers: Mapping[str, Answer], registry: tuple[Earner, ...] answers: Mapping[str, Answer], registry: tuple[Earner, ...]
) -> None: ) -> None:
@ -153,19 +98,25 @@ def _check_registered(
raise KeyError(msg) raise KeyError(msg)
def _term(item: Earner, answers: Mapping[str, Answer], day: date) -> Term: def _term(
"""``item``'s term on ``day``; no answer at all is logged and earns nothing.""" 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.
The pay itself is :func:`~earned_time.term_for`, shared with every consumer.
"""
if item.name not in answers: if item.name not in answers:
_logger.warning( _logger.warning(
"No answer for the %s earner; it earns nothing today", item.label "No answer for the %s earner; it earns nothing today", item.label
) )
units = _units(answers.get(item.name)) return term_for(
count = units or 0 item,
return Term( day,
earner=item, answer=answers.get(item.name),
answer=units, progress=(progress or {}).get(item.name),
gaming_minutes=item.gaming_for(count),
shutdown_minutes=item.shutdown_for(count, day),
) )
@ -177,6 +128,7 @@ def resolve(
first_credits: Mapping[str, date | None] | None = None, first_credits: Mapping[str, date | None] | None = None,
sick: bool = False, sick: bool = False,
leisure: bool | None = None, leisure: bool | None = None,
progress: Mapping[str, Progress] | None = None,
) -> Resolution: ) -> Resolution:
"""Sum the base and every earned term, each capped at its ceiling. """Sum the base and every earned term, each capped at its ceiling.
@ -205,6 +157,10 @@ def resolve(
shutdown are unchanged. From ``GAMING_UNLIMITED_FROM`` (0.22.0) shutdown are unchanged. From ``GAMING_UNLIMITED_FROM`` (0.22.0)
``None`` is always the old base: read ``None`` is always the old base: read
``Resolution.gaming_enforced``, the budget is not a limit. ``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: Returns:
The resolution, with a term for every registered earner. The resolution, with a term for every registered earner.
@ -219,7 +175,7 @@ def resolve(
# One switch-file read per resolve, so base and cap can never disagree. # One switch-file read per resolve, so base and cap can never disagree.
on = is_leisure(target, leisure=leisure) on = is_leisure(target, leisure=leisure)
base = _base(target, registry, first_credits, on=on) 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) gaming = base.gaming_minutes + sum(t.gaming_minutes for t in terms)
earned = min( earned = min(
shutdown_ceiling_for(target), shutdown_ceiling_for(target),

View File

@ -243,4 +243,5 @@ REVIEW: Final = ReviewEarner(
ledger=REVIEW_LEDGER, ledger=REVIEW_LEDGER,
match=review_match, match=review_match,
missing_ledger_is_no=True, missing_ledger_is_no=True,
progress_source="review",
) )

View File

@ -0,0 +1,130 @@
# 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
import logging
from typing import TYPE_CHECKING, Final
from earned_time._ladder import REVIEW_PROGRESS_FROM, shutdown_minutes_for
from earned_time._resolution import Term
from earned_time._review import ReviewEarner
if TYPE_CHECKING:
from datetime import date
from earned_time._policy import Earner
from earned_time._progress import Progress
_logger: Final = logging.getLogger(__name__)
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
)
def share_term(item: Earner, units: int | None, day: date, share: Progress) -> Term:
"""``item``'s term on ``day`` when it is paid as a share of ``share``."""
return Term(
item,
units,
gaming_share(item, share),
shutdown_share(item, share, day),
share,
)
def _review_term(
item: Earner, units: int | None, day: date, progress: Progress | None
) -> Term:
"""The review's term from ``REVIEW_PROGRESS_FROM``: a credited review needs a row.
Only a credited review (a yes) pays, and then ``bonus * done // target`` of
the signed row, never more than the full bonus. A yes with no row pays 0:
a row that fails verification is no row, so it pays 0 too (fail closed,
logged). A no and ``None`` pay 0 whatever a row says, since the guard's
accepted submission, not the row, is the evidence a review happened.
"""
share = progress if units else None
if units and share is None:
_logger.warning(
"%s credited with no progress row on %s; it pays nothing",
item.label,
day,
)
if share is None:
return Term(item, units, 0, 0)
return share_term(item, units, day, share)
def term_for(
earner: Earner,
day: date,
*,
answer: int | bool | None,
progress: Progress | None = None,
) -> Term:
"""What ``earner`` pays on ``day``: the one derivation, for every consumer.
:func:`~earned_time.resolve` builds each of its terms here, so a consumer
pricing one earner (the screen-locker's live pass) cannot disagree with it:
consumers never re-derive a share. Read ``shutdown_minutes`` and
``gaming_minutes`` off the result; ``Term.progress`` is the row it was
paid from.
Args:
earner: The earner (its ladder rung on ``day`` is the full pay).
day: The day priced.
answer: The consumer's answer: a unit count (``True``/``False`` are
1/0), or ``None`` for "could not check", which earns nothing.
progress: The earner's verified signed row for ``day``
(:func:`~earned_time.read_progress`), or ``None`` for no row.
Returns:
The term. A yes pays full as ever. A no pays ``full * done // target``
of ``progress``, floored, never above full, and nothing without a row.
The review is the exception: from ``REVIEW_PROGRESS_FROM`` only a yes
pays, only by its row, and a yes with no row pays 0; before it the row
is ignored (0.23.0).
"""
units = None if answer is None else max(0, int(answer))
if isinstance(earner, ReviewEarner):
if day >= REVIEW_PROGRESS_FROM:
return _review_term(earner, units, day, progress)
progress = None
if progress is not None and units is not None and units < 1:
return share_term(earner, units, day, progress)
count = units or 0
return Term(
earner=earner,
answer=units,
gaming_minutes=earner.gaming_for(count),
shutdown_minutes=earner.shutdown_for(count, day),
)

View File

@ -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": "427b689f8e0931ea09254bfb518a790ddefc00fa1ce1fb13b0281f7bde6cbb47",
"default|2026-11-25": "387960d1560514130f792581afd82e49e17e6253dc7ec7df326b664b6e910c4c",
"default|2026-11-26": "ba5fa2369f422283795973929fef3b1c129474f565078adec2ce46dd52a085ff",
"default|2026-11-27": "c5178b0a166b8034bb2afa9521f3b90c9714356c5cdb154e82789892da1549d7",
"default|2026-12-25": "3bb71f9165f0d7b9939f3ee765b33b44f4dfb49b349ad501973187f421de930e",
"default|2027-01-01": "a527db8c78abefa1713cbbd1854da5405d68eaf108094ebd00824a31bfd02507",
"default|2027-01-02": "b19381c6d2e1ddd94d8a9e9d4f30a85962e8a3141207cfacaa860fd8a5af617b",
"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": "1659bf90ace7713910f941ea6a872e740f8c8130bfd886143ddee5ff5f3bb21d",
"focus|2026-11-25": "2f0ae0b3892fd26d8c2376d0629aa2414a5d192169ff36beb4c09e879d2483de",
"focus|2026-11-26": "a706d2f25df525a3023677de18e9e68f68bf13be3fea5b6925bb96f6e287c715",
"focus|2026-11-27": "dc9bd93cef5acc080d61242c0b36ec8986f1e17d4db9a068cc8d24318536e00d",
"focus|2026-12-25": "0562f87b3326ad18de00d15bbe438c331ebf86755c2f189017e86baef730af4c",
"focus|2027-01-01": "8fb10422496f3b11deacfe4f5d126d67b02121048e2b278ac7cbce553cbd7038",
"focus|2027-01-02": "b72518c6a21ba3894fb6ea8da831fa6866a28b38f1026936688a714fa7776da9",
"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"
}

View File

@ -0,0 +1,126 @@
# 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)
# From this day a credited review with no progress row pays nothing, which is
# not 0.23.0's answer (REVIEW_PROGRESS_FROM, a literal: 0.23.0 has no such name).
# From it the review is only asked "no" and "could not check", which agree.
REVIEW_PROGRESS_FROM = date(2026, 11, 24)
REVIEW_OPTIONS: tuple[int | None, ...] = (None, 0)
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))]
options = [
REVIEW_OPTIONS if name == "review" and day >= REVIEW_PROGRESS_FROM else OPTIONS
for name in names
]
for values in itertools.product(*options):
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")

View File

@ -0,0 +1,91 @@
# 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}}
def bare(
done: object = "1",
target: object = "3",
source: str = "workout",
day: date = DAY,
) -> dict[str, object]:
"""A signed progress row with no ``created_at`` and no ``device``.
The workout ledger writes rows like this; the reader must accept them.
"""
return signed(
{
"kind": "progress",
"entry_id": f"progress:{day.isoformat()}:{done}:{target}",
"day": day.isoformat(),
"amount": 0,
"detail": {
"source": source,
"for_day": day.isoformat(),
"done": done,
"target": target,
},
}
)

View File

@ -0,0 +1,69 @@
# 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.
The one exception is the review from ``REVIEW_PROGRESS_FROM``: a credited
review with no row pays nothing, so the grid asks it only no or unknown there.
"""
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

View File

@ -0,0 +1,169 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Among a day's good progress rows the last in file order wins, as one pair."""
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING
import pytest
from earned_time import (
LEETCODE,
READING,
WORKOUT,
Progress,
entry_signature,
read_progress,
)
from earned_time.tests._maturity_rows import signed
from earned_time.tests._progress_rows import (
DAY,
bare,
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]) -> Progress | None:
ledger = write(tmp_path / "ledger.json", rows)
return read_progress(LEETCODE, ledger, key_file, DAY)
return reader
def test_a_later_row_with_a_lower_target_wins_whole(read: Reader) -> None:
rows = [progress(done="1", target="5"), progress(done="2", target="3")]
assert read(rows) == Progress(2, 3)
def test_a_later_row_with_a_lower_done_wins_whole(read: Reader) -> None:
rows = [progress(done="2", target="3"), progress(done="1", target="3")]
assert read(rows) == Progress(1, 3)
def test_a_later_row_with_a_higher_pair_wins_whole(read: Reader) -> None:
rows = [progress(done="1", target="3"), progress(done="2", target="4")]
assert read(rows) == Progress(2, 4)
def test_file_order_decides_not_the_numbers(read: Reader) -> None:
rows = [progress(done="1", target="3"), progress(done="2", target="4")]
assert read(rows[::-1]) == Progress(1, 3)
def test_the_last_row_of_three_wins(read: Reader) -> None:
rows = [
progress(done="3", target="3"),
progress(done="1", target="6"),
progress(done="2", target="6"),
]
assert read(rows) == Progress(2, 6)
def test_a_trailing_forged_row_is_skipped(read: Reader) -> None:
forged = tampered(progress(done="3", target="3"), done="2")
assert read([progress(done="1", target="3"), forged]) == Progress(1, 3)
def test_a_trailing_row_with_the_wrong_key_is_skipped(read: Reader) -> None:
row = progress(done="3", target="3")
row["hmac"] = entry_signature(row, b"someone else")
assert read([progress(done="1", target="3"), row]) == Progress(1, 3)
def test_a_trailing_unsigned_row_is_skipped(read: Reader) -> None:
row = progress(done="3", target="3")
del row["hmac"]
assert read([progress(done="1", target="3"), row]) == Progress(1, 3)
@pytest.mark.parametrize("junk", ["garbage", 7, None, [], ["x"], {}, {"kind": 1}])
def test_a_trailing_garbage_entry_is_skipped(read: Reader, junk: object) -> None:
assert read([progress(done="1", target="3"), junk]) == Progress(1, 3)
@pytest.mark.parametrize(
"bad", [("x", "3"), ("1", "x"), ("1", "0"), ("", "3"), ("1", "9" * 5000)]
)
def test_a_trailing_unparsable_row_is_skipped(
read: Reader, bad: tuple[str, str]
) -> None:
rows = [progress(done="1", target="3"), progress(done=bad[0], target=bad[1])]
assert read(rows) == Progress(1, 3)
def test_a_trailing_credit_row_is_skipped(read: Reader) -> None:
credit = signed({**progress(done="3", target="3"), "kind": "credit"})
assert read([progress(done="1", target="3"), credit]) == Progress(1, 3)
def test_trailing_rows_of_another_day_or_source_are_skipped(read: Reader) -> None:
rows = [
progress(done="1", target="3"),
progress(done="3", target="3", day=DAY - timedelta(days=1)),
progress(done="3", target="3", day=DAY + timedelta(days=1)),
progress(done="3", target="3", source="reading"),
progress(done="3", target="3", source="workout"),
]
assert read(rows) == Progress(1, 3)
def test_a_malformed_detail_row_is_skipped(read: Reader) -> None:
rows = [progress(done="1", target="3"), {**progress(), "detail": "x"}]
assert read(rows) == Progress(1, 3)
def test_only_bad_rows_read_as_none(read: Reader) -> None:
rows = [progress(done="x"), progress(source="reading"), "garbage"]
assert read(rows) is None
def test_rows_without_created_at_and_device_are_accepted(
tmp_path: Path, key_file: Path
) -> None:
first, last = bare(done="1", target="3"), bare(done="2", target="3")
assert "created_at" not in last
assert "device" not in last
ledger = write(tmp_path / "w.json", [first, last])
assert read_progress(WORKOUT, ledger, key_file, DAY) == Progress(2, 3)
def test_the_rule_does_not_read_created_at(read: Reader) -> None:
early = signed(
{**bare(done="2", source="leetcode"), "created_at": "2026-11-24T23:00:00+00:00"}
)
late = signed(
{**bare(done="1", source="leetcode"), "created_at": "2026-11-24T01:00:00+00:00"}
)
# File order, not timestamps: the later row in the file wins.
assert read([early, late]) == Progress(1, 3)
assert read([late, early]) == Progress(2, 3)
def test_each_source_reads_its_own_last_row(tmp_path: Path, key_file: Path) -> None:
rows = [
bare(done="1", target="3", source="workout"),
progress(done="2", target="4", source="reading"),
bare(done="3", target="3", source="workout"),
progress(done="1", target="9", source="reading"),
]
ledger = write(tmp_path / "mixed.json", rows)
assert read_progress(WORKOUT, ledger, key_file, DAY) == Progress(3, 3)
assert read_progress(READING, ledger, key_file, DAY) == Progress(1, 9)
def test_the_last_good_row_is_still_capped_at_its_target(read: Reader) -> None:
rows = [progress(done="1", target="3"), progress(done="9", target="4")]
assert read(rows) == Progress(4, 4)

View File

@ -0,0 +1,218 @@
# 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_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,)) == {}

View File

@ -0,0 +1,226 @@
# 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:
half = {"review": Progress(1, 2)}
paid = resolve({**NOTHING, "review": True}, DAY, progress=half)
assert paid.term("review").shutdown_minutes == 10
# The review's own rule (test_review_progress.py): a no pays nothing.
unpaid = resolve({**NOTHING, "review": False}, DAY, progress=half)
assert unpaid.term("review").shutdown_minutes == 0
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"

View File

@ -0,0 +1,175 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The review's partial pay: from REVIEW_PROGRESS_FROM no row means no pay."""
from __future__ import annotations
from datetime import date, timedelta
import logging
from typing import TYPE_CHECKING
import pytest
from earned_time import (
REVIEW,
REVIEW_FROM,
REVIEW_PROGRESS_FROM,
REVIEW_SHUTDOWN_MINUTES,
Progress,
progress_map,
resolve,
)
from earned_time.tests._progress_rows import (
home_ledger,
progress,
tampered,
write,
)
if TYPE_CHECKING:
from pathlib import Path
NOTHING: dict[str, int | bool | None] = {
"workout": 0,
"leetcode": False,
"reading": False,
"tutor": 0,
}
ON = date(2026, 11, 24)
DAYS = [ON, ON + timedelta(days=1), date(2027, 1, 1)]
Share = dict[str, Progress]
def _review(
answer: int | None,
day: date,
*,
sick: bool = False,
progress: Share | None = None,
) -> int:
answers = {**NOTHING, "review": answer}
return resolve(answers, day, sick=sick, progress=progress).shutdown_minutes
def _paid(day: date, share: Share | None = None, *, sick: bool = False) -> int:
"""What the credited review adds to the day's shutdown over no review."""
got = _review(1, day, sick=sick, progress=share)
return got - _review(0, day, sick=sick, progress=share)
def test_the_switch_is_the_day_after_the_release() -> None:
assert date(2026, 11, 24) == REVIEW_PROGRESS_FROM
assert REVIEW_FROM + timedelta(days=1) == REVIEW_PROGRESS_FROM
def test_before_the_switch_the_review_pays_as_in_0_23_0() -> None:
day = REVIEW_PROGRESS_FROM - timedelta(days=1)
assert _paid(day) == REVIEW_SHUTDOWN_MINUTES
# A row changes nothing yet: a yes pays full, a no pays nothing.
half: Share = {"review": Progress(1, 2)}
assert _paid(day, half) == REVIEW_SHUTDOWN_MINUTES
assert _review(0, day, progress=half) == _review(0, day)
@pytest.mark.parametrize("day", DAYS)
def test_a_credited_review_with_no_row_pays_nothing(day: date) -> None:
assert _paid(day) == 0
assert _paid(day, {}) == 0
assert _paid(day, {"leetcode": Progress(1, 2)}) == 0
term = resolve({**NOTHING, "review": True}, day).term("review")
assert (term.shutdown_minutes, term.gaming_minutes, term.progress) == (0, 0, None)
assert term.answer == 1
@pytest.mark.parametrize("day", DAYS)
def test_a_row_pays_equal_slices_of_the_bonus(day: date) -> None:
assert _paid(day, {"review": Progress(1, 2)}) == 10
assert _paid(day, {"review": Progress(2, 2)}) == 20
assert _paid(day, {"review": Progress(0, 2)}) == 0
assert _paid(day, {"review": Progress(1, 3)}) == 20 // 3
assert _paid(day, {"review": Progress(2, 3)}) == 40 // 3
def test_a_row_never_pays_more_than_the_full_bonus() -> None:
assert _paid(ON, {"review": Progress(9, 2)}) == 20
assert _paid(ON, {"review": Progress(5, 5)}) == 20
def test_the_term_shows_the_row_it_was_paid_from() -> None:
row = Progress(1, 2)
term = resolve({**NOTHING, "review": 1}, ON, progress={"review": row}).term(
"review"
)
assert term.progress == row
assert term.gaming_minutes == 0
@pytest.mark.parametrize("answer", [0, None])
def test_a_row_without_a_credited_review_pays_nothing(
answer: int | None,
) -> None:
full: Share = {"review": Progress(2, 2)}
assert _review(answer, ON, progress=full) == _review(0, ON)
term = resolve({**NOTHING, "review": answer}, ON, progress=full).term("review")
assert term.shutdown_minutes == 0
assert term.progress is None
def test_a_sick_day_follows_the_same_rule() -> None:
assert _paid(ON, sick=True) == 0
assert _paid(ON, {"review": Progress(1, 2)}, sick=True) == 10
assert _paid(ON, {"review": Progress(2, 2)}, sick=True) == 20
def test_other_earners_keep_the_yes_no_rule_without_a_row() -> None:
plain = resolve({**NOTHING, "leetcode": True}, ON)
assert plain.term("leetcode").shutdown_minutes == 60
shown = resolve(NOTHING, ON, progress={"leetcode": Progress(1, 3)})
assert shown.term("leetcode").shutdown_minutes == 20
assert resolve(NOTHING, ON).term("leetcode").shutdown_minutes == 0
def test_a_missing_review_answer_still_earns_nothing() -> None:
answers = dict(NOTHING)
shown = resolve(answers, ON, progress={"review": Progress(2, 2)})
assert shown.term("review").shutdown_minutes == 0
def test_a_credited_review_without_a_row_is_logged(
caplog: pytest.LogCaptureFixture,
) -> None:
with caplog.at_level(logging.WARNING, logger="earned_time._share"):
resolve({**NOTHING, "review": True}, ON)
assert "no progress row" in caplog.text
assert REVIEW.label in caplog.text
def test_no_warning_with_a_row_or_before_the_switch(
caplog: pytest.LogCaptureFixture,
) -> None:
with caplog.at_level(logging.WARNING, logger="earned_time._share"):
resolve({**NOTHING, "review": True}, ON, progress={"review": Progress(1, 2)})
resolve({**NOTHING, "review": True}, REVIEW_FROM)
assert "no progress row" not in caplog.text
def test_a_row_that_fails_verification_counts_as_no_row(
tmp_path: Path, key_file: Path
) -> None:
good = progress(source="review", done="2", target="2", day=ON)
forged = tampered(good, done="2")
forged["hmac"] = "0" * 64
for rows, expected in (([good], 20), ([forged], 0), ([], 0)):
write(home_ledger(tmp_path, REVIEW), list(rows))
share = progress_map(ON, tmp_path, key_file)
assert _paid(ON, share) == expected
def test_the_last_good_row_prices_the_day(tmp_path: Path, key_file: Path) -> None:
rows = [
progress(source="review", done="1", target="2", day=ON),
progress(source="review", done="2", target="2", day=ON),
]
write(home_ledger(tmp_path, REVIEW), list(rows))
assert _paid(ON, progress_map(ON, tmp_path, key_file)) == 20
write(home_ledger(tmp_path, REVIEW), list(rows[:1]))
assert _paid(ON, progress_map(ON, tmp_path, key_file)) == 10

View File

@ -1,5 +1,8 @@
# Copyright (c) 2026 Krzysztof Rudnicki # Copyright (c) 2026 Krzysztof Rudnicki
"""The review top-up in the day (0.23.0): added last, capped, never a rung.""" """The review top-up in the day (0.23.0): added last, capped, never a rung.
On ``REVIEW_FROM``, the day before ``REVIEW_PROGRESS_FROM``: the flat pay, no row.
"""
from __future__ import annotations from __future__ import annotations
@ -18,11 +21,14 @@ from earned_time import (
shutdown_ceiling_for, shutdown_ceiling_for,
shutdown_minutes_for, shutdown_minutes_for,
) )
from earned_time.tests._review_rows import DAY, accepted, home_with, review from earned_time.tests._review_rows import DAY as ROWS_DAY
from earned_time.tests._review_rows import accepted, home_with, review
if TYPE_CHECKING: if TYPE_CHECKING:
from pathlib import Path from pathlib import Path
# The last day before REVIEW_PROGRESS_FROM: the flat 0.23.0 pay, no row needed.
DAY = REVIEW_FROM
NOTHING: dict[str, int | bool | None] = { NOTHING: dict[str, int | bool | None] = {
"workout": 0, "workout": 0,
"leetcode": False, "leetcode": False,
@ -118,6 +124,6 @@ def test_a_sick_day_before_unlimited_gaming_adds_it_too() -> None:
def test_maturity_never_penalises_it(tmp_path: Path, key_file: Path) -> None: def test_maturity_never_penalises_it(tmp_path: Path, key_file: Path) -> None:
ledger = home_with(tmp_path, [review()], [accepted()]) ledger = home_with(tmp_path, [review()], [accepted()])
verdict = maturity(REVIEW, ledger, key_file, DAY) verdict = maturity(REVIEW, ledger, key_file, ROWS_DAY)
assert verdict.penalty_start is None assert verdict.penalty_start is None
assert any("top-up" in reason for reason in verdict.reasons) assert any("top-up" in reason for reason in verdict.reasons)

View File

@ -0,0 +1,142 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""``term_for``: the one place an earner's pay for a day is derived.
``resolve`` builds its terms through it, so a consumer pricing one earner (the
screen-locker's live pass) can never disagree with ``resolve``.
"""
from __future__ import annotations
from datetime import date
from itertools import product
from typing import Any
import pytest
from earned_time import (
LEETCODE,
REVIEW,
REVIEW_PROGRESS_FROM,
WORKOUT,
Earner,
Progress,
Term,
earners_for,
resolve,
shutdown_minutes_for,
term_for,
)
DAYS = (
date(2026, 10, 5),
date(2026, 10, 16),
date(2026, 11, 22),
REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day - 1),
REVIEW_PROGRESS_FROM,
REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day + 1),
date(2027, 1, 1),
)
ANSWERS: tuple[int | bool | None, ...] = (True, False, None, 0, 1, 2)
FACTS: tuple[Progress | None, ...] = (
None,
Progress(0, 3),
Progress(1, 3),
Progress(2, 3),
Progress(3, 3),
Progress(1, 1),
Progress(7, 2),
)
LADDER = date(2026, 11, 22)
def test_the_signature_is_keyword_clear() -> None:
loose: Any = term_for
with pytest.raises(TypeError):
loose(LEETCODE, LADDER, 1)
@pytest.mark.parametrize("day", DAYS)
def test_term_for_equals_the_term_resolve_builds(day: date) -> None:
for item, answer, fact in product(earners_for(day), ANSWERS, FACTS):
others = {e.name: 0 for e in earners_for(day)}
asked = resolve(
{**others, item.name: answer},
day,
progress=None if fact is None else {item.name: fact},
).term(item.name)
got = term_for(item, day, answer=answer, progress=fact)
assert got == asked, (item.name, day, answer, fact)
assert isinstance(got, Term)
def test_a_generic_earner_pays_a_share_of_the_ladder_rung() -> None:
full = shutdown_minutes_for(LEETCODE, LADDER)
assert full == 60
row = Progress(1, 3)
assert term_for(LEETCODE, LADDER, answer=False, progress=row).shutdown_minutes == 20
assert term_for(LEETCODE, LADDER, answer=False, progress=row).gaming_minutes == 20
assert term_for(LEETCODE, LADDER, answer=False).shutdown_minutes == 0
def test_a_yes_pays_full_whatever_the_row_says() -> None:
low = term_for(LEETCODE, LADDER, answer=True, progress=Progress(1, 3))
assert low.shutdown_minutes == shutdown_minutes_for(LEETCODE, LADDER)
assert low.progress is None
def test_a_row_never_pays_above_full() -> None:
term = term_for(LEETCODE, LADDER, answer=False, progress=Progress(9, 3))
assert term.shutdown_minutes == shutdown_minutes_for(LEETCODE, LADDER)
def test_none_earns_nothing_even_with_a_full_row() -> None:
assert term_for(LEETCODE, LADDER, answer=None, progress=Progress(3, 3)) == Term(
LEETCODE, None, 0, 0
)
def test_the_review_follows_its_dated_rule() -> None:
row = Progress(1, 3)
before = REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day - 1)
assert term_for(REVIEW, before, answer=True, progress=row).shutdown_minutes == 20
assert term_for(REVIEW, before, answer=False, progress=row).shutdown_minutes == 0
on = REVIEW_PROGRESS_FROM
assert term_for(REVIEW, on, answer=True, progress=row).shutdown_minutes == 6
assert term_for(REVIEW, on, answer=True).shutdown_minutes == 0
assert term_for(REVIEW, on, answer=False, progress=row).shutdown_minutes == 0
def test_a_counted_earner_pays_per_unit() -> None:
day = LADDER
one = term_for(WORKOUT, day, answer=1).shutdown_minutes
assert term_for(WORKOUT, day, answer=True).shutdown_minutes == one
assert term_for(WORKOUT, day, answer=0).shutdown_minutes == 0
def _expected(
item: Earner, day: date, answer: int | None, fact: Progress | None
) -> int:
"""The shutdown minutes by the written rules, not by the library's code."""
if answer is None:
return 0
full = shutdown_minutes_for(item, day)
yes = answer is True or answer >= 1
if item is REVIEW and day >= REVIEW_PROGRESS_FROM:
if not yes or fact is None:
return 0
return full * min(fact.done, fact.target) // fact.target
if yes or (item is REVIEW) or fact is None:
return item.shutdown_for(max(0, int(answer)), day)
return full * min(fact.done, fact.target) // fact.target
@pytest.mark.parametrize("day", DAYS)
def test_the_minutes_follow_the_written_rules(day: date) -> None:
for item, answer, fact in product(earners_for(day), ANSWERS, FACTS):
got = term_for(item, day, answer=answer, progress=fact)
assert got.shutdown_minutes == _expected(item, day, answer, fact), (
item.name,
day,
answer,
fact,
)

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "earned-time" 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" description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [] dependencies = []
@ -35,7 +35,7 @@ unfixable = []
[tool.ruff.lint.pylint] [tool.ruff.lint.pylint]
# Same as [tool.pylint.design] max-args: resolve()'s keyword-only switches. # Same as [tool.pylint.design] max-args: resolve()'s keyword-only switches.
max-args = 6 max-args = 7
[tool.ruff.lint.pydocstyle] [tool.ruff.lint.pydocstyle]
convention = "google" convention = "google"
@ -111,10 +111,10 @@ disable = []
min-public-methods = 0 min-public-methods = 0
max-module-lines = 1000 max-module-lines = 1000
# Earner is a frozen registry record: its fields are the policy (cf. music_theory). # 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 # resolve()'s keyword-only switches (first_credits, sick, leisure) are the
# public API every consumer calls; bundling them would break each caller. # public API every consumer calls; bundling them would break each caller.
max-args = 6 max-args = 7
[tool.pylint.typecheck] [tool.pylint.typecheck]
generated-members = [ generated-members = [

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "freedays" name = "freedays"
version = "0.4.3" version = "0.4.4"
description = "Shared pre-declared free-day pool: one global list of days on which every gate app stands down" description = "Shared pre-declared free-day pool: one global list of days on which every gate app stands down"
requires-python = ">=3.14" requires-python = ">=3.14"
# Deliberately NOT gatelock. Its __init__ imports tkinter for the lock-window # Deliberately NOT gatelock. Its __init__ imports tkinter for the lock-window
@ -13,7 +13,7 @@ requires-python = ">=3.14"
# ~15 lines of HMAC that were wanted live in freedays/_hmac.py instead. # ~15 lines of HMAC that were wanted live in freedays/_hmac.py instead.
dependencies = [ dependencies = [
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync", "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit", "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
] ]
[project.scripts] [project.scripts]

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "gatelock" name = "gatelock"
version = "0.16.0" version = "0.16.1"
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps" description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [] # pure stdlib — tkinter is bundled with Python dependencies = [] # pure stdlib — tkinter is bundled with Python
@ -22,8 +22,8 @@ randr = ["python-xlib==0.33"]
# own CLI imports these (lazily). Pins match book-guard / leetcode-guard. # own CLI imports these (lazily). Pins match book-guard / leetcode-guard.
evening = [ evening = [
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time", "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.6#subdirectory=sickdays", "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
] ]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]

View File

@ -92,7 +92,11 @@ and +10 days), `cluster_progress()`, `next_new(...)`, `cluster_of(slug)`. A
(`DOCS-review.md`). `review-finish` takes only a slug the guard flags now and (`DOCS-review.md`). `review-finish` takes only a slug the guard flags now and
writes one signed row per slug to writes one signed row per slug to
`~/.local/share/leetcode-coach/review_ledger.json` (`review_ledger.record`), `~/.local/share/leetcode-coach/review_ledger.json` (`review_ledger.record`),
then the `review` event. It never touches the guard's ledger. then the `review` event. It never touches the guard's ledger. Each credit row
is written with a `progress` row ("done N of target M", source `review`) in
the same rename: the target is the number of flagged solves when the day's
first review is finished and stays frozen that day, `done` is the day's signed
review rows capped at it (`earned_time` 0.24.0 pays `bonus * done // target`).
**Toolbox + cards.** `toolbox.load_safe() -> Toolbox` (`.entries`, **Toolbox + cards.** `toolbox.load_safe() -> Toolbox` (`.entries`,
`.properties`), `toolbox_cards.cards_for(names) -> [Card]` (property list -> `.properties`), `toolbox_cards.cards_for(names) -> [Card]` (property list ->

View File

@ -59,6 +59,10 @@ taught. You find the one cause, log it, and that starts the cold re-test clock
- exit 0, `review logged: ...` and `ledger row: written`: the solve is no - exit 0, `review logged: ...` and `ledger row: written`: the solve is no
longer flagged, and the re-test falls due 3 and 10 days from today longer flagged, and the re-test falls due 3 and 10 days from today
(`leetcode --retest <slug>`). (`leetcode --retest <slug>`).
The same write adds a `progress` row (`progress:<day>:<done>:<target>`),
so a review pays its share of the day's bonus: the target is how many
solves were flagged when that day's first review finished and does not
change after it.
- `refused: ...` (exit 1): the slug is not flagged or an argument is - `refused: ...` (exit 1): the slug is not flagged or an argument is
wrong. Nothing was written. wrong. Nothing was written.
- `could not check: ...` (exit 2): nothing was written. Tell kuhy; do not - `could not check: ...` (exit 2): nothing was written. Tell kuhy; do not

View File

@ -36,6 +36,8 @@ python3 ~/.claude/skills/leetcode/fetch_problem.py "<first token>"
never quote it to kuhy unasked. never quote it to kuhy unasked.
Default starter language is JavaScript (`--lang python3` etc. if kuhy asks). Default starter language is JavaScript (`--lang python3` etc. if kuhy asks).
Then `python3 ~/.claude/skills/leetcode/history.py "<first token>"`: his own attempts,
failed and accepted, with code. For you only: never paste it back; ask where it broke.
## 2. Open ## 2. Open
@ -214,8 +216,8 @@ the method appeared.
## 5d. Cold re-test ## 5d. Cold re-test
`[cold re-test]` in the arguments (`leetcode --retest <slug>`, due +3 and `[cold re-test]` in the arguments (`leetcode --retest <slug>`, due +3 and
+10 days after a solve) means kuhy solved this before; you have no history, +10 days after a solve) means kuhy solved this before; `history.py` has his old
so do not ask about the old code. In the opening, say plainly: **do NOT code, for you only: it is solved cold. In the opening, say plainly: **do NOT
submit on LeetCode** -- a resubmission mints a gate credit. Then coach as submit on LeetCode** -- a resubmission mints a gate credit. Then coach as
usual, requirement list first, and judge by running the statement's examples usual, requirement list first, and judge by running the statement's examples
locally with `node` (section 4). The normal exit and post-mortem (5, 5b) locally with `node` (section 4). The normal exit and post-mortem (5, 5b)
@ -234,12 +236,10 @@ Runs on **sonnet, opus or fable** as written. Haiku went in circles (~30
micro-questions on an Easy, 2026-10-18); `model:` frontmatter is ignored for micro-questions on an Easy, 2026-10-18); `model:` frontmatter is ignored for
skills (2026-09-18), so only if you are haiku, the **first line** of your skills (2026-09-18), so only if you are haiku, the **first line** of your
opening message is opening message is
> Type `/model sonnet` now — learning sessions are gated to sonnet, opus or > Type `/model sonnet` now — learning sessions are gated to sonnet, opus or
> fable; your next message is refused until you do (or send `keep model`). > fable; your next message is refused until you do (or send `keep model`).
then continue with the opening. `hooks/leetcode_model_gate_userprompt.sh` then continue with the opening (`hooks/leetcode_model_gate_userprompt.sh`).
enforces it from the next prompt on.
The right client is `leetcode <url>` (print mode: the Stop hook can still The right client is `leetcode <url>` (print mode: the Stop hook can still
withhold a reply; the TUI has already streamed it). `leetcode --local` runs withhold a reply; the TUI has already streamed it). `leetcode --local` runs

View File

@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Print kuhy's own submissions on one problem, failed and accepted, with code.
Usage: history.py <url-or-slug>
kuhy, 2026-11-22: a Claude coaching a problem "should also have access to my
history of approaches", including the ones that succeeded. leetcode-guard's
one-minute harvester mirrors every submission (status, time, code) into
``~/.local/share/leetcode_guard/history/<slug>.json`` (``_history_store`` in
leetcode-guard documents the shape). This reads that mirror, read-only, and
prints a bounded summary: the newest :data:`SHOWN` submissions, each code
cut at :data:`CODE_CHARS`. The mirror is display-only context and never a
gate input; nothing here writes.
Exit codes: 0 printed (also "no mirror yet" and "unreadable"), 1 bad input.
Stdlib only and free of package imports, like ``fetch_problem.py``: SKILL.md
runs it by path. Its stdout IS its interface (T201 exemption in pyproject.toml).
"""
from __future__ import annotations
from datetime import UTC, datetime
import json
from pathlib import Path
import re
import sys
from typing import Final
HISTORY_DIR: Final = Path.home() / ".local" / "share" / "leetcode_guard" / "history"
SHOWN: Final = 12
"""Newest submissions printed; older ones are counted, not shown."""
CODE_CHARS: Final = 1500
"""Code longer than this is cut: one huge paste must not flood the context."""
_ARGC: Final = 2
"""argv is the script and one problem."""
def slug_from(arg: str) -> str:
"""A full problem URL or a bare slug; anything else raises ``ValueError``."""
found = re.search(r"leetcode\.(?:com|cn)/problems/([a-z0-9-]+)", arg)
if found:
return found.group(1)
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", arg):
return arg
msg = f"not a LeetCode slug: {arg!r}"
raise ValueError(msg)
def _when(raw: object) -> str:
"""Unix seconds as a UTC minute, ``?`` when off."""
if isinstance(raw, int) and not isinstance(raw, bool):
return datetime.fromtimestamp(raw, tz=UTC).strftime("%Y-%m-%d %H:%M UTC")
return "?"
def _row(item: dict[str, object]) -> str:
"""One submission: a header line and its code block."""
stats = ", ".join(str(item.get(key, "?")) for key in ("lang", "runtime", "memory"))
head = f"### {item.get('status', '?')} - {_when(item.get('timestamp'))} - {stats}"
code = item.get("code")
if not isinstance(code, str):
return f"{head}\n(code not mirrored yet)"
cut = "\n[cut]" if len(code) > CODE_CHARS else ""
return f"{head}\n```\n{code[:CODE_CHARS]}{cut}\n```"
def render(arg: str) -> str:
"""The summary for one problem, as markdown."""
slug = slug_from(arg)
path = HISTORY_DIR / f"{slug}.json"
if not path.exists():
return f"No mirrored submissions for {slug} yet."
try:
data = json.loads(path.read_text(encoding="utf-8"))
except OSError, ValueError:
data = None
rows = data.get("submissions") if isinstance(data, dict) else None
if not isinstance(rows, list):
return f"The submission mirror for {slug} is unreadable."
items = [item for item in rows if isinstance(item, dict)]
items.sort(key=lambda item: _stamp(item.get("timestamp")), reverse=True)
accepted = sum(item.get("status") == "Accepted" for item in items)
title = f"{len(items)} submissions ({accepted} accepted)"
parts = [f"# kuhy's submissions on {slug}: {title}"]
parts += [_row(item) for item in items[:SHOWN]]
if len(items) > SHOWN:
parts.append(f"({len(items) - SHOWN} older not shown)")
return "\n\n".join(parts)
def _stamp(raw: object) -> int:
"""A sort key: the timestamp, 0 when off."""
return raw if isinstance(raw, int) and not isinstance(raw, bool) else 0
def main() -> int:
"""Print the summary for the problem named on argv."""
if len(sys.argv) != _ARGC:
print("usage: history.py <url-or-slug>", file=sys.stderr)
return 1
try:
print(render(sys.argv[1]))
except ValueError as exc:
print(str(exc), file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -103,13 +103,13 @@ def review_finish(problem: str, cause: str, module: str | None) -> int:
return _unchecked(exc, "; nothing written") return _unchecked(exc, "; nothing written")
if slug not in reviewable: if slug not in reviewable:
return _refuse(f"{slug} is not flagged, {NOTHING}; nothing written") return _refuse(f"{slug} is not flagged, {NOTHING}; nothing written")
return _record(slug, cause, module) return _record(slug, cause, module, due=len(reviewable))
def _record(slug: str, cause: str, module: str | None) -> int: def _record(slug: str, cause: str, module: str | None, *, due: int) -> int:
"""Write the row, then the event, and say which of the two happened.""" """Write the rows, then the event, and say which of the two happened."""
try: try:
fresh = review_ledger.record(slug, cause) fresh = review_ledger.record(slug, cause, due=due)
except review_ledger.LedgerError as exc: except review_ledger.LedgerError as exc:
_LOG.warning("review of %s not recorded: %s", slug, exc) _LOG.warning("review of %s not recorded: %s", slug, exc)
print( print(

View File

@ -12,6 +12,11 @@ the coach does not depend on ``earned_time``;
``test_earned_time_verifies_the_row_and_signs_it_the_same`` holds the two ``test_earned_time_verifies_the_row_and_signs_it_the_same`` holds the two
together. together.
Every credit row is written with a ``progress`` row in the same rename
(`record`): the review's share of the day's bonus is ``done`` of ``target``
(``earned_time`` 0.24.0, DOCS-progress.md). The target is frozen at the day's
first review; the facts are read back from the signed rows, never stored apart.
Fail closed: without a readable key, or over a ledger file that does not Fail closed: without a readable key, or over a ledger file that does not
parse, `record` raises `LedgerError` and writes nothing. Each slug gets one row parse, `record` raises `LedgerError` and writes nothing. Each slug gets one row
ever. The write is a rename over the target, so a crash leaves the old file. ever. The write is a rename over the target, so a crash leaves the old file.
@ -39,6 +44,8 @@ VERSION: Final = 1
"""The guard ledger's ``_ledger_io._VERSION``.""" """The guard ledger's ``_ledger_io._VERSION``."""
SOURCE: Final = "leetcode-coach-review" SOURCE: Final = "leetcode-coach-review"
ID_PREFIX: Final = "review:" ID_PREFIX: Final = "review:"
PROGRESS_SOURCE: Final = "review"
"""``earned_time``'s ``Earner.progress_source`` for the review top-up."""
class LedgerError(RuntimeError): class LedgerError(RuntimeError):
@ -99,29 +106,72 @@ def _write(entries: list[Any]) -> None:
raise LedgerError(msg) from exc raise LedgerError(msg) from exc
def record(slug: str, cause: str, *, now: datetime | None = None) -> bool: def _signed(row: dict[str, Any], key: bytes) -> bool:
"""Sign and append the row for one finished review. """True when `row` carries the signature `entry_signature` gives it."""
claim = row.get("hmac")
return isinstance(claim, str) and hmac.compare_digest(
claim, entry_signature(row, key)
)
Args:
slug: The reviewed problem.
cause: The one named cause.
now: The finish time, timezone-aware (default: now, local time).
Returns: def _is_credit(row: dict[str, Any], day: str) -> bool:
True when the row was written, False when the slug already had one. detail = row.get("detail")
return (
row.get("kind") == "credit"
and row.get("day") == day
and isinstance(detail, dict)
and detail.get("source") == SOURCE
)
Raises:
LedgerError: no key, an unreadable ledger or a failed write; nothing def _fact(row: dict[str, Any], day: str) -> tuple[int, int] | None:
on disk changed. """``(done, target)`` of a progress row about `day` for the review source."""
""" detail = row.get("detail")
key = _key() if row.get("kind") != "progress" or not isinstance(detail, dict):
entries = _entries() return None
entry_id = ID_PREFIX + slug done, target = detail.get("done"), detail.get("target")
if any(isinstance(e, dict) and e.get("entry_id") == entry_id for e in entries): if (
return False detail.get("source") != PROGRESS_SOURCE
moment = now or datetime.now(tz=UTC).astimezone() or detail.get("for_day") != day
row: dict[str, object] = { or not all(
"entry_id": entry_id, isinstance(v, str) and v.isascii() and v.isdigit() for v in (done, target)
)
):
return None
return int(str(done)), int(str(target))
def _progress_row(
rows: list[Any], key: bytes, day: str, due: int, moment: datetime
) -> dict[str, object] | None:
"""The row that makes the day's facts true, or None when they already are."""
signed = [r for r in rows if isinstance(r, dict) and _signed(r, key)]
facts = [f for r in signed if (f := _fact(r, day)) is not None]
paid = sum(1 for r in signed if _is_credit(r, day))
target = facts[0][1] if facts else max(due, paid, 1)
state = (min(paid, target), target)
if facts and facts[-1] == state:
return None
done = state[0]
return {
"entry_id": f"progress:{day}:{done}:{target}",
"kind": "progress",
"day": day,
"created_at": moment.isoformat(),
"amount": 0,
"device": "pc",
"detail": {
"source": PROGRESS_SOURCE,
"for_day": day,
"done": str(done),
"target": str(target),
},
}
def _credit_row(slug: str, cause: str, moment: datetime) -> dict[str, object]:
return {
"entry_id": ID_PREFIX + slug,
"kind": "credit", "kind": "credit",
"day": moment.date().isoformat(), "day": moment.date().isoformat(),
"created_at": moment.isoformat(), "created_at": moment.isoformat(),
@ -134,6 +184,48 @@ def record(slug: str, cause: str, *, now: datetime | None = None) -> bool:
"finished_at": str(int(moment.timestamp())), "finished_at": str(int(moment.timestamp())),
}, },
} }
row["hmac"] = entry_signature(row, key)
_write([*entries, row])
return True def record(slug: str, cause: str, *, due: int, now: datetime | None = None) -> bool:
"""Sign and append the rows for one finished review: credit plus progress.
The progress row says "``done`` of ``target`` reviews for the day": ``done``
is the day's signed review credits, capped at ``target``, which is `due`
at the day's first progress row and never changes after it. Nothing is
appended for a state the last progress row already says, and a slug that
has its credit still gets the progress row it lacks (rows written before
this writer existed), with ``max(due, credits)`` as the target.
Args:
slug: The reviewed problem.
cause: The one named cause.
due: How many reviews are due right now, this one included.
now: The finish time, timezone-aware (default: now, local time).
Returns:
True when the credit row was written, False when the slug already had
one.
Raises:
LedgerError: no key, an unreadable ledger or a failed write; nothing
on disk changed, so neither row exists without the other.
"""
key = _key()
entries = _entries()
moment = now or datetime.now(tz=UTC).astimezone()
entry_id = ID_PREFIX + slug
fresh = not any(
isinstance(e, dict) and e.get("entry_id") == entry_id for e in entries
)
new: list[dict[str, object]] = []
if fresh:
credit = _credit_row(slug, cause, moment)
credit["hmac"] = entry_signature(credit, key)
new.append(credit)
day = moment.date().isoformat()
if (tally := _progress_row([*entries, *new], key, day, due, moment)) is not None:
tally["hmac"] = entry_signature(tally, key)
new.append(tally)
if new:
_write([*entries, *new])
return fresh

View File

@ -0,0 +1,194 @@
"""Tests for ``history.py``: kuhy's own attempts on one problem, for the coach.
The guard's harvester mirrors every submission with its code into
``~/.local/share/leetcode_guard/history/<slug>.json`` (phase 2, 2026-11-22).
The coach reads it as context, read-only, bounded.
"""
from __future__ import annotations
import json
import runpy
import sys
from typing import TYPE_CHECKING
import pytest
from leetcode_coach import history
if TYPE_CHECKING:
from pathlib import Path
MIRROR = {
"slug": "two-sum",
"fetched_at": 1795287060,
"complete": True,
"next_offset": 0,
"submissions": [
{
"id": "3",
"status": "Accepted",
"lang": "python3",
"timestamp": 1795287000,
"runtime": "40 ms",
"memory": "17 MB",
"code": "class Solution:\n def twoSum(self): return seen",
},
{
"id": "2",
"status": "Wrong Answer",
"lang": "python3",
"timestamp": 1795286000,
"runtime": "N/A",
"memory": "N/A",
"code": "x" * 5000,
},
{
"id": "1",
"status": "Compile Error",
"lang": "python3",
"timestamp": 1795285000,
"runtime": "N/A",
"memory": "N/A",
},
],
}
@pytest.fixture(name="mirror_dir")
def _mirror_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""A scratch history dir; the real one is never read."""
folder = tmp_path / "history"
folder.mkdir()
monkeypatch.setattr(history, "HISTORY_DIR", folder)
return folder
def write(folder: Path, data: object, slug: str = "two-sum") -> None:
"""Put one mirror file down."""
(folder / f"{slug}.json").write_text(json.dumps(data), encoding="utf-8")
def test_every_attempt_is_listed_newest_first_with_code(mirror_dir: Path):
"""Failed and accepted alike, each with its status, and code where fetched."""
write(mirror_dir, MIRROR)
text = history.render("two-sum")
assert (
text.index("Accepted")
< text.index("Wrong Answer")
< text.index("Compile Error")
)
assert "return seen" in text
assert "(code not mirrored yet)" in text
assert "3 submissions (1 accepted)" in text
def test_long_code_is_cut(mirror_dir: Path):
"""One huge paste must not flood the coach's context."""
write(mirror_dir, MIRROR)
text = history.render("two-sum")
assert "x" * history.CODE_CHARS in text
assert "x" * (history.CODE_CHARS + 1) not in text
assert "[cut]" in text
def test_only_the_newest_submissions_are_shown(mirror_dir: Path):
"""A problem with 60 attempts shows the newest few and says how many more."""
rows = [
{"id": str(n), "status": "Wrong Answer", "timestamp": 1795280000 + n}
for n in range(60)
]
write(mirror_dir, {**MIRROR, "submissions": rows})
text = history.render("two-sum")
assert text.count("Wrong Answer") == history.SHOWN
assert f"{60 - history.SHOWN} older not shown" in text
def test_no_mirror_says_so(mirror_dir: Path):
"""No file yet (never submitted, or the harvester has not reached it)."""
assert mirror_dir.exists()
assert history.render("two-sum") == "No mirrored submissions for two-sum yet."
@pytest.mark.parametrize("data", ["{", [], {"submissions": 3}])
def test_an_unreadable_mirror_is_reported_not_trusted(mirror_dir: Path, data: object):
"""Hand-edited or half-written: say it is unreadable, never crash."""
path = mirror_dir / "two-sum.json"
path.write_text(
data if isinstance(data, str) else json.dumps(data), encoding="utf-8"
)
assert (
history.render("two-sum") == "The submission mirror for two-sum is unreadable."
)
def test_a_bad_slug_is_refused(mirror_dir: Path):
"""``../x`` is not a slug and never becomes a path."""
assert mirror_dir.exists()
with pytest.raises(ValueError, match="not a LeetCode slug"):
history.render("../escape")
def test_cli_prints_and_takes_a_url(
mirror_dir: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
):
"""Run by path like fetch_problem.py: a URL or a slug, exit 0."""
write(mirror_dir, MIRROR)
monkeypatch.setattr(
sys,
"argv",
["history.py", "https://leetcode.com/problems/two-sum/description/"],
)
assert history.main() == 0
assert "Accepted" in capsys.readouterr().out
def test_cli_rejects_garbage(
mirror_dir: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
):
"""Exit 1 with one stderr line, like fetch_problem.py's bad input."""
assert mirror_dir.exists()
monkeypatch.setattr(sys, "argv", ["history.py", "../x"])
assert history.main() == 1
assert "not a LeetCode slug" in capsys.readouterr().err
def test_runs_as_a_script(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
"""``python3 history.py <slug>`` works without the package installed."""
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setattr(sys, "argv", ["history.py", "two-sum"])
with pytest.raises(SystemExit) as stop:
runpy.run_path(history.__file__, run_name="__main__")
assert stop.value.code == 0
def test_cli_wants_exactly_one_problem(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
"""No argument: the usage line on stderr, exit 1."""
monkeypatch.setattr(sys, "argv", ["history.py"])
assert history.main() == 1
assert "usage" in capsys.readouterr().err
def test_a_row_without_a_timestamp_still_prints(mirror_dir: Path):
"""A hand-edited row missing its time shows ``?``, never crashes."""
write(mirror_dir, {**MIRROR, "submissions": [{"id": "9", "status": "Accepted"}]})
assert "### Accepted - ? - ?, ?, ?" in history.render("two-sum")

View File

@ -73,11 +73,12 @@ def test_review_finish_logs_the_event_and_signs_a_row(
"cause": "missing-idea", "cause": "missing-idea",
"module": "hashing", "module": "hashing",
} }
(row,) = _rows() row, tally = _rows()
assert (row["entry_id"], row["detail"]["cause"]) == ( assert (row["entry_id"], row["detail"]["cause"]) == (
"review:two-sum", "review:two-sum",
"missing-idea", "missing-idea",
) )
assert tally["entry_id"] == f"progress:{row['day']}:1:1"
assert progress.history("two-sum").solved == progress.local_today() assert progress.history("two-sum").solved == progress.local_today()
assert capsys.readouterr().out.splitlines() == [ assert capsys.readouterr().out.splitlines() == [
"review logged: two-sum, cause missing-idea, module hashing", "review logged: two-sum, cause missing-idea, module hashing",
@ -86,6 +87,20 @@ def test_review_finish_logs_the_event_and_signs_a_row(
] ]
def test_the_target_is_how_many_solves_are_flagged_when_the_review_is_finished(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_guard(tmp_path, monkeypatch, "two-sum", "3sum", "lru-cache")
assert review_cli.main(["review-finish", "two-sum", "--cause", "debugging"]) == 0
fake_guard(tmp_path, monkeypatch, "3sum")
assert review_cli.main(["review-finish", "3sum", "--cause", "debugging"]) == 0
day = _rows()[0]["day"]
assert [r["entry_id"] for r in _rows() if r["kind"] == "progress"] == [
f"progress:{day}:1:3",
f"progress:{day}:2:3",
]
@pytest.mark.parametrize("cause", ["statement", "debugging", "interruption"]) @pytest.mark.parametrize("cause", ["statement", "debugging", "interruption"])
def test_a_cause_without_a_card_is_only_recorded( def test_a_cause_without_a_card_is_only_recorded(
tmp_path: Path, tmp_path: Path,
@ -196,10 +211,13 @@ def test_a_slug_with_a_row_gets_its_event_but_no_second_row(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None: ) -> None:
fake_guard(tmp_path, monkeypatch, "two-sum") fake_guard(tmp_path, monkeypatch, "two-sum")
review_ledger.record("two-sum", "statement") review_ledger.record("two-sum", "statement", due=1)
assert review_cli.main(["review-finish", "two-sum", "--cause", "debugging"]) == 0 assert review_cli.main(["review-finish", "two-sum", "--cause", "debugging"]) == 0
assert [e["event"] for e in _events("two-sum")] == ["review"] assert [e["event"] for e in _events("two-sum")] == ["review"]
assert [r["detail"]["cause"] for r in _rows()] == ["statement"] assert [r["detail"]["cause"] for r in _rows() if r["kind"] == "credit"] == [
"statement"
]
assert len(_rows()) == 2
assert "ledger row: already there, not written twice" in capsys.readouterr().out assert "ledger row: already there, not written twice" in capsys.readouterr().out
@ -217,4 +235,4 @@ def test_a_lost_event_is_reported_as_exactly_that(
out = capsys.readouterr().out out = capsys.readouterr().out
assert out.startswith("ledger row written, review event NOT logged (") assert out.startswith("ledger row written, review event NOT logged (")
assert "run the same command again" in out assert "run the same command again" in out
assert len(_rows()) == 1 assert len(_rows()) == 2

View File

@ -64,11 +64,12 @@ def test_the_seams_point_away_from_the_real_machine(tmp_path: Path) -> None:
def test_a_finished_review_writes_one_signed_row_in_the_guard_layout() -> None: def test_a_finished_review_writes_one_signed_row_in_the_guard_layout() -> None:
assert review_ledger.record("two-sum", "idea-to-code", now=NOW) is True assert review_ledger.record("two-sum", "idea-to-code", due=1, now=NOW) is True
data = _ledger() data = _ledger()
assert list(data) == ["version", "entries"] assert list(data) == ["version", "entries"]
assert data["version"] == 1 assert data["version"] == 1
(row,) = data["entries"] row, progress = data["entries"]
assert progress["entry_id"] == "progress:2026-11-21:1:1"
signature = row.pop("hmac") signature = row.pop("hmac")
assert row == { assert row == {
"entry_id": "review:two-sum", "entry_id": "review:two-sum",
@ -94,8 +95,8 @@ def test_earned_time_verifies_the_row_and_signs_it_the_same(
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
earned_time = _earned_time(monkeypatch) earned_time = _earned_time(monkeypatch)
review_ledger.record("two-sum", "missing-idea", now=NOW) review_ledger.record("two-sum", "missing-idea", due=1, now=NOW)
(row,) = _ledger()["entries"] row, _progress = _ledger()["entries"]
assert earned_time.verified(row, REVIEW_KEY) is True assert earned_time.verified(row, REVIEW_KEY) is True
assert row["hmac"] == earned_time.entry_signature(row, REVIEW_KEY) assert row["hmac"] == earned_time.entry_signature(row, REVIEW_KEY)
odd = {**GUARD_ROW, "detail": {"title_slug": "zażółć", "n": 1.5, "x": None}} odd = {**GUARD_ROW, "detail": {"title_slug": "zażółć", "n": 1.5, "x": None}}
@ -108,8 +109,8 @@ def test_earned_time_verifies_the_row_and_signs_it_the_same(
def test_the_default_clock_is_local_time_with_an_offset() -> None: def test_the_default_clock_is_local_time_with_an_offset() -> None:
review_ledger.record("two-sum", "debugging") review_ledger.record("two-sum", "debugging", due=1)
(row,) = _ledger()["entries"] row, _progress = _ledger()["entries"]
created = dt.datetime.fromisoformat(row["created_at"]) created = dt.datetime.fromisoformat(row["created_at"])
assert created.utcoffset() is not None assert created.utcoffset() is not None
assert row["day"] == created.date().isoformat() assert row["day"] == created.date().isoformat()
@ -117,12 +118,12 @@ def test_the_default_clock_is_local_time_with_an_offset() -> None:
def test_a_slug_is_never_written_twice() -> None: def test_a_slug_is_never_written_twice() -> None:
assert review_ledger.record("two-sum", "debugging", now=NOW) is True assert review_ledger.record("two-sum", "debugging", due=1, now=NOW) is True
before = review_ledger.LEDGER_PATH.read_bytes() before = review_ledger.LEDGER_PATH.read_bytes()
assert review_ledger.record("two-sum", "statement", now=NOW) is False assert review_ledger.record("two-sum", "statement", due=1, now=NOW) is False
assert review_ledger.LEDGER_PATH.read_bytes() == before assert review_ledger.LEDGER_PATH.read_bytes() == before
assert review_ledger.record("3sum", "statement", now=NOW) is True assert review_ledger.record("3sum", "statement", due=1, now=NOW) is True
assert [e["entry_id"] for e in _ledger()["entries"]] == [ assert [e["entry_id"] for e in _ledger()["entries"] if e["kind"] == "credit"] == [
"review:two-sum", "review:two-sum",
"review:3sum", "review:3sum",
] ]
@ -135,7 +136,7 @@ def test_without_a_key_nothing_is_written(content: bytes | None) -> None:
else: else:
review_ledger.KEY_FILE.write_bytes(content) review_ledger.KEY_FILE.write_bytes(content)
with pytest.raises(review_ledger.LedgerError, match="signing key"): with pytest.raises(review_ledger.LedgerError, match="signing key"):
review_ledger.record("two-sum", "debugging", now=NOW) review_ledger.record("two-sum", "debugging", due=1, now=NOW)
assert not review_ledger.LEDGER_PATH.exists() assert not review_ledger.LEDGER_PATH.exists()
@ -144,7 +145,7 @@ def test_an_unreadable_ledger_is_never_overwritten(text: str) -> None:
review_ledger.LEDGER_PATH.parent.mkdir(parents=True) review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_bytes(text.encode("latin-1")) review_ledger.LEDGER_PATH.write_bytes(text.encode("latin-1"))
with pytest.raises(review_ledger.LedgerError, match="not overwritten"): with pytest.raises(review_ledger.LedgerError, match="not overwritten"):
review_ledger.record("two-sum", "debugging", now=NOW) review_ledger.record("two-sum", "debugging", due=1, now=NOW)
assert review_ledger.LEDGER_PATH.read_bytes() == text.encode("latin-1") assert review_ledger.LEDGER_PATH.read_bytes() == text.encode("latin-1")
@ -155,4 +156,4 @@ def test_a_failed_write_is_a_ledger_error(
blocker.write_text("x", encoding="utf-8") blocker.write_text("x", encoding="utf-8")
monkeypatch.setattr(review_ledger, "LEDGER_PATH", blocker / "review_ledger.json") monkeypatch.setattr(review_ledger, "LEDGER_PATH", blocker / "review_ledger.json")
with pytest.raises(review_ledger.LedgerError, match="cannot write"): with pytest.raises(review_ledger.LedgerError, match="cannot write"):
review_ledger.record("two-sum", "debugging", now=NOW) review_ledger.record("two-sum", "debugging", due=1, now=NOW)

View File

@ -0,0 +1,208 @@
"""The progress row every review credit is written with (earned_time 0.24.0)."""
from __future__ import annotations
import datetime as dt
import importlib
import json
import logging
from pathlib import Path
import tempfile
from typing import TYPE_CHECKING, Any
import pytest
from leetcode_coach import review_ledger
from leetcode_coach.tests._review_support import REVIEW_KEY
if TYPE_CHECKING:
from types import ModuleType
TZ = dt.timezone(dt.timedelta(hours=1))
MONDAY = dt.datetime(2026, 11, 23, 9, 0, 0, tzinfo=TZ)
TUESDAY = dt.datetime(2026, 11, 24, 9, 0, 0, tzinfo=TZ)
REPO_ROOT = Path(__file__).resolve().parents[3]
def _rows() -> list[dict[str, Any]]:
data = json.loads(review_ledger.LEDGER_PATH.read_text(encoding="utf-8"))
rows: list[dict[str, Any]] = data["entries"]
return rows
def _ids() -> list[str]:
return [row["entry_id"] for row in _rows()]
def _progress_ids() -> list[str]:
return [i for i in _ids() if i.startswith("progress:")]
def _finish(slug: str, due: int, now: dt.datetime = MONDAY) -> bool:
return review_ledger.record(slug, "debugging", due=due, now=now)
def _signed(row: dict[str, object]) -> dict[str, object]:
return {**row, "hmac": review_ledger.entry_signature(row, REVIEW_KEY)}
def _foreign_progress(
source: str, target: str, day: str = "2026-11-23"
) -> dict[str, object]:
return {
"entry_id": f"progress:{day}:0:{target}",
"kind": "progress",
"day": day,
"created_at": f"{day}T08:00:00+01:00",
"amount": 0,
"device": "pc",
"detail": {"source": source, "for_day": day, "done": "0", "target": target},
}
def test_the_first_review_of_a_day_writes_its_credit_and_progress_one_of_due() -> None:
assert _finish("two-sum", due=3) is True
credit, progress = _rows()
assert credit["entry_id"] == "review:two-sum"
progress.pop("hmac")
assert progress == {
"entry_id": "progress:2026-11-23:1:3",
"kind": "progress",
"day": "2026-11-23",
"created_at": "2026-11-23T09:00:00+01:00",
"amount": 0,
"device": "pc",
"detail": {
"source": "review",
"for_day": "2026-11-23",
"done": "1",
"target": "3",
},
}
def test_the_second_review_reuses_the_frozen_target_whatever_is_due_now() -> None:
_finish("two-sum", due=3)
_finish("3sum", due=1)
assert _progress_ids() == ["progress:2026-11-23:1:3", "progress:2026-11-23:2:3"]
_finish("lru-cache", due=9)
assert _progress_ids()[-1] == "progress:2026-11-23:3:3"
def test_a_repeat_of_the_same_state_writes_nothing() -> None:
_finish("two-sum", due=3)
before = review_ledger.LEDGER_PATH.read_bytes()
assert _finish("two-sum", due=2) is False
assert review_ledger.LEDGER_PATH.read_bytes() == before
def test_done_is_capped_at_the_target_and_adds_no_row_past_it() -> None:
_finish("a", due=1)
_finish("b", due=1)
assert _progress_ids() == ["progress:2026-11-23:1:1"]
assert _ids().count("review:b") == 1
def test_a_new_day_freezes_its_own_target() -> None:
_finish("a", due=3)
_finish("b", due=3)
_finish("c", due=2, now=TUESDAY)
assert _progress_ids() == [
"progress:2026-11-23:1:3",
"progress:2026-11-23:2:3",
"progress:2026-11-24:1:2",
]
def test_a_credit_with_no_progress_gets_it_on_the_next_call() -> None:
"""Rows from before the progress writer: done counts them, target is due."""
credit = _signed(
{
"entry_id": "review:old",
"kind": "credit",
"day": "2026-11-23",
"created_at": "2026-11-23T08:00:00+01:00",
"amount": 1,
"device": "pc",
"detail": {
"title_slug": "old",
"cause": "statement",
"source": review_ledger.SOURCE,
"finished_at": "1",
},
}
)
review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_text(
json.dumps({"version": 1, "entries": [credit]}), encoding="utf-8"
)
assert _finish("old", due=2) is False
assert _progress_ids() == ["progress:2026-11-23:1:2"]
_finish("new", due=1)
assert _progress_ids()[-1] == "progress:2026-11-23:2:2"
@pytest.mark.parametrize(
("source", "signed"),
[("review", False), ("workout", True), ("leetcode", True)],
)
def test_only_a_signed_review_progress_row_freezes_the_target(
source: str, *, signed: bool
) -> None:
other = _foreign_progress(source, "99")
row = _signed(other) if signed else {**other, "hmac": "0" * 64}
review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_text(
json.dumps({"version": 1, "entries": [row]}), encoding="utf-8"
)
_finish("two-sum", due=3)
assert _progress_ids()[-1] == "progress:2026-11-23:1:3"
def test_every_row_verifies_with_earned_time_and_the_credit_comes_with_progress(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.syspath_prepend(str(REPO_ROOT / "earned_time"))
earned_time: ModuleType = importlib.import_module("earned_time")
_finish("a", due=2)
_finish("b", due=2)
rows = _rows()
assert [r["kind"] for r in rows] == ["credit", "progress", "credit", "progress"]
assert all(earned_time.verified(r, REVIEW_KEY) for r in rows)
assert all(r["hmac"] == earned_time.entry_signature(r, REVIEW_KEY) for r in rows)
assert all(isinstance(v, str) for r in rows[1::2] for v in r["detail"].values())
def test_a_failed_write_leaves_neither_row_and_is_logged_loudly(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
blocker = tmp_path / "a-file"
blocker.write_text("x", encoding="utf-8")
monkeypatch.setattr(review_ledger, "LEDGER_PATH", blocker / "review_ledger.json")
with caplog.at_level(logging.WARNING), pytest.raises(review_ledger.LedgerError):
_finish("two-sum", due=3)
assert any(r.levelno >= logging.WARNING for r in caplog.records)
assert not (blocker / "review_ledger.json").exists()
def test_the_failed_second_review_leaves_the_first_pair_untouched(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_finish("a", due=2)
before = review_ledger.LEDGER_PATH.read_bytes()
def boom(*_a: object, **_k: object) -> None:
raise OSError(28, "No space left on device")
monkeypatch.setattr(tempfile, "mkstemp", boom)
with pytest.raises(review_ledger.LedgerError):
_finish("b", due=2)
assert review_ledger.LEDGER_PATH.read_bytes() == before
@pytest.mark.parametrize("due", [-1, 0])
def test_a_first_review_with_nothing_due_still_gets_a_target_of_one(due: int) -> None:
_finish("two-sum", due=due)
assert _progress_ids() == ["progress:2026-11-23:1:1"]

View File

@ -71,6 +71,7 @@ unfixable = []
"leetcode_coach/local_session.py" = ["T201"] "leetcode_coach/local_session.py" = ["T201"]
"leetcode_coach/make_cards.py" = ["T201"] "leetcode_coach/make_cards.py" = ["T201"]
"leetcode_coach/fetch_problem.py" = ["S310", "T201"] "leetcode_coach/fetch_problem.py" = ["S310", "T201"]
"leetcode_coach/history.py" = ["T201"]
"leetcode_coach/eval_local.py" = ["T201"] "leetcode_coach/eval_local.py" = ["T201"]
"leetcode_coach/stop_gate.py" = ["T201"] "leetcode_coach/stop_gate.py" = ["T201"]
"leetcode_coach/cluster_cli.py" = ["T201"] "leetcode_coach/cluster_cli.py" = ["T201"]

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "sickdays" name = "sickdays"
version = "0.5.8" version = "0.5.9"
description = "Shared sick-day pool: per-date, uncapped, synced; every gate respects it" description = "Shared sick-day pool: per-date, uncapped, synced; every gate respects it"
requires-python = ">=3.14" requires-python = ">=3.14"
# Deliberately NOT gatelock (its __init__ imports tkinter); the HMAC lives in # Deliberately NOT gatelock (its __init__ imports tkinter); the HMAC lives in
@ -13,8 +13,8 @@ requires-python = ">=3.14"
# so the two packages can never form an import cycle. # so the two packages can never form an import cycle.
dependencies = [ dependencies = [
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync", "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit", "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
] ]
[project.scripts] [project.scripts]

View File

@ -5,7 +5,7 @@ description: >-
injected closures -- no keystore or platform plugin access lives in this injected closures -- no keystore or platform plugin access lives in this
package itself. package itself.
publish_to: 'none' publish_to: 'none'
version: 0.8.4 version: 0.8.6
environment: environment:
sdk: ^3.13.0 sdk: ^3.13.0
@ -14,12 +14,12 @@ dependencies:
crdt_sync: crdt_sync:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.1 ref: crdt_sync_dart-v0.14.2
path: crdt_sync_dart path: crdt_sync_dart
data_transfer_flutter: data_transfer_flutter:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.3 ref: data_transfer_flutter-v0.2.4
path: data_transfer_flutter path: data_transfer_flutter
flutter: flutter:
sdk: flutter sdk: flutter