gatelock 0.16.0: evening gate chain

Merge b84a27e (0.15.0 chain) over main's 0.15.1 reporter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYYxXeZ4Ws1a1YuM8X
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 22:38:07 +01:00
commit 781b82863c
14 changed files with 1064 additions and 7 deletions

View File

@ -5,10 +5,10 @@ on:
branches: [main]
# The workflow's own file counts as gatelock: editing only this file used
# to trigger nothing, so a fix to the job itself could never prove itself.
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
pull_request:
branches: [main]
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
jobs:
test:
@ -26,6 +26,14 @@ jobs:
cache: pip
cache-dependency-path: gatelock/requirements.txt
# The evening chain (gatelock.evening_chain) reads earned_time, freedays
# and sickdays; they are siblings in this repo, so CI installs the
# checkout, not a tag.
- name: Install the sibling packages
run: >-
pip install ../crdt-sync ../earned_time
&& pip install --no-deps ../freedays ../sickdays
- name: Install dependencies
run: pip install -r requirements.txt

View File

@ -143,6 +143,30 @@ Uncaught, thread and Tk callback errors and waits over 1 s go to
`~/.local/state/app-errors-spool/<app>.jsonl`. The `app-errors` ingest timer
turns them into board tickets. Nothing shows on screen.
## Evening gate chain
`python3 -m gatelock.evening_chain pending|run` (0.16.0) runs book, then tutor,
then LeetCode in front of night lockdown. Needs the `evening` extra
(earned-time, freedays, sickdays); only this CLI imports them.
- `pending` prints the unpaid rungs. Exit 0 some rung is unpaid; 1 nothing
to do (all paid, free day, sick day, or 23:00 and later); 2 could not
check (unreadable ledger or key, any exception; stderr says why) -- it
fails closed, so root enters lockdown. Reading and LeetCode use
`earned_time.done_today`; the tutor is quota-based
(`credit_units >= max_units`). The LeetCode rung is pending only while
payable: a day settled by any signed `charge:<day>` row (escape hatch,
outage) can never earn the bonus, so it is not listed. Cheap: three small reads, root runs it
every minute.
- `run` runs each unpaid rung's gate (`GATE_COMMANDS`, all `--production
--evening`) and re-checks before each. A gate's exit 10
(`EXIT_END_EVENING`) stops the chain with 0; 3 (`EXIT_NO_X`) exits 3; a
gate killed at 23:00 or nothing left exits 0; a failing gate (or one that
exits 0 with its rung still unpaid) is skipped, and two in a row exit 1.
- `RANK_EVENING_GATE` = 150 sits between the screen-locker and diet-guard.
- `systemd/evening-gates.service` is the user unit root starts;
`install_evening_gates.sh` copies it and reloads, and never enables it.
## Development
```bash

View File

