mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-23 15:26:33 +01:00
Gate the free-day rules against the Python package, and fix two picker paths
showDatePicker asserts that initialDate satisfies selectableDayPredicate, so with today already free the picker asserted in debug and, in release, pre-selected a disabled day. The cursor now starts on the first non-free day. And the reason dialog had no Cancel: a barrier tap marked the day anyway. Both covered by widget tests; the first fails without the fix. The cross-language check that proved the Dart port was a one-off probe, deleted after it ran. It is now scripts/free_days_interop/check.sh, a pre-commit hook on both inputs: Dart writes one pool through every policy branch, Python replays the same edits into a scratch pool, and every semantic reading has to agree. The Python package is the oracle -- Dart's own count compared to what Python reads from Dart's file cannot see a drift in what Dart writes. Proved by dropping the sticky consumed flag from release: remaining dart=33 python=32. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019pBgaXSJKyY3DarYpDatDF
This commit is contained in:
parent
146c427d6d
commit
758b2976b8
@ -147,6 +147,15 @@ repos:
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
# The Dart free-day rules are a port of ~/utils/freedays; this replays
|
||||
# one edit sequence through both and fails on any semantic disagreement.
|
||||
# Only fires when either implementation's inputs change.
|
||||
- id: free-days-interop
|
||||
name: free-day rules agree with the Python package
|
||||
entry: scripts/free_days_interop/check.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: (phone_app/lib/services/free_day_pool\.dart|phone_app/test/free_day_interop_writer_test\.dart|scripts/free_days_interop/.*)$
|
||||
- id: shellcheck
|
||||
name: shellcheck
|
||||
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
||||
|
||||
@ -45,13 +45,17 @@ date → service start; a garbage XML file → service start.
|
||||
## Cross-language check
|
||||
|
||||
The Dart port is a second implementation of the rules, so it is verified
|
||||
against the Python one rather than against itself: a log written by
|
||||
`FreeDayPool` (mark, mark today, mark+release future, mark+release after
|
||||
arrival) read back with `freedays.is_free_day` / `remaining` gives the same
|
||||
verdicts and the same count (32 of 35), and the PC's live pool read by Dart
|
||||
gives the same 27 of 35 that `freedays status` prints. Rerun that whenever
|
||||
either side's policy changes — the shape test in `free_day_pool_test.dart`
|
||||
only checks field names, not semantics.
|
||||
against the Python one rather than against itself:
|
||||
`scripts/free_days_interop/check.sh` (a pre-commit hook on both inputs)
|
||||
writes one pool through `FreeDayPool` — mark, mark today, mark+release a
|
||||
future day, mark+release after arrival — replays the same edits through
|
||||
`freedays.mark`/`release` into a scratch pool, and fails unless the free set,
|
||||
spent set, `remaining` and `is_free_day` verdicts agree. Dart's own numbers
|
||||
are never the reference: comparing them to what Python reads from Dart's
|
||||
file cannot see a drift in what Dart *writes*. Proved on 2026-09-11 by
|
||||
dropping the sticky `consumed` from `release` — the gate reported
|
||||
`remaining: dart=33 python=32`. Needs the freedays venv
|
||||
(`~/utils/freedays/install.sh`).
|
||||
|
||||
## Do NOT
|
||||
|
||||
|
||||
@ -83,9 +83,17 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
||||
final pool = _pool;
|
||||
if (pool == null) return;
|
||||
final today = _today;
|
||||
// showDatePicker asserts that initialDate satisfies the predicate, so
|
||||
// when today is already free the cursor starts on the next day that is
|
||||
// not. Day arithmetic, not Duration: adding 24h across a DST change
|
||||
// lands on the same date twice.
|
||||
var initial = today;
|
||||
while (pool.isFree(initial)) {
|
||||
initial = DateTime(initial.year, initial.month, initial.day + 1);
|
||||
}
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: today,
|
||||
initialDate: initial,
|
||||
firstDate: today,
|
||||
lastDate: DateTime(today.year + 1, 12, 31),
|
||||
helpText: 'Take a free day',
|
||||
@ -93,8 +101,9 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
||||
);
|
||||
if (picked == null || !mounted) return;
|
||||
final reason = await _askReason();
|
||||
if (!mounted) return;
|
||||
await _apply(() => pool.mark(picked, reason: reason ?? '', now: today));
|
||||
// Null is Cancel or a barrier tap; an empty string is "no reason".
|
||||
if (reason == null || !mounted) return;
|
||||
await _apply(() => pool.mark(picked, reason: reason, now: today));
|
||||
}
|
||||
|
||||
/// Optional, by design. Enter with an empty field and nothing is stored.
|
||||
@ -110,6 +119,10 @@ class _FreeDaysScreenState extends State<FreeDaysScreen> {
|
||||
decoration: const InputDecoration(hintText: 'e.g. travelling'),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: const Text('Mark free'),
|
||||
|
||||
44
phone_app/test/free_day_interop_writer_test.dart
Normal file
44
phone_app/test/free_day_interop_writer_test.dart
Normal file
@ -0,0 +1,44 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wake_alarm_sync/services/free_day_pool.dart';
|
||||
|
||||
/// Half of the cross-language gate (`scripts/free_days_interop/check.sh`).
|
||||
///
|
||||
/// Writes a pool through the Dart rules to `FREE_DAYS_INTEROP_OUT`, then the
|
||||
/// script replays the same edits through the Python package and compares. Under a plain
|
||||
/// `flutter test` the variable is unset and this does nothing: the point is
|
||||
/// the comparison, and only the script can make it.
|
||||
class _FilePersistence implements LogPersistence {
|
||||
_FilePersistence(this.file);
|
||||
|
||||
final File file;
|
||||
|
||||
@override
|
||||
Future<String?> read() async =>
|
||||
file.existsSync() ? file.readAsStringSync() : null;
|
||||
|
||||
@override
|
||||
Future<void> write(String text) async => file.writeAsStringSync(text);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('writes the interop fixture when asked', () async {
|
||||
final out = Platform.environment['FREE_DAYS_INTEROP_OUT'];
|
||||
if (out == null) return;
|
||||
final pool = await FreeDayPool.open(
|
||||
persistence: _FilePersistence(File(out)),
|
||||
deviceId: 'dart-interop',
|
||||
);
|
||||
final now = DateTime(2026, 9, 11);
|
||||
// One of each policy branch: future, today (consumed on the spot),
|
||||
// future then refunded, and released only after it had arrived.
|
||||
await pool.mark(DateTime(2026, 9, 12), reason: 'from dart', now: now);
|
||||
await pool.mark(now, now: now);
|
||||
await pool.mark(DateTime(2026, 9, 13), now: now);
|
||||
await pool.release(DateTime(2026, 9, 13), now: now);
|
||||
await pool.mark(DateTime(2026, 9, 14), now: now);
|
||||
await pool.release(DateTime(2026, 9, 14), now: DateTime(2026, 9, 14));
|
||||
});
|
||||
}
|
||||
@ -140,6 +140,43 @@ void main() {
|
||||
expect(syncs, 1);
|
||||
});
|
||||
|
||||
testWidgets('the picker opens even when today is already free', (
|
||||
tester,
|
||||
) async {
|
||||
await pool.mark(_today, now: _today);
|
||||
await tester.pumpWidget(app());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Take a day'));
|
||||
await tester.pumpAndSettle();
|
||||
// The cursor moved to the 12th; today is disabled, not asserted on.
|
||||
expect(find.text('Take a free day'), findsOneWidget);
|
||||
await tester.tap(find.text('OK'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Mark free'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(pool.isFree(DateTime(2026, 9, 12)), isTrue);
|
||||
expect(find.text('33 of 35'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('cancelling the reason dialog marks nothing', (tester) async {
|
||||
await tester.pumpWidget(app());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Take a day'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('12'));
|
||||
await tester.tap(find.text('OK'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(pool.freeDays(), isEmpty);
|
||||
expect(find.text('35 of 35'), findsOneWidget);
|
||||
expect(syncs, 1);
|
||||
});
|
||||
|
||||
testWidgets('a pool that cannot open reports it', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
|
||||
1
scripts/free_days_interop/__init__.py
Normal file
1
scripts/free_days_interop/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Cross-language gate for the free-day pool; see check.sh."""
|
||||
58
scripts/free_days_interop/check.sh
Executable file
58
scripts/free_days_interop/check.sh
Executable file
@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Cross-language gate for the free-day pool.
|
||||
#
|
||||
# phone_app/lib/services/free_day_pool.dart reimplements the rules that
|
||||
# ~/utils/freedays (Python) owns. Two implementations of one policy drift,
|
||||
# and a Dart-only test cannot see it: it is self-consistent with the port.
|
||||
# This writes a pool through the Dart rules and reads it back through the
|
||||
# Python ones, and fails on any disagreement about what is free, what is
|
||||
# spent and how many days are left.
|
||||
#
|
||||
# Requires the freedays venv that install.sh in ~/utils/freedays creates.
|
||||
#
|
||||
# Usage: scripts/free_days_interop/check.sh
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
readonly SCRIPT_DIR REPO_DIR
|
||||
readonly FREEDAYS_PYTHON="${FREEDAYS_PYTHON:-$HOME/.local/share/freedays/venv/bin/python}"
|
||||
|
||||
TEMP_DIR=""
|
||||
cleanup() {
|
||||
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
|
||||
rm -rf "$TEMP_DIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
validate_requirements() {
|
||||
if [[ ! -x "$FREEDAYS_PYTHON" ]]; then
|
||||
echo "Error: no freedays venv at $FREEDAYS_PYTHON (run ~/utils/freedays/install.sh)" >&2
|
||||
exit 1
|
||||
fi
|
||||
command -v flutter >/dev/null || { echo "Error: flutter not on PATH" >&2; exit 1; }
|
||||
}
|
||||
|
||||
main() {
|
||||
validate_requirements
|
||||
TEMP_DIR="$(mktemp -d)"
|
||||
local pool="$TEMP_DIR/free_days.json"
|
||||
|
||||
echo "== free-day interop: Dart writes =="
|
||||
(
|
||||
cd "$REPO_DIR/phone_app"
|
||||
FREE_DAYS_INTEROP_OUT="$pool" flutter test test/free_day_interop_writer_test.dart \
|
||||
| tail -1
|
||||
)
|
||||
[[ -s "$pool" ]] || { echo "Error: Dart wrote no fixture" >&2; exit 1; }
|
||||
|
||||
echo "== free-day interop: Python reads =="
|
||||
"$FREEDAYS_PYTHON" "$SCRIPT_DIR/verify.py" "$pool"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
86
scripts/free_days_interop/verify.py
Normal file
86
scripts/free_days_interop/verify.py
Normal file
@ -0,0 +1,86 @@
|
||||
"""Replay the fixture's edits through the Python rules and compare the pools.
|
||||
|
||||
The Dart port in phone_app is a second implementation of ~/utils/freedays'
|
||||
policy, so it is checked against the original rather than against itself.
|
||||
Comparing Dart's *own* count to what Python reads from Dart's file cannot
|
||||
catch a drift in what Dart writes -- both sides would agree on the wrong
|
||||
record. So the Python package is the oracle: it performs the same
|
||||
mark/release sequence into a scratch pool, and every semantic reading of the
|
||||
two logs (free set, spent set, remaining, is_free_day) has to agree.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import freedays
|
||||
from freedays._api import load, mark, release
|
||||
from freedays._budget import free_days_in_year, remaining, spent_days_in_year
|
||||
from freedays._paths import Paths
|
||||
|
||||
EXPECTED_ARGC = 2
|
||||
|
||||
# Mirror of free_day_interop_writer_test.dart, one call per policy branch.
|
||||
TODAY = date(2026, 9, 11)
|
||||
DAYS = [date(2026, 9, 11), date(2026, 9, 12), date(2026, 9, 13), date(2026, 9, 14)]
|
||||
|
||||
|
||||
def python_pool(root: Path) -> Path:
|
||||
"""Write the oracle pool with the same edits the Dart fixture made."""
|
||||
paths = Paths(
|
||||
log=root / "free_days.json",
|
||||
device_id=root / "device_id",
|
||||
audit=root / "audit.jsonl",
|
||||
hmac_key=root / "hmac.key",
|
||||
sync_state=root / "sync_state.json",
|
||||
)
|
||||
mark(date(2026, 9, 12), reason="from dart", paths=paths, now=TODAY)
|
||||
mark(TODAY, paths=paths, now=TODAY)
|
||||
mark(date(2026, 9, 13), paths=paths, now=TODAY)
|
||||
release(date(2026, 9, 13), paths=paths, now=TODAY)
|
||||
mark(date(2026, 9, 14), paths=paths, now=TODAY)
|
||||
release(date(2026, 9, 14), paths=paths, now=date(2026, 9, 14))
|
||||
return paths.log
|
||||
|
||||
|
||||
def reading(pool: Path) -> dict[str, object]:
|
||||
"""Every semantic view of a pool that a gate or the picker relies on."""
|
||||
log = load(pool)
|
||||
return {
|
||||
"remaining": remaining(log, 2026),
|
||||
"spent": [d.isoformat() for d in spent_days_in_year(log, 2026)],
|
||||
"free": [d.isoformat() for d in free_days_in_year(log, 2026)],
|
||||
"is_free_day": {
|
||||
d.isoformat(): freedays.is_free_day(d, log_path=pool) for d in DAYS
|
||||
},
|
||||
"reason": freedays.lookup(date(2026, 9, 12), log_path=pool).reason,
|
||||
}
|
||||
|
||||
|
||||
def say(line: str) -> None:
|
||||
"""One report line; the shell wrapper shows these verbatim."""
|
||||
sys.stdout.write(line + "\n")
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
"""Compare the Dart-written pool at ``argv[1]`` with the oracle."""
|
||||
if len(argv) != EXPECTED_ARGC:
|
||||
sys.stderr.write(f"usage: {argv[0]} <free_days.json>\n")
|
||||
return 2
|
||||
dart = reading(Path(argv[1]))
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
python = reading(python_pool(Path(tmp)))
|
||||
ok = True
|
||||
for key, expected in python.items():
|
||||
same = dart[key] == expected
|
||||
ok = ok and same
|
||||
say(f"{'ok ' if same else 'XX '}{key}: dart={dart[key]} python={expected}")
|
||||
say("free-day interop: " + ("OK" if ok else "MISMATCH"))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
Loading…
Reference in New Issue
Block a user