utils/freedays/freedays/_audit.py
Krzysztof kuhy Rudnicki 6154dc09bf Pin pre-commit's ruff to 0.16.7 and satisfy the CPY001 it brings
The three Python packages pinned ruff twice at different versions:
requirements.txt at 0.16.7, .pre-commit-config.yaml at v0.15.2. Only the
older one ever ran, so `select = ["ALL"]` was enforced two minor versions
behind. Measured before aligning: v0.15.2 reports 0 findings, every 0.16.x
reports CPY001 on each file -- 70 crdt-sync, 23 freedays, 71 gatelock, and
no other rule.

Resolved by adding the notice rather than ignoring the rule, so the gate
keeps its teeth.

Two gatelock modules sat at exactly the 250-line cap, so a one-line header
tipped them to 251. Both are split along a real seam rather than shaved:

  _widget_fills.py    colour arithmetic over LockConfig, no tkinter import
  _surfaces_focus.py  selects among existing surfaces, never mutates them

The focus split keeps _surfaces.py's documented containment (it stays the
only module that creates, moves or destroys windows), and the static guard
in test_recovery_invariants.py globs _surfaces*.py, so the new sibling is
covered with no list to extend. widgets.py re-exports the fills helpers,
which keeps gatelock.widgets the single public surface its tests import.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019kMvSMtsVMB3d2uoZ56pbp
2026-09-12 18:11:24 +02:00

72 lines
2.4 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki
"""Append-only, HMAC-signed trail of every mark and release.
Nothing reads this to make a decision -- the CRDT log is the truth, and this
file is deliberately not consulted by :mod:`freedays._api`. It exists so that
"when did I take that day, and from which device" is answerable later, and so
that a hand-edited entry is detectable rather than invisible.
Signing is best-effort on purpose. If the key is missing the entry is still
written, unsigned: an unsigned audit line is a much smaller problem than a
free day that could not be claimed because a key file was absent.
"""
from __future__ import annotations
from datetime import UTC, datetime
import json
import logging
from typing import TYPE_CHECKING, Any
from freedays._day import to_iso
from freedays._hmac import generate_key, sign
from freedays._paths import Paths, resolve_paths
if TYPE_CHECKING:
from datetime import date
_logger = logging.getLogger(__name__)
def record_event(
action: str,
day: date,
*,
actor: str,
reason: str = "",
paths: Paths | None = None,
) -> None:
"""Append one signed line describing a change to the pool.
Args:
action: ``"mark"`` or ``"release"``.
day: The day that changed.
actor: The device id that made the change.
reason: Optional free text supplied by the person.
paths: Where the trail and its signing key live.
"""
resolved = resolve_paths(paths)
entry: dict[str, Any] = {
"action": action,
"day": to_iso(day),
"actor": actor,
"reason": reason,
"at": datetime.now(tz=UTC).isoformat(),
}
key_target = resolved.hmac_key
if not key_target.exists():
# First run on this machine. Generating it here rather than in an
# installer means the trail is signed from its very first entry,
# with no setup step that can be skipped.
generate_key(key_target)
entry["hmac"] = sign(entry, key_file=key_target)
target = resolved.audit
try:
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(entry, sort_keys=True) + "\n")
except OSError as exc:
# An unwritable audit trail must never be the reason a day cannot be
# taken -- the caller has already committed the change to the log.
_logger.warning("could not append to the free-day audit trail: %s", exc)