@ -10,6 +10,7 @@ from __future__ import annotations
from gatelock._arbiter import (
RANK_DIET_GUARD,
RANK_EVENING_GATE,
RANK_SCREEN_LOCKER,
RANK_WAKE_ALARM,
Arbiter,
@ -79,6 +80,7 @@ __all__ = [
"QUEUE_HEARTBEAT_SECONDS",
"QUEUE_POLL_SECONDS",
"RANK_DIET_GUARD",
"RANK_EVENING_GATE",
"RANK_SCREEN_LOCKER",
"RANK_WAKE_ALARM",
"Arbiter",

View File

@ -2,9 +2,8 @@
"""Decide which of N locker apps may hold the screen.
On 2026-07-25 two lockers armed at the same boot. One won the X grab; the
other spun forever in a retry loop, logging that "a fullscreen game" held the
grab. No game was running -- the holder was the other locker. Nothing
coordinated them because nothing could: each app only knew about itself.
other spun forever, logging that "a fullscreen game" held it. No game was
running -- the holder was the other locker, and each app only knew itself.
This module is that coordination. Every app publishes a *claim* before it
builds any window, and the highest-ranked live claim wins. Ranks, highest
@ -12,6 +11,7 @@ first:
* ``RANK_WAKE_ALARM`` -- you have to wake up before you can do anything else
* ``RANK_SCREEN_LOCKER`` -- then you work out
* ``RANK_EVENING_GATE`` -- then the evening gate chain
* ``RANK_DIET_GUARD`` -- then you eat
Two properties do the real work.
@ -55,8 +55,8 @@ _logger = logging.getLogger(__name__)
RANK_WAKE_ALARM: Final = 300
RANK_SCREEN_LOCKER: Final = 200
RANK_EVENING_GATE: Final = 150
RANK_DIET_GUARD: Final = 100
_HOLDER_FILENAME: Final = "holder.lock"

View File

@ -0,0 +1,155 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""What the evening chain reads: constants, sources and today's verdict.
Split from :mod:`gatelock.evening_chain` (the CLI and the run loop) to keep
each file readable in one piece. Import the public names from there.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import time
import json
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Final, Protocol
import earned_time
import freedays
import sickdays
from gatelock.log_integrity import DEFAULT_HMAC_KEY_FILE
if TYPE_CHECKING:
from collections.abc import Mapping
from datetime import date, datetime
class _Earner(Protocol):
"""What this module reads off an ``earned_time.Earner``."""
ledger: str
max_units: int | None
_logger: Final = logging.getLogger(__name__)
EXIT_OK: Final = 0
EXIT_NOTHING: Final = 1
EXIT_UNCHECKABLE: Final = 2
EXIT_NO_X: Final = 3
EXIT_END_EVENING: Final = 10
"""A gate's "end evening" control: stop the chain, lockdown at the next tick."""
CHAIN: Final = ("reading", "tutor", "leetcode")
CUTOFF: Final = time(23, 0)
"""The only hard time: from here no gate runs and nothing is pending."""
MAX_FAILURES_IN_A_ROW: Final = 2
_PYTHON: Final = "/usr/bin/python3"
GATE_COMMANDS: Final[Mapping[str, tuple[str, ...]]] = {
"reading": (_PYTHON, "-m", "book_guard", "lock", "--production", "--evening"),
"tutor": (_PYTHON, "-m", "tutor.gate", "--production", "--evening"),
"leetcode": (_PYTHON, "-m", "leetcode_guard", "--production", "--evening"),
}
TUTOR: Final = "tutor"
LEETCODE: Final = "leetcode"
# What a ledger read may raise; anything else is a bug and surfaces in main().
_CHECK_ERRORS: Final = (OSError, ValueError, TypeError, LookupError, RuntimeError)
@dataclass(frozen=True)
class Sources:
"""Every file the chain reads. No defaults: callers say where."""
home: Path
key_file: Path
free_log: Path | None # None: freedays' own pool
sick_log: Path | None # None: sickdays' own pool
@dataclass(frozen=True)
class Verdict:
"""Today's chain: the rungs still to run, in order, and why none."""
todo: tuple[str, ...] = ()
unchecked: tuple[str, ...] = ()
stood_down: str = "" # "free", "sick", "late" or ""
def production_sources() -> Sources:
"""The real machine's files: ``$HOME`` ledgers, the shared HMAC key."""
return Sources(Path.home(), Path(DEFAULT_HMAC_KEY_FILE), None, None)
def _charged_today(ledger: Path, sources: Sources, day: date) -> bool:
"""Whether a verified ``charge`` row names ``day``, whatever its source.
A day settled by the escape hatch or a LeetCode outage carries a
non-paying charge, and the gate then writes no ``source=leetcode`` row, so
the rung can never be paid. earned_time has no public helper for "any
charge" (``done_today`` only sees the paying one), so this reads the rows
itself and trusts only signed ones. Raises OSError/ValueError when the
ledger or key cannot be read.
"""
key = sources.key_file.read_bytes().strip()
rows = json.loads(ledger.read_text(encoding="utf-8"))["entries"]
return any(
isinstance(row, dict)
and row.get("kind") == "charge"
and row.get("day") == day.isoformat()
and earned_time.verified(row, key)
for row in rows
)
def _paid(rung: str, earner: _Earner, sources: Sources, now: datetime) -> bool | None:
"""Whether ``rung`` has nothing to run; None when it could not be checked.
The LeetCode rung also counts as settled on a day an unpaying charge
closed (see :func:`_charged_today`): it is not payable, so not pending.
"""
ledger = sources.home / earner.ledger
try:
if rung == TUTOR:
units = earned_time.credit_units(
earner, ledger, sources.key_file, now.date()
)
cap = earner.max_units
return None if units is None or cap is None else units >= cap
done = earned_time.done_today(
earner, ledger, sources.key_file, now=now, gate_off=False
)
if done is None:
return None
if done or rung != LEETCODE:
return bool(done)
return _charged_today(ledger, sources, now.date())
except _CHECK_ERRORS:
_logger.exception("Could not check the %s rung", rung)
return None
def evaluate(now: datetime, sources: Sources) -> Verdict:
"""Which rungs are unpaid at ``now``; free/sick/late days stand down."""
now = now.astimezone()
if now.time() >= CUTOFF:
return Verdict(stood_down="late")
day = now.date()
if freedays.is_free_day(day, log_path=sources.free_log):
return Verdict(stood_down="free")
if sickdays.is_sick_day(day, log_path=sources.sick_log):
return Verdict(stood_down="sick")
earners = {e.name: e for e in earned_time.earners_for(day)}
todo: list[str] = []
unchecked: list[str] = []
for rung in CHAIN:
if rung not in earners:
continue
paid = _paid(rung, earners[rung], sources, now)
if paid is None:
unchecked.append(rung)
if not paid:
todo.append(rung)
return Verdict(tuple(todo), tuple(unchecked))

View File

@ -0,0 +1,197 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The evening gate chain: book, then tutor, then LeetCode, before lockdown.
When the resolved shutdown time arrives and a rung of the chain is unpaid
today, root (digital-wellbeing's day-specific-shutdown-check) asks this module
instead of entering night lockdown:
* ``python3 -m gatelock.evening_chain pending`` -- prints the unpaid rungs.
Exit 0 some rung is unpaid; 1 nothing to do (all paid, a free or sick day,
or 23:00 or later); 2 could not check. Root calls it every minute, so it
reads three small files and nothing else.
* ``python3 -m gatelock.evening_chain run`` -- the ``evening-gates.service``
body: each unpaid rung's gate in order, until all are paid.
"Paid today" is read-only from the signed ledgers (``earned_time``): reading
and LeetCode by ``done_today``, the tutor by QUOTA (``credit_units`` reaching
``max_units``). A rung not in ``earned_time.earners_for(day)`` is not asked.
Failure modes, chosen out loud. ``pending`` fails CLOSED: an unreadable
ledger or key, a missing dependency or any exception is exit 2 on stderr, and
root then enters lockdown. ``run`` treats a rung it cannot check as unpaid
(its gate stays up and decides itself) but never spins: a gate that fails,
or exits 0 with the rung still unpaid, is skipped for the evening, and two
such failures in a row stop the chain with exit 1.
"""
from __future__ import annotations
import argparse
from datetime import UTC, datetime
import logging
import subprocess
import sys
from typing import TYPE_CHECKING, Final
from gatelock._evening_state import (
CHAIN,
CUTOFF,
EXIT_END_EVENING,
EXIT_NO_X,
EXIT_NOTHING,
EXIT_OK,
EXIT_UNCHECKABLE,
GATE_COMMANDS,
MAX_FAILURES_IN_A_ROW,
Sources,
Verdict,
evaluate,
production_sources,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
__all__ = [
"CHAIN",
"CUTOFF",
"EXIT_END_EVENING",
"EXIT_NO_X",
"GATE_COMMANDS",
"Sources",
"Verdict",
"evaluate",
"main",
"pending",
"run",
]
_logger: Final = logging.getLogger(__name__)
# Everything a broken install or ledger can plausibly raise. A tuple, not a
# bare ``except Exception``: pylint bans that and per-line suppressions are
# banned here. Anything outside it is a traceback and exit 1, which root also
# reads as "enter lockdown" (fail closed either way).
_ANY_FAILURE: Final = (
OSError,
ValueError,
TypeError,
LookupError,
RuntimeError,
ImportError,
AttributeError,
ArithmeticError,
AssertionError,
NameError,
)
type Clock = Callable[[], datetime]
type Runner = Callable[[Sequence[str], float], int | None]
"""Runs one gate command with a timeout in seconds; None means it timed out."""
def pending(sources: Sources, clock: Clock, emit: Callable[[str], None]) -> int:
"""``pending``'s answer: print the unpaid rungs, return its exit code."""
verdict = evaluate(clock(), sources)
if verdict.stood_down:
_logger.info("Evening chain stands down: %s", verdict.stood_down)
return EXIT_NOTHING
if verdict.unchecked:
_logger.error("Could not check: %s", " ".join(verdict.unchecked))
return EXIT_UNCHECKABLE
if not verdict.todo:
return EXIT_NOTHING
emit(" ".join(verdict.todo))
return EXIT_OK
def subprocess_runner(cmd: Sequence[str], timeout_s: float) -> int | None:
"""Run a gate; on timeout kill it and return None."""
try:
return subprocess.run(cmd, check=False, timeout=timeout_s).returncode
except subprocess.TimeoutExpired:
return None
except OSError:
_logger.exception("Cannot start %s", cmd[0])
return 127
def _seconds_to_cutoff(now: datetime) -> float:
cutoff = datetime.combine(now.date(), CUTOFF, now.tzinfo)
return max((cutoff - now).total_seconds(), 1.0)
def _stop_code(rung: str, code: int | None) -> int | None:
"""The run's own exit code when ``code`` ends the chain, else None."""
if code is None:
_logger.warning("%s gate still up at %s; stopping", rung, CUTOFF)
return EXIT_OK
return {EXIT_END_EVENING: EXIT_OK, EXIT_NO_X: EXIT_NO_X}.get(code)
def run(sources: Sources, clock: Clock, runner: Runner) -> int:
"""Run each unpaid rung's gate in order; see the module docstring."""
skipped: list[str] = []
ran_clean = "" # a rung whose gate exited 0 and must now read as paid
failures = 0
while True:
now = clock().astimezone()
verdict = evaluate(now, sources)
if ran_clean in verdict.todo:
_logger.error("%s gate exited 0 but the rung is unpaid", ran_clean)
skipped.append(ran_clean)
failures += 1
elif ran_clean:
failures = 0
ran_clean = ""
if failures >= MAX_FAILURES_IN_A_ROW:
_logger.error("Two gates failed in a row; stopping the chain")
return EXIT_NOTHING
if verdict.stood_down:
return EXIT_OK
todo = [r for r in verdict.todo if r not in skipped]
if not todo:
return EXIT_NOTHING if verdict.todo else EXIT_OK
rung = todo[0]
code = runner(GATE_COMMANDS[rung], _seconds_to_cutoff(now))
stop = _stop_code(rung, code)
if stop is not None:
return stop
if code == 0:
ran_clean = rung
continue
_logger.error("%s gate failed with exit %d; skipping it", rung, code)
skipped.append(rung)
failures += 1
def main(
argv: Sequence[str] | None = None,
*,
sources: Sources | None = None,
clock: Clock | None = None,
runner: Runner | None = None,
) -> int:
"""CLI entry. Collaborators are injectable; defaults are production."""
parser = argparse.ArgumentParser(prog="python3 -m gatelock.evening_chain")
parser.add_argument("command", choices=("pending", "run"))
command = parser.parse_args(argv).command
handler = logging.StreamHandler(sys.stderr)
root = logging.getLogger()
root.addHandler(handler)
root.setLevel(logging.INFO)
try:
where = sources if sources is not None else production_sources()
now = clock if clock is not None else (lambda: datetime.now(tz=UTC))
if command == "pending":
return pending(where, now, print)
return run(where, now, runner if runner is not None else subprocess_runner)
except _ANY_FAILURE:
_logger.exception("Evening chain %s failed", command)
return EXIT_UNCHECKABLE if command == "pending" else EXIT_NOTHING
finally:
root.removeHandler(handler)
if __name__ == "__main__":
sys.exit(main())

View File

@ -12,6 +12,8 @@ display).
from __future__ import annotations
import sys
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
@ -184,6 +186,14 @@ def make_arbiter(
return arbiter
@pytest.fixture(autouse=True)
def _no_live_focus_project(monkeypatch: pytest.MonkeyPatch) -> None:
"""earned_time reads the real focus projects file; no project is active."""
monkeypatch.setitem(
sys.modules, "focus_project", SimpleNamespace(active=lambda _day: None)
)
@pytest.fixture(autouse=True)
def _release_arbiters() -> Generator[None]:
"""Close every claim file a test opened."""

View File

@ -0,0 +1,64 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The chain's process edges: gate subprocesses, production paths, the unit."""
from __future__ import annotations
from pathlib import Path
import runpy
import subprocess
import sys
from types import SimpleNamespace
from unittest import mock
import pytest
from gatelock import evening_chain as chain
def test_subprocess_runner_returns_the_exit_code_with_the_timeout() -> None:
done = SimpleNamespace(returncode=7)
with mock.patch("gatelock.evening_chain.subprocess.run", return_value=done) as run:
assert chain.subprocess_runner(("gate", "--x"), 12.5) == 7
run.assert_called_once_with(("gate", "--x"), check=False, timeout=12.5)
def test_subprocess_runner_deadline_is_none() -> None:
expired = subprocess.TimeoutExpired(("gate",), 1)
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=expired):
assert chain.subprocess_runner(("gate",), 1) is None
def test_subprocess_runner_unstartable_gate_is_a_failure() -> None:
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=OSError):
assert chain.subprocess_runner(("gate",), 1) == 127
def test_production_sources_names_the_real_key_and_home() -> None:
sources = chain.production_sources()
assert str(sources.key_file) == "/etc/workout-locker/hmac.key"
assert sources.home == Path.home()
assert sources.free_log is None
assert sources.sick_log is None
def test_module_entry_point_rejects_an_unknown_command() -> None:
with (
pytest.warns(RuntimeWarning),
pytest.raises(SystemExit) as raised,
mock.patch.object(sys, "argv", ["evening_chain", "bogus"]),
):
runpy.run_module("gatelock.evening_chain", run_name="__main__")
assert raised.value.code == 2
UNIT = Path(__file__).parents[2] / "systemd" / "evening-gates.service"
def test_unit_matches_the_contract() -> None:
lines = UNIT.read_text(encoding="utf-8").splitlines()
assert "Type=simple" in lines
assert "Restart=no" in lines
assert "Environment=DISPLAY=:0" in lines
assert "Environment=XAUTHORITY=%h/.Xauthority" in lines
assert "ExecStart=/usr/bin/python3 -m gatelock.evening_chain run" in lines
assert "[Install]" not in lines

View File

@ -0,0 +1,222 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""``evening_chain pending``: which rungs are unpaid, and its exit code."""
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING
import pytest
from gatelock import RANK_DIET_GUARD, RANK_SCREEN_LOCKER
from gatelock import evening_chain as chain
from gatelock._arbiter import RANK_EVENING_GATE
from gatelock.tests.test_evening_rows import (
DAY,
EVENING,
LATE,
leetcode_row,
mark_free,
mark_sick,
pay_all,
seeded,
settled_row,
tutor_row,
write_ledger,
)
if TYPE_CHECKING:
from datetime import datetime
from pathlib import Path
def _run(sources: chain.Sources, now: datetime) -> tuple[int, str]:
out: list[str] = []
code = chain.pending(sources, lambda: now, out.append)
return code, " ".join(out)
def test_constants_follow_the_contract() -> None:
assert chain.EXIT_END_EVENING == 10
assert chain.EXIT_NO_X == 3
assert chain.CHAIN == ("reading", "tutor", "leetcode")
assert chain.CUTOFF.hour == 23
def test_evening_gate_ranks_between_diet_guard_and_screen_locker() -> None:
assert RANK_EVENING_GATE == 150
assert RANK_DIET_GUARD < RANK_EVENING_GATE < RANK_SCREEN_LOCKER
def test_nothing_paid_lists_every_rung_exit_0(tmp_path: Path) -> None:
sources = seeded(tmp_path)
write_ledger(sources, "reading", [])
write_ledger(sources, "tutor", [])
write_ledger(sources, "leetcode", [])
assert _run(sources, EVENING) == (0, "reading tutor leetcode")
def test_everything_paid_is_exit_1(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
assert _run(sources, EVENING) == (1, "")
def test_paid_rungs_are_skipped(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "tutor", [tutor_row(14)]) # 14 min < the 15 quota
assert _run(sources, EVENING) == (0, "tutor")
def test_tutor_is_quota_based_not_done_today(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "tutor", [tutor_row(15)])
assert _run(sources, EVENING)[0] == 1
write_ledger(sources, "tutor", [tutor_row(1)])
assert _run(sources, EVENING) == (0, "tutor")
def test_free_day_stands_down(tmp_path: Path) -> None:
sources = seeded(tmp_path)
mark_free(sources)
assert _run(sources, EVENING) == (1, "")
def test_sick_day_stands_down(tmp_path: Path) -> None:
sources = seeded(tmp_path)
mark_sick(sources)
assert _run(sources, EVENING) == (1, "")
def test_from_23_00_nothing_is_pending(tmp_path: Path) -> None:
sources = seeded(tmp_path)
assert _run(sources, LATE) == (1, "")
def test_unreadable_ledger_fails_closed(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
path = write_ledger(sources, "leetcode", [leetcode_row()])
path.write_text("{not json", encoding="utf-8")
assert _run(sources, EVENING) == (2, "")
def test_missing_key_fails_closed(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
sources.key_file.unlink()
assert _run(sources, EVENING)[0] == 2
def test_unreadable_rung_wins_over_unpaid_one(tmp_path: Path) -> None:
sources = seeded(tmp_path)
write_ledger(sources, "reading", [])
write_ledger(sources, "leetcode", [leetcode_row()]).write_text("x")
assert _run(sources, EVENING)[0] == 2
def test_exception_in_the_check_is_exit_2_and_logged(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
def boom(_day: object) -> None:
msg = "registry exploded"
raise RuntimeError(msg)
monkeypatch.setattr("earned_time.earners_for", boom)
code = chain.main(["pending"], sources=seeded(tmp_path), clock=lambda: EVENING)
assert code == 2
assert "registry exploded" in capsys.readouterr().err
def test_main_pending_prints_rungs_on_stdout(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "reading", [])
assert chain.main(["pending"], sources=sources, clock=lambda: EVENING) == 0
assert capsys.readouterr().out.strip() == "reading"
def test_a_reader_that_raises_is_unchecked_exit_2(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
def boom(*_args: object, **_kwargs: object) -> None:
msg = "no shared reader"
raise ValueError(msg)
monkeypatch.setattr("earned_time.done_today", boom)
assert _run(sources, EVENING) == (2, "")
def test_a_rung_the_registry_dropped_is_not_asked(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
import earned_time
sources = seeded(tmp_path)
write_ledger(sources, "leetcode", [])
kept = tuple(e for e in earned_time.earners_for(DAY) if e.name != "reading")
monkeypatch.setattr("earned_time.earners_for", lambda _day: kept)
assert _run(sources, EVENING) == (0, "tutor leetcode")
@pytest.mark.parametrize("source", ["escape", "outage"])
def test_a_settled_leetcode_day_is_unpayable_so_not_pending(
tmp_path: Path, source: str
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row(source)])
assert _run(sources, EVENING) == (1, "")
def test_a_settled_leetcode_day_leaves_the_other_rungs(tmp_path: Path) -> None:
sources = seeded(tmp_path)
write_ledger(sources, "reading", [])
write_ledger(sources, "tutor", [])
write_ledger(sources, "leetcode", [settled_row("escape")])
assert _run(sources, EVENING) == (0, "reading tutor")
def test_yesterdays_charge_does_not_settle_today(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
yesterday = DAY - timedelta(days=1)
write_ledger(sources, "leetcode", [settled_row("escape", yesterday)])
assert _run(sources, EVENING) == (0, "leetcode")
def test_an_unsigned_charge_does_not_settle_the_day(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
forged = {**settled_row("escape"), "hmac": "0" * 64}
write_ledger(sources, "leetcode", [forged])
assert _run(sources, EVENING) == (0, "leetcode")
def test_a_plain_unpaid_leetcode_day_is_still_pending(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [])
assert _run(sources, EVENING) == (0, "leetcode")
def test_a_settled_check_that_cannot_verify_is_exit_2(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row("escape")])
def boom(*_args: object) -> bool:
msg = "cannot verify"
raise ValueError(msg)
monkeypatch.setattr("earned_time.verified", boom)
assert _run(sources, EVENING) == (2, "")

View File

@ -0,0 +1,116 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Seeded state for the evening-chain tests: tmp ledgers signed with a tmp key.
Nothing here names a production path. ``seeded`` builds a ``Sources`` whose
home, key, free-day pool and sick-day pool all live under ``tmp_path``.
"""
from __future__ import annotations
from datetime import date, datetime, time
import json
from typing import TYPE_CHECKING
import earned_time
from earned_time import entry_signature
import freedays
import sickdays
from gatelock.evening_chain import Sources
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
KEY = b"evening-test-key"
DAY = date(2026, 11, 17) # a Tuesday: the tutor's workday quota is 15 minutes
EVENING = datetime(2026, 11, 17, 20, 30).astimezone()
LATE = datetime(2026, 11, 17, 23, 0).astimezone()
LEDGERS = {
"reading": earned_time.READING,
"tutor": earned_time.TUTOR,
"leetcode": earned_time.LEETCODE,
}
def stamp(hour: int = 19) -> float:
"""A unix time on DAY, local."""
return datetime.combine(DAY, time(hour)).astimezone().timestamp()
def _signed(row: Mapping[str, object]) -> dict[str, object]:
return {**row, "hmac": entry_signature(row, KEY)}
def reading_row() -> dict[str, object]:
"""A reading credit that earned the bonus today."""
detail = {"bonus": "1", "ended_at": stamp()}
return _signed({"kind": "credit", "entry_id": "r1", "detail": detail})
def leetcode_row() -> dict[str, object]:
"""The charge LeetCode writes once today's price is covered by solves."""
detail = {"source": "leetcode"}
row = {"kind": "charge", "entry_id": "l1", "day": DAY.isoformat(), "detail": detail}
return _signed(row)
def settled_row(source: str, day: date = DAY) -> dict[str, object]:
"""A non-paying charge: the day settled by escape hatch or outage."""
row = {
"kind": "charge",
"entry_id": f"charge:{day.isoformat()}",
"day": day.isoformat(),
"detail": {"source": source},
}
return _signed(row)
def tutor_row(minutes: int) -> dict[str, object]:
"""``minutes`` of tutoring ending today."""
detail = {"minutes": minutes, "ended_at": stamp()}
row = {"kind": "credit", "entry_id": f"s-m{minutes}", "detail": detail}
return _signed({**row, "day": DAY.isoformat()})
def write_ledger(sources: Sources, rung: str, rows: list[dict[str, object]]) -> Path:
"""Write ``rows`` as ``rung``'s ledger under the tmp home."""
path = sources.home / str(LEDGERS[rung].ledger)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({"entries": rows}), encoding="utf-8")
return path
def seeded(tmp_path: Path) -> Sources:
"""Empty sources: key present, no ledgers, no free or sick day."""
key = tmp_path / "hmac.key"
key.write_bytes(KEY)
return Sources(
home=tmp_path / "home",
key_file=key,
free_log=tmp_path / "free" / "free_days.json",
sick_log=tmp_path / "sick" / "sick_days.json",
)
def pay_all(sources: Sources) -> None:
"""Every rung paid today."""
write_ledger(sources, "reading", [reading_row()])
write_ledger(sources, "tutor", [tutor_row(15)])
write_ledger(sources, "leetcode", [leetcode_row()])
def mark_free(sources: Sources) -> None:
"""Make DAY a free day in the tmp pool."""
assert sources.free_log is not None
paths = freedays.Paths.under(sources.free_log.parent)
sources.free_log.parent.mkdir(parents=True, exist_ok=True)
freedays.mark(DAY, paths=paths, now=DAY)
def mark_sick(sources: Sources) -> None:
"""Make DAY a sick day in the tmp pool."""
assert sources.sick_log is not None
paths = sickdays.Paths.under(sources.sick_log.parent)
sources.sick_log.parent.mkdir(parents=True, exist_ok=True)
sickdays.add_sick_day(DAY, paths=paths, is_free=lambda _day: False, now=DAY)

