Manual-workout phone sync P3: PC pushes its manual entries to pc/log.json

Two-way sync: the PC now publishes its own manual workouts so the phone can see
them for the shared budget. Reverses the old "the PC never pushes" invariant.

- _manual_push.py (new): a small crdt-sync store of PC-originated manuals
  (manual_sync_log.json, next to workout_log.json). record_pc_manual() appends
  the form's entry (wrapped as the shared kind/date payload under a stable
  manual: id, monotonic HLC); push_pc_manuals() runs one sync_log tick to
  devices/pc/log.json. Best-effort: no token, empty store, or a 403 from a
  read-only token is swallowed so the local form still works.
- _manual_workout_dialog.py: record the manual locally on form save (fast, both
  hosts) — published on the next lock startup.
- screen_lock.py: push_pc_manuals() runs in the startup sync step (also retries
  any manual a previous push failed to publish).
- Updated the now-false "PC only ever reads, never pushes" docstrings in
  _workout_sync.py and _constants.py; noted the contents:write PAT requirement.

A PC-pushed record round-trips through the same ingestion decoder, so it is
ingestable by any device. Full suite green at 100% coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PM3auNTifaVgcXWDizZrjH
This commit is contained in:
Krzysztof Rudnicki 2026-07-13 11:29:41 +02:00
parent 870a65015f
commit 233536d275
6 changed files with 288 additions and 9 deletions

View File

@ -113,8 +113,9 @@ RUNNERUP_EXPORT_DIRS: tuple[str, ...] = (
# Sync (phone workout data) — Workstream C, built on the shared crdt-sync
# library. GitHub is used purely as dumb file storage via the REST Contents
# API (not a git clone), same pattern as diet_guard's cross-device sync. The
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC only
# ever reads that one path, it never pushes here itself.
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC reads
# every device's log and pushes its OWN manual workouts to devices/pc/log.json
# (see _manual_push) — which needs a token with contents:write, not read-only.
# ---------------------------------------------------------------------------
SYNC_REPO_OWNER: str = "kuhyx"
SYNC_REPO_NAME: str = "syncs"

View File

@ -0,0 +1,141 @@
"""Push PC-originated manual workouts to the shared sync repo.
The PC manual-workout form writes its entry into ``workout_log.json`` (day-keyed,
locally). For the two-way shared budget, the PC must ALSO publish its manual
workouts to the sync repo so the phone can see them. This module keeps a small
crdt-sync log of *PC-originated* manuals (``manual_sync_log.json``, next to
``workout_log.json``) and pushes it to ``devices/pc/log.json``.
This reverses the old "the PC only ever reads, never pushes" invariant (it had
no data of its own to contribute); manual workouts are that data. Pushing needs
a sync token with **contents:write** on the repo — a read-only token 403s, which
is swallowed (best-effort), so the local form still works offline.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from crdt_sync import (
GitHubSyncClient,
GitHubSyncError,
Hlc,
Record,
sync_log,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_TIMEOUT_SECONDS,
)
from screen_locker._manual_workout import (
MANUAL_WORKOUT_SYNC_KIND,
_today_iso,
manual_sync_record_id,
)
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from crdt_sync import Log
_logger = logging.getLogger(__name__)
_PC_DEVICE_ID = "pc"
_STORE_FILENAME = "manual_sync_log.json"
_PAYLOAD_FIELD = "payload"
def _store_path(log_file: Path) -> Path:
"""Return the PC manual-sync store path next to ``workout_log.json``."""
return log_file.parent / _STORE_FILENAME
def _encode_log(log: Log) -> str:
"""Serialize a crdt-sync log to JSON (record id -> record dict)."""
return json.dumps({rid: record.to_dict() for rid, record in log.items()})
def _decode_log(text: str) -> Log:
"""Parse a crdt-sync log blob back into ``{id: Record}``."""
raw = json.loads(text)
return {rid: Record.from_dict(data) for rid, data in raw.items()}
def _load_store(store_file: Path) -> dict[str, Record]:
"""Load the local PC manual store, or ``{}`` if missing/corrupt."""
if not store_file.exists():
return {}
try:
return dict(_decode_log(store_file.read_text()))
except (OSError, ValueError, KeyError, TypeError):
_logger.warning("Corrupt PC manual store at %s — ignoring", store_file)
return {}
def _max_hlc(log: dict[str, Record]) -> Hlc | None:
"""Return the greatest HLC across the store's payload fields, if any."""
hlcs = [
record.fields[_PAYLOAD_FIELD][1]
for record in log.values()
if _PAYLOAD_FIELD in record.fields
]
return max(hlcs) if hlcs else None
def record_pc_manual(log_file: Path, entry: Mapping[str, object]) -> str:
"""Record a PC-originated manual workout into the local sync store.
``entry`` is the :func:`build_entry` dict the form already produced; this
wraps it in the shared sync payload (adds ``kind`` + ``date``) under a
stable ``manual:`` id and appends it to the store with a fresh monotonic
HLC. Fast and local — the network push happens separately
(:func:`push_pc_manuals`). Returns the record id.
"""
date = _today_iso()
store_file = _store_path(log_file)
log = _load_store(store_file)
payload = {**entry, "kind": MANUAL_WORKOUT_SYNC_KIND, "date": date}
record_id = manual_sync_record_id(date, str(entry.get("start_time", "")))
hlc = Hlc.new_tick(_PC_DEVICE_ID, previous=_max_hlc(log))
log[record_id] = Record(id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)})
store_file.write_text(_encode_log(log))
return record_id
def push_pc_manuals(log_file: Path) -> None:
"""Push the PC's manual-workout store to ``devices/pc/log.json``.
Best-effort: no token, an empty store, or any sync error (notably a 403
from a read-only token that lacks ``contents:write``) is swallowed so the
local form keeps working. Runs one full sync tick, so it also retries any
manuals a previous push failed to publish.
"""
token = read_sync_token()
if token is None:
return
log = _load_store(_store_path(log_file))
if not log:
return
client = GitHubSyncClient(
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
token,
timeout_seconds=SYNC_TIMEOUT_SECONDS,
)
try:
sync_log(
client=client,
device_id=_PC_DEVICE_ID,
path_prefix=_DEVICES_PREFIX,
local_log=log,
encode=_encode_log,
decode=_decode_log,
)
except GitHubSyncError as exc:
_logger.info("PC manual push skipped (%s)", exc)

