utils/focus_project/focus_project/sources/__init__.py
Krzysztof kuhy Rudnicki c29d0989dd Clear inherited CI debt in the Python libs
main was red on file length, the noqa ban, codespell, test naming and
dart coverage; this change touches every one of those jobs.

- sickdays: set_enabled is keyword-only; the panel test splits in two
  with shared probes; the sync wire format moves to DOCS-sync.md.
- earned_time: _focus types the project as a Protocol, no noqa; the
  gate-maturity section moves to DOCS-maturity.md; codespell knows the
  `checkin` event name.
- focus_project: real fixes for every noqa (local-day clocks, typed
  fakes, logged broad catches, split helpers). The public API that
  focus-guard calls keeps its signatures; their PLR0913 exemption
  lives in pyproject with the reason, not in noqa.
- crdt-sync: pylint gets nacl/argon2, docstrings, and allows the
  public E2eLayout.of; _blobs moves to _e2e_blobs.py.
- crdt_sync_dart: Argon2Params and the header errors move to
  e2e_params.dart (re-exported); tests split and reach 100% lines.
- sql_drills: test helpers get a leading underscore, as in earned_time.

Todo: fda71ed1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:58:01 +01:00

90 lines
3.3 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki
"""Evidence adapters: each turns one record of work into time intervals.
An adapter is a module ``focus_project.sources.<name>`` exposing one pure,
read-only function::
def intervals(day: date, project: Project) -> list[Interval]
``Interval`` is ``(start, end)`` in unix seconds, ``start <= end``. Adapters
may return spans outside ``day``; :func:`collect` clips them. To add a source,
add the module and its name to :data:`ADAPTERS`; a name whose module does not
exist yet is skipped as inactive.
Failure mode (fail closed, named): an adapter that raises is logged and
contributes nothing; it never stops the others or the harvester.
"""
from __future__ import annotations
from datetime import date, datetime, time, timedelta
import importlib
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from focus_project._model import Project
Interval = tuple[float, float]
# Each heartbeat vouches for the five minutes before it.
HEARTBEAT_WINDOW_S = 300.0
ADAPTERS = ("activity", "leetcode", "browser")
_logger = logging.getLogger(__name__)
def heartbeat_interval(ts: float) -> Interval:
"""The span a heartbeat at ``ts`` covers: ``[ts - 300, ts]``."""
return (ts - HEARTBEAT_WINDOW_S, ts)
def day_bounds(day: date) -> Interval:
"""Local midnight to the next local midnight, as unix seconds."""
start = datetime.combine(day, time.min).astimezone()
end = datetime.combine(day + timedelta(days=1), time.min).astimezone()
return (start.timestamp(), end.timestamp())
def clip(spans: list[Interval], bounds: Interval) -> list[Interval]:
"""``spans`` limited to ``bounds``; empty and inverted spans dropped."""
lo, hi = bounds
out = [(max(a, lo), min(b, hi)) for a, b in spans]
return [(a, b) for a, b in out if b > a]
def collect_by_source(day: date, project: Project) -> dict[str, list[Interval]]:
"""Every adapter's clipped intervals for ``day``, keyed by adapter name.
Missing adapters are absent from the result; failing ones map to ``[]``.
"""
bounds = day_bounds(day)
found: dict[str, list[Interval]] = {}
for name in ADAPTERS:
module_name = f"{__name__}.{name}"
# A broken adapter must add 0, never stop the others.
try:
module = importlib.import_module(module_name)
except ModuleNotFoundError as exc:
if exc.name == module_name:
_logger.info("source %s: not installed (inactive)", name)
continue
_logger.exception("source %s: import failed, contributes 0", name)
found[name] = []
continue
except Exception: # pylint: disable=broad-exception-caught
_logger.exception("source %s: import failed, contributes 0", name)
found[name] = []
continue
# Fail closed: this source adds 0.
try:
found[name] = clip(list(module.intervals(day, project)), bounds)
except Exception: # pylint: disable=broad-exception-caught
_logger.exception("source %s: failed, contributes 0", name)
found[name] = []
return found
def collect(day: date, project: Project) -> list[Interval]:
"""All adapters' clipped intervals for ``day``, concatenated."""
return [s for spans in collect_by_source(day, project).values() for s in spans]