View File

@ -0,0 +1,204 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""``evening_chain run``: order, skipping, exit codes, no spinning."""
from __future__ import annotations
from datetime import datetime, timedelta
import os
from pathlib import Path
import pwd
from typing import TYPE_CHECKING
from gatelock import evening_chain as chain
from gatelock.tests.test_evening_rows import (
EVENING,
leetcode_row,
pay_all,
reading_row,
seeded,
settled_row,
tutor_row,
write_ledger,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
import pytest
CMD_OF = {tuple(cmd): rung for rung, cmd in chain.GATE_COMMANDS.items()}
class FakeGates:
"""Runner stand-in: records the rung run, pays it, returns scripted codes."""
def __init__(
self,
sources: chain.Sources,
codes: dict[str, list[int | None]] | None = None,
) -> None:
self.sources = sources
self.codes = codes or {}
self.ran: list[str] = []
self.timeouts: list[float] = []
def __call__(self, cmd: Sequence[str], timeout_s: float) -> int | None:
rung = CMD_OF[tuple(cmd)]
self.ran.append(rung)
self.timeouts.append(timeout_s)
script = self.codes.get(rung)
code = script.pop(0) if script else 0
if code == 0:
pays = {"reading": reading_row, "leetcode": leetcode_row}
rows = [tutor_row(15)] if rung == "tutor" else [pays[rung]()]
write_ledger(self.sources, rung, rows)
return code
def _run(
sources: chain.Sources,
gates: Callable[[Sequence[str], float], int | None],
now: datetime = EVENING,
) -> int:
return chain.run(sources, lambda: now, gates)
def test_gate_commands_match_the_contract() -> None:
py = "/usr/bin/python3"
expected = {
"reading": (py, "-m", "book_guard", "lock", "--production", "--evening"),
"tutor": (py, "-m", "tutor.gate", "--production", "--evening"),
"leetcode": (py, "-m", "leetcode_guard", "--production", "--evening"),
}
assert expected == chain.GATE_COMMANDS
def test_runs_book_then_tutor_then_leetcode(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources)
assert _run(sources, gates) == 0
assert gates.ran == ["reading", "tutor", "leetcode"]
def test_paid_rungs_are_skipped(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "tutor", [])
gates = FakeGates(sources)
assert _run(sources, gates) == 0
assert gates.ran == ["tutor"]
def test_nothing_pending_runs_nothing(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
gates = FakeGates(sources)
assert _run(sources, gates) == 0
assert gates.ran == []
def test_exit_10_stops_the_chain_with_exit_0(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources, {"tutor": [10]})
assert _run(sources, gates) == 0
assert gates.ran == ["reading", "tutor"]
def test_exit_3_no_x_is_exit_3_at_once(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources, {"reading": [3]})
assert _run(sources, gates) == 3
assert gates.ran == ["reading"]
def test_one_failing_gate_is_skipped_and_the_rest_run(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources, {"reading": [7]})
assert _run(sources, gates) == 1 # reading stays unpaid
assert gates.ran == ["reading", "tutor", "leetcode"]
def test_two_failures_in_a_row_stop_with_exit_1(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources, {"reading": [7], "tutor": [9]})
assert _run(sources, gates) == 1
assert gates.ran == ["reading", "tutor"]
def test_a_gate_that_exits_0_unpaid_never_spins(tmp_path: Path) -> None:
sources = seeded(tmp_path)
calls: list[str] = []
def liar(cmd: Sequence[str], timeout_s: float) -> int | None:
calls.append(CMD_OF[tuple(cmd)])
return 0 if len(calls) < 50 else 99 # pays nothing
assert _run(sources, liar) == 1
assert calls == ["reading", "tutor"]
def test_stops_at_23_00_without_running_a_gate(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources)
assert _run(sources, gates, EVENING.replace(hour=23, minute=0)) == 0
assert gates.ran == []
def test_gate_is_bounded_by_the_23_00_cutoff(tmp_path: Path) -> None:
sources = seeded(tmp_path)
gates = FakeGates(sources, {"reading": [None]}) # timed out at the deadline
assert _run(sources, gates) == 0
assert gates.ran == ["reading"]
assert gates.timeouts == [timedelta(hours=2, minutes=30).total_seconds()]
def test_unchecked_rung_still_gets_its_gate(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", []).write_text("{bad")
gates = FakeGates(sources, {"leetcode": [7]})
assert _run(sources, gates) == 1
assert gates.ran == ["leetcode"]
def test_main_run_uses_the_injected_runner(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
gates = FakeGates(sources)
code = chain.main(["run"], sources=sources, clock=lambda: EVENING, runner=gates)
assert code == 0
assert gates.ran == []
def test_run_failing_to_evaluate_is_exit_1(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def boom(_day: object) -> None:
msg = "registry exploded"
raise RuntimeError(msg)
monkeypatch.setattr("earned_time.earners_for", boom)
gates = FakeGates(seeded(tmp_path))
code = chain.main(
["run"], sources=seeded(tmp_path), clock=lambda: EVENING, runner=gates
)
assert code == 1
assert gates.ran == []
def test_live_ledgers_are_untouched_by_a_run(tmp_path: Path) -> None:
home = Path(pwd.getpwuid(os.getuid()).pw_dir)
live = sorted((home / ".local" / "share").glob("*/ledger.json"))
before = [(p, p.stat().st_mtime_ns) for p in live]
sources = seeded(tmp_path)
assert _run(sources, FakeGates(sources)) == 0
assert [(p, p.stat().st_mtime_ns) for p in live] == before
def test_a_settled_leetcode_day_never_runs_its_gate(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row("outage")])
gates = FakeGates(sources)
assert _run(sources, gates) == 0
assert gates.ran == []

View File

@ -0,0 +1,28 @@
#!/bin/bash
# Install the evening-gates user unit. Idempotent; never enables or starts it:
# root's shutdown check starts it on demand (see evening_chain.py).
set -euo pipefail
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_DIR
readonly UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
readonly SYSTEM_PYTHON="/usr/bin/python3"
fail() {
echo "install_evening_gates: $*" >&2
exit 1
}
main() {
[[ $EUID -ne 0 ]] || fail "run as kuhy, not root (it is a user unit)"
"$SYSTEM_PYTHON" -c "import gatelock.evening_chain, earned_time, freedays, sickdays" \
|| fail "the system python cannot import gatelock.evening_chain and its readers"
mkdir -p "$UNIT_DIR"
install -m 644 "$REPO_DIR/systemd/evening-gates.service" "$UNIT_DIR/"
systemctl --user daemon-reload
systemd-analyze --user verify "$UNIT_DIR/evening-gates.service" \
|| fail "evening-gates.service does not verify"
echo "installed $UNIT_DIR/evening-gates.service (not enabled, not started)"
}
main "$@"

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "gatelock"
version = "0.15.1"
version = "0.16.0"
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
requires-python = ">=3.14"
dependencies = [] # pure stdlib — tkinter is bundled with Python
@ -16,6 +16,15 @@ dependencies = [] # pure stdlib — tkinter is bundled with Python
# because a dependency is missing is itself a way to end up unlocked.
# Consumers' install scripts install it unconditionally all the same.
randr = ["python-xlib==0.33"]
# The evening gate chain (gatelock.evening_chain) reads the signed ledgers and
# the free/sick-day pools. Optional for the same reason as randr: a locker
# must not refuse to start over a missing dependency, and only the chain's
# own CLI imports these (lazily). Pins match book-guard / leetcode-guard.
evening = [
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays",
]
[tool.setuptools.packages.find]
include = ["gatelock*"]
@ -114,6 +123,8 @@ ignore = [".venv", "__pycache__"]
# paths, so a directory name in `ignore` never fires under the hook.
ignore-paths = ["^(.*/)?tests/.*$"]
ignore-patterns = [".*\\.pyi$"]
# The evening chain reads these siblings; the pre-commit pylint env has none.
ignored-modules = ["earned_time", "freedays", "sickdays"]
[tool.pylint.messages_control]
enable = "all"

View File

@ -0,0 +1,16 @@
[Unit]
Description=Evening gate chain: book, tutor, LeetCode before night lockdown
After=graphical-session.target
# Started by root's day-specific-shutdown-check (systemctl --user -M kuhy@
# start) when `python3 -m gatelock.evening_chain pending` exits 0. There is no
# timer and no [Install]: arming it any other way would put a gate up on a day
# nobody asked for one.
[Service]
Type=simple
Environment=DISPLAY=:0
Environment=XAUTHORITY=%h/.Xauthority
ExecStart=/usr/bin/python3 -m gatelock.evening_chain run
# A stopped or finished chain stays stopped: root reads "inactive after it was
# started tonight" as "kuhy ended the evening" and enters lockdown.
Restart=no