View File

@ -24,6 +24,7 @@ from screen_locker._constants import (
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
)
from screen_locker._manual_push import record_pc_manual
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
_logger = logging.getLogger(__name__)
@ -296,4 +297,7 @@ class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
self._mw_error_label.config(text=error)
return
entry = _manual_workout.build_entry(draft)
# Record the manual for cross-device sync (published on the next lock
# startup). Local + best-effort — never blocks saving/unlocking.
record_pc_manual(self.log_file, entry)
self._on_manual_workout_saved(entry)

View File

@ -1,11 +1,11 @@
"""Pulls the phone's last-synced workout via crdt-sync's GitHub transport.
"""Pulls phone/other-device workouts via crdt-sync's GitHub transport.
GitHub is used purely as dumb file storage (see ``crdt_sync``'s own docs) --
the phone app pushes its completed-workout log to a private repo; this
module only ever reads it, it never pushes here itself (the PC has no
workout data of its own to contribute). Sync is optional: an unconfigured
token is a normal, expected state, not an error -- unlike diet_guard, where
sync is core to the app.
the phone app pushes its completed-workout log to a private repo; this module
reads the session log and every device's manual-workout records. (The PC does
push its OWN manual workouts, but via :mod:`screen_locker._manual_push`, not
here.) Sync is optional: an unconfigured token is a normal, expected state,
not an error -- unlike diet_guard, where sync is core to the app.
"""
from __future__ import annotations

View File

@ -40,6 +40,7 @@ from screen_locker._extra_benefits import (
)
from screen_locker._heat_skip import HeatSkipMixin
from screen_locker._log_mixin import LogMixin
from screen_locker._manual_push import push_pc_manuals
from screen_locker._manual_sync import ingest_manual_records
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._phone_verification import PhoneVerificationMixin
@ -217,7 +218,8 @@ class ScreenLocker(
self._check_heat_skip_exit()
def _ingest_synced_manual_workouts(self) -> None:
"""Log any manual workouts synced from the phone or another device."""
"""Sync manual workouts: publish this PC's, ingest everyone else's."""
push_pc_manuals(self.log_file)
ingested = ingest_manual_records(self.log_file, pull_all_manual_records())
for record_id in ingested:
_logger.info("Ingested synced manual workout: %s", record_id)

View File

@ -0,0 +1,131 @@
"""Tests for pushing PC-originated manual workouts to the sync repo."""
# pylint: disable=protected-access
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from crdt_sync import GitHubSyncError, Hlc, Record
from screen_locker import _manual_push, _workout_sync
from screen_locker._manual_push import (
_decode_log,
_encode_log,
_load_store,
_max_hlc,
_store_path,
push_pc_manuals,
record_pc_manual,
)
if TYPE_CHECKING:
from pathlib import Path
_ENTRY = {
"type": "manual_workout",
"source": "table tennis at Solec",
"sport": "table_tennis",
"start_time": "18:00",
"end_time": "19:30",
"location_name": "Solec",
"rpe": 6,
}
def _hlc(ms: int) -> Hlc:
return Hlc(wall_time_ms=ms, counter=0, node_id="pc")
def _record(record_id: str, ms: int) -> Record:
return Record(id=record_id, fields={"payload": ({"x": 1}, _hlc(ms))})
class TestEncodeDecodeRoundTrip:
def test_round_trips_a_log(self) -> None:
log = {"manual:a": _record("manual:a", 100)}
assert _decode_log(_encode_log(log)) == log
class TestLoadStore:
def test_missing_file_returns_empty(self, tmp_path: Path) -> None:
assert _load_store(tmp_path / "nope.json") == {}
def test_corrupt_file_returns_empty(self, tmp_path: Path) -> None:
store = tmp_path / "manual_sync_log.json"
store.write_text("{not json")
assert _load_store(store) == {}
def test_valid_file_round_trips(self, tmp_path: Path) -> None:
store = tmp_path / "manual_sync_log.json"
log = {"manual:a": _record("manual:a", 100)}
store.write_text(_encode_log(log))
assert _load_store(store) == log
class TestMaxHlc:
def test_empty_returns_none(self) -> None:
assert _max_hlc({}) is None
def test_returns_greatest_hlc(self) -> None:
log = {"a": _record("a", 100), "b": _record("b", 300)}
assert _max_hlc(log) == _hlc(300)
def test_skips_records_without_a_payload_field(self) -> None:
no_payload = Record(id="a", fields={"other": (1, _hlc(1))})
assert _max_hlc({"a": no_payload}) is None
class TestRecordPcManual:
def test_writes_a_manual_record(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_id = record_pc_manual(log_file, _ENTRY)
assert record_id.startswith("manual:")
assert record_id.endswith("T18:00")
store = _load_store(_store_path(log_file))
payload, _clock = store[record_id].fields["payload"]
assert payload["kind"] == "manual_workout"
assert "date" in payload
def test_second_record_has_a_greater_clock(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, {**_ENTRY, "start_time": "18:00"})
record_pc_manual(log_file, {**_ENTRY, "start_time": "20:00"})
store = _load_store(_store_path(log_file))
clocks = sorted(rec.fields["payload"][1] for rec in store.values())
assert clocks[0] < clocks[1]
class TestPushPcManuals:
def test_no_token_is_a_no_op(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
with patch.object(_manual_push, "read_sync_token", return_value=None):
push_pc_manuals(log_file) # no exception, no client
def test_empty_store_is_a_no_op(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
with patch.object(_manual_push, "GitHubSyncClient") as client_cls:
push_pc_manuals(log_file)
client_cls.assert_not_called()
def test_pushes_when_token_and_store_present(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
client = MagicMock()
client.list_directory.return_value = []
with patch.object(_manual_push, "GitHubSyncClient", return_value=client):
push_pc_manuals(log_file)
client.put_file_text.assert_called_once()
def test_swallows_a_sync_error(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
client = MagicMock()
client.list_directory.return_value = []
client.put_file_text.side_effect = GitHubSyncError("403")
with patch.object(_manual_push, "GitHubSyncClient", return_value=client):
push_pc_manuals(log_file) # swallowed, no raise