Compare commits

..

No commits in common. "966ec60f17f91c8f1ec0e448dc05e04a22e613c5" and "3589d166cdb4c33b8eaaa16e6f1215dceacb1c5c" have entirely different histories.

22 changed files with 757 additions and 887 deletions

View File

@ -1,34 +0,0 @@
name: file length
# The 250-line cap, enforced on push as well as in pre-commit
# (refactor_claude_todo.md, "make it permanent").
#
# Unlike the pre-commit hook, which only sees the files in a commit, this runs
# over the whole tree: the hook keeps a violation from being *introduced*, and
# this keeps one from surviving a path the hook never saw (a merge, a push
# from a machine without hooks installed, a rebase that resurrects a file).
#
# No paths filter on purpose. The cap applies to every file in the repo, so
# scoping this job to a subdirectory would be the one way to reintroduce the
# problem it exists to catch.
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
file-length:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Every file is at most 250 lines
run: bash scripts/check_file_length.sh --all

View File

@ -3,12 +3,8 @@ library;
export 'src/device.dart';
export 'src/firebase_account_provisioning.dart';
export 'src/firebase_auth_error.dart';
export 'src/firebase_auth_rest.dart';
export 'src/firebase_credentials.dart';
export 'src/firebase_client.dart';
export 'src/firebase_errors.dart';
export 'src/firebase_keys.dart';
export 'src/firebase_config.dart';
export 'src/firebase_settings.dart';
export 'src/github_client.dart';
@ -20,4 +16,3 @@ export 'src/remote_store.dart';
export 'src/secure_credential_store.dart';
export 'src/store.dart';
export 'src/sync.dart';
export 'src/sync_state.dart';

View File

@ -1,31 +0,0 @@
import 'dart:convert';
import 'remote_store.dart';
/// Raised for an authentication failure the caller must not silently ignore.
///
/// A [RemoteSyncError] so callers that only care about "sync is broken" can
/// catch one type, while a settings screen can single this out to say
/// "your password is wrong" rather than "the network is down".
class FirebaseAuthError extends RemoteSyncError {
FirebaseAuthError(super.message);
}
/// The human-readable reason buried in an identitytoolkit error body.
///
/// Returns an empty string for a non-JSON body (a proxy error page, say),
/// where the status code is all the detail there is.
String reasonFrom(String body) {
try {
final decoded = jsonDecode(body);
if (decoded is Map<String, dynamic>) {
final error = decoded['error'];
if (error is Map<String, dynamic>) return '(${error['message']})';
if (error is String) return '($error)';
}
} on FormatException {
// Non-JSON body (a proxy error page, say): the status code is all the
// detail there is.
}
return '';
}

View File

@ -11,12 +11,92 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'firebase_auth_error.dart';
import 'firebase_credentials.dart';
import 'remote_store.dart';
const _signInBase = 'https://identitytoolkit.googleapis.com/v1';
const _refreshBase = 'https://securetoken.googleapis.com/v1';
/// Refresh this long before the token actually expires.
///
/// An ID token lives ~1 h. Refreshing early means a tick that starts just
/// under the wire still finishes with a valid token, rather than 401ing
/// halfway through a multi-file push.
const _refreshSkew = Duration(minutes: 5);
/// Raised for an authentication failure the caller must not silently ignore.
///
/// A [RemoteSyncError] so callers that only care about "sync is broken" can
/// catch one type, while a settings screen can single this out to say
/// "your password is wrong" rather than "the network is down".
class FirebaseAuthError extends RemoteSyncError {
FirebaseAuthError(super.message);
}
/// One device's Firebase session: a short-lived ID token plus the long-lived
/// refresh token that mints the next one.
class FirebaseCredentials {
FirebaseCredentials({
required this.idToken,
required this.refreshToken,
required this.expiresAt,
});
factory FirebaseCredentials.fromJson(Map<String, dynamic> json) =>
FirebaseCredentials(
idToken: json['id_token'] as String,
refreshToken: json['refresh_token'] as String,
expiresAt: DateTime.parse(json['expires_at'] as String).toUtc(),
);
/// The bearer credential for Realtime Database requests. Expires quickly.
final String idToken;
/// The long-lived credential. **This is the secret worth protecting** --
/// store it in `flutter_secure_storage` on Android or a `0600` file on
/// Linux, never in plain `SharedPreferences`.
final String refreshToken;
final DateTime expiresAt;
/// Whether [idToken] is expired, or close enough that a tick starting now
/// might outlive it.
bool isExpiredAt(DateTime now) => !now.add(_refreshSkew).isBefore(expiresAt);
Map<String, dynamic> toJson() => {
'id_token': idToken,
'refresh_token': refreshToken,
'expires_at': expiresAt.toUtc().toIso8601String(),
};
}
/// Where a device keeps its [FirebaseCredentials] between runs.
///
/// Abstract because the right answer differs per platform, and one of the
/// callers (`wake_alarm` PC) is a **fresh process every minute** -- without
/// persistence it would re-authenticate 1440 times a day.
abstract interface class FirebaseCredentialStore {
Future<FirebaseCredentials?> load();
Future<void> save(FirebaseCredentials credentials);
Future<void> clear();
}
/// An in-memory [FirebaseCredentialStore], for tests and one-shot scripts.
class InMemoryCredentialStore implements FirebaseCredentialStore {
InMemoryCredentialStore([this._credentials]);
FirebaseCredentials? _credentials;
@override
Future<FirebaseCredentials?> load() async => _credentials;
@override
Future<void> save(FirebaseCredentials credentials) async =>
_credentials = credentials;
@override
Future<void> clear() async => _credentials = null;
}
/// Signs in and keeps a valid ID token available, refreshing as needed.
///
/// [apiKey] is the project's public Web API key -- not a secret, and safe to
@ -225,7 +305,7 @@ class FirebaseTokenProvider {
}
if (res.statusCode < 200 || res.statusCode >= 300) {
throw FirebaseAuthError(
'failed to $what: HTTP ${res.statusCode} ${reasonFrom(res.body)}',
'failed to $what: HTTP ${res.statusCode} ${_reason(res.body)}',
);
}
return jsonDecode(res.body) as Map<String, dynamic>;
@ -234,5 +314,20 @@ class FirebaseTokenProvider {
/// Pulls Google's machine-readable reason (`INVALID_PASSWORD`,
/// `TOKEN_EXPIRED`, `USER_DISABLED`, ...) out of an error body, so the
/// thrown message says what actually went wrong instead of just "400".
static String _reason(String body) {
try {
final decoded = jsonDecode(body);
if (decoded is Map<String, dynamic>) {
final error = decoded['error'];
if (error is Map<String, dynamic>) return '(${error['message']})';
if (error is String) return '($error)';
}
} on FormatException {
// Non-JSON body (a proxy error page, say): the status code is all the
// detail there is.
}
return '';
}
void close() => _http.close();
}

View File

@ -16,13 +16,90 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'firebase_auth_rest.dart';
import 'firebase_errors.dart';
import 'firebase_keys.dart';
import 'remote_store.dart';
const _httpUnauthorized = 401;
const _httpForbidden = 403;
/// Characters Realtime Database forbids in a key, plus `~` itself because it
/// is this module's escape character.
///
/// `/` is absent deliberately: it is the path separator, so it is handled by
/// splitting into segments before any segment is escaped.
const _escapedChars = {
'~': '~7E',
'.': '~2E',
r'$': '~24',
'#': '~23',
'[': '~5B',
']': '~5D',
};
/// Raised for a Realtime Database failure the caller must not silently
/// ignore.
class FirebaseSyncError extends RemoteSyncError {
FirebaseSyncError(super.message);
}
/// Raised when the database itself is unreachable or the credential is not
/// authorized for it.
///
/// The Firebase counterpart of `RepoNotFoundError`: it means "the database
/// URL is wrong, or the security rules reject this uid", as opposed to
/// "nothing has been pushed to that path yet", which is benign and surfaces
/// as a null/empty result.
class DatabaseNotFoundError extends FirebaseSyncError
implements RemoteNotFoundError {
DatabaseNotFoundError(super.message);
}
/// Escapes one path segment into a legal Realtime Database key.
///
/// RTDB rejects `. $ # [ ] /` in keys, and the REST API's trailing `.json`
/// is a *format suffix* rather than part of the path -- so a filename like
/// `log.json` cannot be stored verbatim. The mapping is a reversible `~XX`
/// hex escape (`log.json` -> `log~2Ejson`) rather than a lossy "strip the
/// extension", because callers see these names again: todo-app's
/// `listDirectory('todo-sync/notes')` returns *filenames*, not device
/// directories, and must keep getting `<uuid>.json` back.
///
/// `~` is used as the escape character because it is legal in RTDB keys and
/// unreserved in URLs, so the escaped form needs no percent-encoding -- which
/// would otherwise be decoded back into the illegal character by the server.
String encodeKey(String segment) {
final buffer = StringBuffer();
for (final rune in segment.split('')) {
buffer.write(_escapedChars[rune] ?? rune);
}
return buffer.toString();
}
/// Reverses [encodeKey].
String decodeKey(String key) {
final buffer = StringBuffer();
var index = 0;
while (index < key.length) {
final escape = key.length - index >= 3 ? key.substring(index, index + 3) : '';
final decoded = _escapeToChar[escape];
if (decoded == null) {
buffer.write(key[index]);
index += 1;
} else {
buffer.write(decoded);
index += 3;
}
}
return buffer.toString();
}
final Map<String, String> _escapeToChar = {
for (final entry in _escapedChars.entries) entry.value: entry.key,
};
/// Escapes every segment of a `/`-separated logical path.
String encodePath(String path) =>
path.split('/').where((s) => s.isNotEmpty).map(encodeKey).join('/');
/// Realtime Database seen through the same three-method contract as GitHub.
///
/// Reads and writes UTF-8 text blobs stored as JSON string leaves, so the
@ -47,9 +124,9 @@ class FirebaseRestClient implements RemoteStore, BulkMapReader {
Future<Uri> _uri(String path, {Map<String, String> query = const {}}) async {
final encoded = encodePath(path);
return Uri.parse(
'$_databaseUrl/$encoded.json',
).replace(queryParameters: {'auth': await auth.idToken(), ...query});
return Uri.parse('$_databaseUrl/$encoded.json').replace(
queryParameters: {'auth': await auth.idToken(), ...query},
);
}
/// Turns a non-2xx response into the right error type.

View File

@ -16,7 +16,6 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'firebase_auth_rest.dart';
import 'firebase_credentials.dart';
import 'firebase_client.dart';
import 'mirror_store.dart';
import 'remote_store.dart';
@ -137,10 +136,7 @@ Future<FirebaseRestClient> firebaseClientFor({
// than failing every sign-in against ''. Apps that know their uid should
// pass expectedUid so a mis-tapped account picker is caught here instead
// of turning into a silently denied sync.
await auth.signInWithGoogle(
idToken: google,
expectedUid: expectedUid ?? config.uid,
);
await auth.signInWithGoogle(idToken: google, expectedUid: expectedUid ?? config.uid);
} else if (password != null) {
await auth.signIn(email: config.email, password: password);
} else {

View File

@ -1,71 +0,0 @@
/// Refresh this long before the token actually expires.
///
/// An ID token lives ~1 h. Refreshing early means a tick that starts just
/// under the wire still finishes with a valid token, rather than 401ing
/// halfway through a multi-file push.
const _refreshSkew = Duration(minutes: 5);
/// One device's Firebase session: a short-lived ID token plus the long-lived
/// refresh token that mints the next one.
class FirebaseCredentials {
FirebaseCredentials({
required this.idToken,
required this.refreshToken,
required this.expiresAt,
});
factory FirebaseCredentials.fromJson(Map<String, dynamic> json) =>
FirebaseCredentials(
idToken: json['id_token'] as String,
refreshToken: json['refresh_token'] as String,
expiresAt: DateTime.parse(json['expires_at'] as String).toUtc(),
);
/// The bearer credential for Realtime Database requests. Expires quickly.
final String idToken;
/// The long-lived credential. **This is the secret worth protecting** --
/// store it in `flutter_secure_storage` on Android or a `0600` file on
/// Linux, never in plain `SharedPreferences`.
final String refreshToken;
final DateTime expiresAt;
/// Whether [idToken] is expired, or close enough that a tick starting now
/// might outlive it.
bool isExpiredAt(DateTime now) => !now.add(_refreshSkew).isBefore(expiresAt);
Map<String, dynamic> toJson() => {
'id_token': idToken,
'refresh_token': refreshToken,
'expires_at': expiresAt.toUtc().toIso8601String(),
};
}
/// Where a device keeps its [FirebaseCredentials] between runs.
///
/// Abstract because the right answer differs per platform, and one of the
/// callers (`wake_alarm` PC) is a **fresh process every minute** -- without
/// persistence it would re-authenticate 1440 times a day.
abstract interface class FirebaseCredentialStore {
Future<FirebaseCredentials?> load();
Future<void> save(FirebaseCredentials credentials);
Future<void> clear();
}
/// An in-memory [FirebaseCredentialStore], for tests and one-shot scripts.
class InMemoryCredentialStore implements FirebaseCredentialStore {
InMemoryCredentialStore([this._credentials]);
FirebaseCredentials? _credentials;
@override
Future<FirebaseCredentials?> load() async => _credentials;
@override
Future<void> save(FirebaseCredentials credentials) async =>
_credentials = credentials;
@override
Future<void> clear() async => _credentials = null;
}

View File

@ -1,19 +0,0 @@
import 'remote_store.dart';
/// Raised for a Realtime Database failure the caller must not silently
/// ignore.
class FirebaseSyncError extends RemoteSyncError {
FirebaseSyncError(super.message);
}
/// Raised when the database itself is unreachable or the credential is not
/// authorized for it.
///
/// The Firebase counterpart of `RepoNotFoundError`: it means "the database
/// URL is wrong, or the security rules reject this uid", as opposed to
/// "nothing has been pushed to that path yet", which is benign and surfaces
/// as a null/empty result.
class DatabaseNotFoundError extends FirebaseSyncError
implements RemoteNotFoundError {
DatabaseNotFoundError(super.message);
}

View File

@ -1,62 +0,0 @@
/// Characters Realtime Database forbids in a key, plus `~` itself because it
/// is this module's escape character.
///
/// `/` is absent deliberately: it is the path separator, so it is handled by
/// splitting into segments before any segment is escaped.
const _escapedChars = {
'~': '~7E',
'.': '~2E',
r'$': '~24',
'#': '~23',
'[': '~5B',
']': '~5D',
};
/// Escapes one path segment into a legal Realtime Database key.
///
/// RTDB rejects `. $ # [ ] /` in keys, and the REST API's trailing `.json`
/// is a *format suffix* rather than part of the path -- so a filename like
/// `log.json` cannot be stored verbatim. The mapping is a reversible `~XX`
/// hex escape (`log.json` -> `log~2Ejson`) rather than a lossy "strip the
/// extension", because callers see these names again: todo-app's
/// `listDirectory('todo-sync/notes')` returns *filenames*, not device
/// directories, and must keep getting `<uuid>.json` back.
///
/// `~` is used as the escape character because it is legal in RTDB keys and
/// unreserved in URLs, so the escaped form needs no percent-encoding -- which
/// would otherwise be decoded back into the illegal character by the server.
String encodeKey(String segment) {
final buffer = StringBuffer();
for (final rune in segment.split('')) {
buffer.write(_escapedChars[rune] ?? rune);
}
return buffer.toString();
}
/// Reverses [encodeKey].
String decodeKey(String key) {
final buffer = StringBuffer();
var index = 0;
while (index < key.length) {
final escape = key.length - index >= 3
? key.substring(index, index + 3)
: '';
final decoded = _escapeToChar[escape];
if (decoded == null) {
buffer.write(key[index]);
index += 1;
} else {
buffer.write(decoded);
index += 3;
}
}
return buffer.toString();
}
final Map<String, String> _escapeToChar = {
for (final entry in _escapedChars.entries) entry.value: entry.key,
};
/// Escapes every segment of a `/`-separated logical path.
String encodePath(String path) =>
path.split('/').where((s) => s.isNotEmpty).map(encodeKey).join('/');

View File

@ -15,7 +15,7 @@ library;
import 'dart:convert';
import 'firebase_credentials.dart';
import 'firebase_auth_rest.dart';
/// Reads a secret by key, returning null when absent.
typedef SecretReader = Future<String?> Function(String key);

View File

@ -5,10 +5,127 @@ import 'package:crypto/crypto.dart';
import 'log.dart';
import 'record.dart';
import 'remote_store.dart';
import 'sync_state.dart';
import 'store.dart';
const _defaultFilename = 'log.json';
/// What one device remembers between ticks so it can skip needless traffic.
///
/// Two facts, both cheap:
/// * [pushedRev] -- the hash of what this device last pushed, so an unchanged
/// log is not re-uploaded. 88% of the pushes in the GitHub-backed history
/// were byte-identical no-ops.
/// * [peerRevs] -- the hash each peer had last time we downloaded it, so an
/// unchanged peer is not re-downloaded.
///
/// **Must be stored next to the log itself and cleared with it.** Skipping an
/// unchanged peer is only sound because that peer's records are already
/// merged into the local log; a cache that outlived its log would skip peers
/// whose data had been lost.
class SyncState {
const SyncState({this.pushedRev, this.peerRevs = const {}});
factory SyncState.fromJson(Map<String, dynamic> json) => SyncState(
pushedRev: json['pushed_rev'] as String?,
peerRevs: {
for (final entry
in (json['peer_revs'] as Map<String, dynamic>? ?? {}).entries)
if (entry.value is String) entry.key: entry.value as String,
},
);
final String? pushedRev;
final Map<String, String> peerRevs;
Map<String, dynamic> toJson() => {
'pushed_rev': pushedRev,
'peer_revs': peerRevs,
};
}
/// Where [syncLog] persists its [SyncState] between runs.
///
/// Persistence is what makes the saving real for the short-lived callers:
/// `wake_alarm` PC is a fresh process every minute and `diet_guard` PC a
/// fresh process every 15 minutes, so an in-memory cache would save nothing.
abstract interface class SyncStateStore {
Future<SyncState> load();
Future<void> save(SyncState state);
}
/// A [SyncStateStore] that forgets everything, for tests and one-shot runs.
///
/// Correct but pessimistic: every tick re-downloads every peer and re-pushes
/// the local log, which is exactly the old behaviour.
class InMemorySyncStateStore implements SyncStateStore {
SyncState _state = const SyncState();
@override
Future<SyncState> load() async => _state;
@override
Future<void> save(SyncState state) async => _state = state;
}
/// A [SyncStateStore] that persists through a [LogPersistence] port.
///
/// This is the mobile counterpart to Python's `FileSyncStateStore`, and it is
/// what makes the revision saving real on a phone: an app is a fresh process
/// after every cold start, so an [InMemorySyncStateStore] would forget every
/// peer revision and re-download all of them on each launch -- the exact
/// traffic the revision scheme exists to avoid.
///
/// Takes the pure-Dart [LogPersistence] port rather than a `File` so it works
/// on web (where `dart:io` is unavailable) and is trivially faked in tests.
/// On mobile and desktop, pass a `FileLogPersistence` from
/// `package:crdt_sync/crdt_sync_io.dart`, which already writes atomically.
///
/// **Store this next to the log it describes and clear the two together.**
/// Skipping an unchanged peer is only sound because that peer's records are
/// already merged into the local log; state that outlived its log would skip
/// peers whose data had been lost. See [SyncState].
class PersistedSyncStateStore implements SyncStateStore {
/// Persists state through [persistence].
PersistedSyncStateStore(this._persistence);
final LogPersistence _persistence;
/// Returns the stored state, or a default one if absent or unreadable.
///
/// A corrupt or half-written file degrades to "remember nothing", which
/// costs one tick of extra traffic rather than failing the sync -- the same
/// fail-safe choice the Python side makes.
@override
Future<SyncState> load() async {
final String? text;
try {
text = await _persistence.read();
} on Exception {
return const SyncState();
}
if (text == null || text.isEmpty) return const SyncState();
try {
final decoded = jsonDecode(text);
if (decoded is! Map<String, dynamic>) return const SyncState();
return SyncState.fromJson(decoded);
} on FormatException {
return const SyncState();
}
}
@override
Future<void> save(SyncState state) async =>
_persistence.write(jsonEncode(state.toJson()));
}
/// The revision of a serialized log: a content hash, not a clock reading.
///
/// A hash rather than the log's maximum HLC because merging a peer's *older*
/// record changes the content without raising the maximum -- with three
/// devices in one namespace (diet-guard has `pc`, `phone` and `desktop`) a
/// clock-based revision can miss a peer's merged state. It is also the same
/// value used to suppress no-op pushes, so the two optimisations share one
/// mechanism.
String revisionOf(String encodedLog) =>
sha256.convert(utf8.encode(encodedLog)).toString();

View File

@ -1,121 +0,0 @@
import 'dart:convert';
import 'store.dart';
/// What one device remembers between ticks so it can skip needless traffic.
///
/// Two facts, both cheap:
/// * [pushedRev] -- the hash of what this device last pushed, so an unchanged
/// log is not re-uploaded. 88% of the pushes in the GitHub-backed history
/// were byte-identical no-ops.
/// * [peerRevs] -- the hash each peer had last time we downloaded it, so an
/// unchanged peer is not re-downloaded.
///
/// **Must be stored next to the log itself and cleared with it.** Skipping an
/// unchanged peer is only sound because that peer's records are already
/// merged into the local log; a cache that outlived its log would skip peers
/// whose data had been lost.
class SyncState {
const SyncState({this.pushedRev, this.peerRevs = const {}});
factory SyncState.fromJson(Map<String, dynamic> json) => SyncState(
pushedRev: json['pushed_rev'] as String?,
peerRevs: {
for (final entry
in (json['peer_revs'] as Map<String, dynamic>? ?? {}).entries)
if (entry.value is String) entry.key: entry.value as String,
},
);
final String? pushedRev;
final Map<String, String> peerRevs;
Map<String, dynamic> toJson() => {
'pushed_rev': pushedRev,
'peer_revs': peerRevs,
};
}
/// Where [syncLog] persists its [SyncState] between runs.
///
/// Persistence is what makes the saving real for the short-lived callers:
/// `wake_alarm` PC is a fresh process every minute and `diet_guard` PC a
/// fresh process every 15 minutes, so an in-memory cache would save nothing.
abstract interface class SyncStateStore {
Future<SyncState> load();
Future<void> save(SyncState state);
}
/// A [SyncStateStore] that forgets everything, for tests and one-shot runs.
///
/// Correct but pessimistic: every tick re-downloads every peer and re-pushes
/// the local log, which is exactly the old behaviour.
class InMemorySyncStateStore implements SyncStateStore {
SyncState _state = const SyncState();
@override
Future<SyncState> load() async => _state;
@override
Future<void> save(SyncState state) async => _state = state;
}
/// A [SyncStateStore] that persists through a [LogPersistence] port.
///
/// This is the mobile counterpart to Python's `FileSyncStateStore`, and it is
/// what makes the revision saving real on a phone: an app is a fresh process
/// after every cold start, so an [InMemorySyncStateStore] would forget every
/// peer revision and re-download all of them on each launch -- the exact
/// traffic the revision scheme exists to avoid.
///
/// Takes the pure-Dart [LogPersistence] port rather than a `File` so it works
/// on web (where `dart:io` is unavailable) and is trivially faked in tests.
/// On mobile and desktop, pass a `FileLogPersistence` from
/// `package:crdt_sync/crdt_sync_io.dart`, which already writes atomically.
///
/// **Store this next to the log it describes and clear the two together.**
/// Skipping an unchanged peer is only sound because that peer's records are
/// already merged into the local log; state that outlived its log would skip
/// peers whose data had been lost. See [SyncState].
class PersistedSyncStateStore implements SyncStateStore {
/// Persists state through [persistence].
PersistedSyncStateStore(this._persistence);
final LogPersistence _persistence;
/// Returns the stored state, or a default one if absent or unreadable.
///
/// A corrupt or half-written file degrades to "remember nothing", which
/// costs one tick of extra traffic rather than failing the sync -- the same
/// fail-safe choice the Python side makes.
@override
Future<SyncState> load() async {
final String? text;
try {
text = await _persistence.read();
} on Exception {
return const SyncState();
}
if (text == null || text.isEmpty) return const SyncState();
try {
final decoded = jsonDecode(text);
if (decoded is! Map<String, dynamic>) return const SyncState();
return SyncState.fromJson(decoded);
} on FormatException {
return const SyncState();
}
}
@override
Future<void> save(SyncState state) async =>
_persistence.write(jsonEncode(state.toJson()));
}
/// The revision of a serialized log: a content hash, not a clock reading.
///
/// A hash rather than the log's maximum HLC because merging a peer's *older*
/// record changes the content without raising the maximum -- with three
/// devices in one namespace (diet-guard has `pc`, `phone` and `desktop`) a
/// clock-based revision can miss a peer's merged state. It is also the same
/// value used to suppress no-op pushes, so the two optimisations share one
/// mechanism.

View File

@ -16,12 +16,6 @@ analyzer:
- "**/*.g.dart"
- "**/*.freezed.dart"
- "test/**"
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:

View File

@ -5,8 +5,72 @@ import 'package:flutter/material.dart';
import 'package:sync_settings_ui/src/backup_slot.dart';
import 'package:sync_settings_ui/src/firebase_sync_controller.dart';
part 'sync_settings_sections.dart';
part 'sync_settings_widget.dart';
/// The shared "Sync settings" screen: Firebase sync (primary, shown by
/// default) and an optional local backup section.
///
/// Generalized from the near-identical settings screens duplicated across
/// the todo app, diet_guard_app, workout_app, wake_alarm/phone_app and
/// home_inventory. Only the sync-related fields migrate here -- app-specific
/// settings (kcal goals, exercise thresholds, notifications, the
/// battery-exemption toggle) stay behind in each app's own Settings screen,
/// reached via a `ListTile` link to this one.
class SyncSettingsScreen extends StatefulWidget {
/// Creates a [SyncSettingsScreen].
const SyncSettingsScreen({
required this.accountLoader,
required this.accountSaver,
required this.accountClearer,
required this.sessionProbe,
required this.firebaseFactory,
this.googleFirebaseFactory,
this.googleAvailable,
this.backup,
super.key,
});
/// Reads the stored Firebase account. Injected because the keystore is a
/// platform channel `flutter test` has no binding for.
final Future<FirebaseAccount?> Function() accountLoader;
/// Persists the account. See [accountLoader].
final Future<void> Function(FirebaseAccount) accountSaver;
/// Forgets the account and any cached session. See [accountLoader].
final Future<void> Function() accountClearer;
/// Whether a Firebase session is stored.
///
/// Separate from [accountLoader] because the two answer different
/// questions: the account marker is bookkeeping, the session is the
/// credential. A device can hold the second without the first, and
/// reporting only the first is what made a syncing phone read as
/// "not connected".
final Future<bool> Function() sessionProbe;
/// Builds the Firebase backend from the stored account. Injected so tests
/// can supply a fake.
final Future<FirebaseRestClient?> Function() firebaseFactory;
/// Builds the Firebase backend via Google sign-in. Separate from
/// [firebaseFactory] because it reaches the Google plugin's platform
/// channel. Null hides the "Sign in with Google" button entirely.
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
/// Narrows whether to offer the Google button. Can only turn it off, never
/// on: the button always requires a non-null [googleFirebaseFactory]
/// regardless of this value, so a host that sets this true without also
/// wiring the factory does not get a button that can never succeed. Tests
/// pass `false` to model a platform that reports Google sign-in
/// unsupported even though a factory is wired.
final bool? googleAvailable;
/// Optional local export/import section. Null omits the "Backup" section
/// entirely (diet_guard, wake_alarm have no local backup format).
final BackupSlot? backup;
@override
State<SyncSettingsScreen> createState() => _SyncSettingsScreenState();
}
class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
late final FirebaseSyncController _firebase = FirebaseSyncController(
@ -190,3 +254,129 @@ class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
);
}
}
class _FirebaseSection extends StatelessWidget {
const _FirebaseSection({
required this.connected,
required this.busy,
required this.googleAvailable,
required this.emailController,
required this.passwordController,
required this.onConnectPassword,
required this.onConnectGoogle,
required this.onDisconnect,
});
final bool connected;
final bool busy;
final bool googleAvailable;
final TextEditingController emailController;
final TextEditingController passwordController;
final VoidCallback onConnectPassword;
final VoidCallback onConnectGoogle;
final VoidCallback onDisconnect;
@override
Widget build(BuildContext context) {
if (connected) {
return Row(
children: [
const Icon(Icons.cloud_done, size: 20),
const SizedBox(width: 8),
Expanded(child: Text(emailController.text)),
TextButton(
onPressed: busy ? null : onDisconnect,
child: const Text('Disconnect'),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (googleAvailable) ...[
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: busy ? null : onConnectGoogle,
icon: const Icon(Icons.account_circle),
label: const Text('Sign in with Google'),
),
),
const SizedBox(height: 12),
],
ExpansionTile(
initiallyExpanded: !googleAvailable,
title: const Text('Use the account password instead'),
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(bottom: 8),
children: [
TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account email',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: passwordController,
obscureText: true,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account password',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: busy ? null : onConnectPassword,
icon: const Icon(Icons.cloud_done),
label: const Text('Connect Firebase'),
),
),
],
),
],
);
}
}
class _BackupSection extends StatelessWidget {
const _BackupSection({
required this.backup,
required this.onExport,
required this.onImport,
});
final BackupSlot backup;
final VoidCallback onExport;
final VoidCallback onImport;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: onExport,
icon: const Icon(Icons.upload),
label: Text('Export ${backup.label}'),
),
),
const SizedBox(width: 12),
Expanded(
child: OutlinedButton.icon(
onPressed: onImport,
icon: const Icon(Icons.download),
label: Text('Import ${backup.label}'),
),
),
],
);
}
}

View File

@ -1,132 +0,0 @@
part of 'sync_settings_screen.dart';
/// The two sections the screen composes.
///
/// Split from sync_settings_screen.dart for the 250-line cap;
/// a `part` rather than an import because both sections are
/// library-private and could not be imported at all.
class _FirebaseSection extends StatelessWidget {
const _FirebaseSection({
required this.connected,
required this.busy,
required this.googleAvailable,
required this.emailController,
required this.passwordController,
required this.onConnectPassword,
required this.onConnectGoogle,
required this.onDisconnect,
});
final bool connected;
final bool busy;
final bool googleAvailable;
final TextEditingController emailController;
final TextEditingController passwordController;
final VoidCallback onConnectPassword;
final VoidCallback onConnectGoogle;
final VoidCallback onDisconnect;
@override
Widget build(BuildContext context) {
if (connected) {
return Row(
children: [
const Icon(Icons.cloud_done, size: 20),
const SizedBox(width: 8),
Expanded(child: Text(emailController.text)),
TextButton(
onPressed: busy ? null : onDisconnect,
child: const Text('Disconnect'),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (googleAvailable) ...[
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: busy ? null : onConnectGoogle,
icon: const Icon(Icons.account_circle),
label: const Text('Sign in with Google'),
),
),
const SizedBox(height: 12),
],
ExpansionTile(
initiallyExpanded: !googleAvailable,
title: const Text('Use the account password instead'),
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(bottom: 8),
children: [
TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account email',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: passwordController,
obscureText: true,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account password',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: busy ? null : onConnectPassword,
icon: const Icon(Icons.cloud_done),
label: const Text('Connect Firebase'),
),
),
],
),
],
);
}
}
class _BackupSection extends StatelessWidget {
const _BackupSection({
required this.backup,
required this.onExport,
required this.onImport,
});
final BackupSlot backup;
final VoidCallback onExport;
final VoidCallback onImport;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: onExport,
icon: const Icon(Icons.upload),
label: Text('Export ${backup.label}'),
),
),
const SizedBox(width: 12),
Expanded(
child: OutlinedButton.icon(
onPressed: onImport,
icon: const Icon(Icons.download),
label: Text('Import ${backup.label}'),
),
),
],
);
}
}

View File

@ -1,68 +0,0 @@
part of 'sync_settings_screen.dart';
/// The shared "Sync settings" screen: Firebase sync (primary, shown by
/// default) and an optional local backup section.
///
/// Generalized from the near-identical settings screens duplicated across
/// the todo app, diet_guard_app, workout_app, wake_alarm/phone_app and
/// home_inventory. Only the sync-related fields migrate here -- app-specific
/// settings (kcal goals, exercise thresholds, notifications, the
/// battery-exemption toggle) stay behind in each app's own Settings screen,
/// reached via a `ListTile` link to this one.
class SyncSettingsScreen extends StatefulWidget {
/// Creates a [SyncSettingsScreen].
const SyncSettingsScreen({
required this.accountLoader,
required this.accountSaver,
required this.accountClearer,
required this.sessionProbe,
required this.firebaseFactory,
this.googleFirebaseFactory,
this.googleAvailable,
this.backup,
super.key,
});
/// Reads the stored Firebase account. Injected because the keystore is a
/// platform channel `flutter test` has no binding for.
final Future<FirebaseAccount?> Function() accountLoader;
/// Persists the account. See [accountLoader].
final Future<void> Function(FirebaseAccount) accountSaver;
/// Forgets the account and any cached session. See [accountLoader].
final Future<void> Function() accountClearer;
/// Whether a Firebase session is stored.
///
/// Separate from [accountLoader] because the two answer different
/// questions: the account marker is bookkeeping, the session is the
/// credential. A device can hold the second without the first, and
/// reporting only the first is what made a syncing phone read as
/// "not connected".
final Future<bool> Function() sessionProbe;
/// Builds the Firebase backend from the stored account. Injected so tests
/// can supply a fake.
final Future<FirebaseRestClient?> Function() firebaseFactory;
/// Builds the Firebase backend via Google sign-in. Separate from
/// [firebaseFactory] because it reaches the Google plugin's platform
/// channel. Null hides the "Sign in with Google" button entirely.
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
/// Narrows whether to offer the Google button. Can only turn it off, never
/// on: the button always requires a non-null [googleFirebaseFactory]
/// regardless of this value, so a host that sets this true without also
/// wiring the factory does not get a button that can never succeed. Tests
/// pass `false` to model a platform that reports Google sign-in
/// unsupported even though a factory is wired.
final bool? googleAvailable;
/// Optional local export/import section. Null omits the "Backup" section
/// entirely (diet_guard, wake_alarm have no local backup format).
final BackupSlot? backup;
@override
State<SyncSettingsScreen> createState() => _SyncSettingsScreenState();
}

View File

@ -144,11 +144,96 @@ per-repo duplicate, since all three already depend on it. Extending
(`/usr/bin/python3 -c "import gatelock"`) since it backs 3 live systemd
services — a dev-venv-only check is not sufficient.
## Pointer-free + small-screen
## Pointer-free + small-screen: per-stack patterns
The rules are in [`operability.md`](operability.md); the per-stack code that
satisfies them — Flutter, web and Python/Tkinter — is in
[`operability-patterns.md`](operability-patterns.md).
The rules themselves are in [`tokens.md`](tokens.md) (*Pointer-free
operability*, *Screen size*). This is how to implement them per stack. Both are
machine-checked — a static lint in pre-commit plus a render test in each repo's
suite — so treat these as the shape the checks expect.
### Flutter
```dart
// Reach: never a bare GestureDetector for an action.
InkWell(onTap: select, child: cell) // focusable + Enter/Space
// A destructive action needs a focusable control, not just onLongPress:
IconButton(icon: Icon(Icons.delete), onPressed: confirmDelete)
// App-level accelerators. On the Chrome --app desktop surface, avoid chords
// Chrome reserves (Ctrl+N/T/W/Shift+N) — they never reach Flutter.
Shortcuts(shortcuts: {
SingleActivator(LogicalKeyboardKey.keyS, control: true): SaveIntent(),
SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
}, child: Actions(actions: {...}, child: child));
// Size: budget height, clamp width.
final short = MediaQuery.sizeOf(context).height < 700; // 768 minus chrome
ConstrainedBox(constraints: BoxConstraints(maxWidth: kProseMaxWidth), child: prose);
```
Any screen whose content can grow needs a `SingleChildScrollView`/`ListView` —
a `Column` with one `Expanded` child does not scroll, it just collapses the
flexible child until it is unusable. Bottom sheets need `isScrollControlled:
true` plus an inner scroll view.
Note on **Flutter web** (todo-app and diet-guard's desktop surface are the web
build in a Chrome `--app` window, not the Linux embedder): the semantics tree is
not built unless assistive tech is detected, so `Semantics` is not a substitute
for real focusability — use focusable widgets, and treat `Semantics` as
additive.
### Web
`:focus-visible` must be styled everywhere, and never removed:
```css
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
/* Never `outline: none` without an equally visible replacement. */
```
Verify at the required viewports with no horizontal scroll and no *inner*
scrollbar: `1366x768` and `1024x600` at minimum. Prefer a compact baseline that
grows, over a desktop layout that must shrink.
### Python/Tkinter
Font sizes are **negative** (see `tokens.md` — positive means points and
inflates everything ~37%). The focus ring and both scales live on
`gatelock.LockConfig` so all four lockers inherit them:
```python
# focused ring — NOT highlightbackground, which is the *unfocused* ring
widget.configure(highlightcolor=cfg.focus_ring, highlightthickness=2)
widget.configure(font=(cfg.font_family, -cfg.type_body)) # negative == pixels
```
Tk specifics that are easy to get wrong, all verified against Tk 8.6's own
class bindings:
- `tk.Button` binds `<space>` on X11 but **not** `<Return>`; `Entry`/`Spinbox`
bind `<Return>` to nothing. Bind `<Return>` yourself for submit.
- `tk.Text` traps `<Tab>` (inserts a literal tab, refocuses itself) and makes
`<Shift-Tab>` a no-op. Rebind both to move focus, or the box is a dead end.
- `tk.Canvas` has no class key bindings, so a Canvas scroll viewport is not even
a focus stop. Bind `<Prior>`/`<Next>`/arrows, **and** add a `<FocusIn>` handler
on children that scrolls the focused child into view — clipping does not
unmap children, so focus walks into invisible fields by default.
- `OptionMenu`/`Menubutton` default to `takefocus=0`. On lock surfaces they are
banned anyway (a posted menu steals the grab); use radio buttons.
- `ttk.Notebook` needs an explicit `enable_traversal()` for `Ctrl+Tab` /
`Ctrl+PageDown` / `Alt`+mnemonic.
- Verify the focus ring by *walking* it (`tk_focusNext`), not by reading code.
Measure the height rather than eyeballing it — this is how the meal-gate
overflow was found, and it is what the render half of the gate does:
```bash
xvfb-run -s "-screen 0 1366x768x24" python3 -m your_pkg.tests.measure_layout
# assert frame.winfo_reqheight() <= available_pane_height
```
Measure both empty **and** fully populated (a day of meals logged, history rows
present) — the empty case is not the worst case.
## Do NOT

View File

@ -137,12 +137,116 @@ The five `GitHubMirrorScreen` copies each carry a near-verbatim "kept
app-local rather than folded into `sync_settings_ui`" comment. That decision
deserves revisiting **on its own**, not smuggled into a component extraction.
### Shipped work
### Flutter — palette drift: DONE 2026-08-14
Palette drift, Phase 2 (Python/Tk) and Phase 3 (TypeScript) are all done. The
decisions behind them — including two deliberate exceptions that must not be
"corrected" back, and the remaining Flutter adopters — are in
[`shipped-record.md`](shipped-record.md).
Standing decision: every app uses **exactly** the frozen palette; where copies
disagree, the most popular wins. That was unambiguous — 9 of 10 theme files
already used the gold `#B8862E` family. All four drifted repos are migrated.
| Repo | Drift that was fixed | How |
|---|---|---|
| `testsAndMisc/focus_owner` | **entirely off-palette**: cool `#5B9DD9` accent, `#1B1D21` field, `#D9776B` danger. Its doc comment claimed it matched the other `com.kuhy.*` apps; it did not. The same six constants were also **duplicated verbatim** in `main.dart:16-21` — the file said they had been "lifted out", but the originals were never deleted. | `theme.dart` now aliases `AppPalette`, so the ~80 call sites keep their names; both copies gone. Literals 15 → 2 (`Colors.transparent`). Verified on the Pixel 6a. |
| `kuhylog` | the only repo using `ColorScheme.fromSeed` (blue `#3B82F6`) — the opposite of what every other theme file documents. | `KuhylogTheme.of()` delegates to `buildLightTheme`/`buildDarkTheme`. Kept as a wrapper for its `visualDensity`, flat `cardTheme` and `scoreColor`. Literals 1 → 0. |
| `epopeja_karta` | `ColorScheme` inlined in `app.dart`, no `theme.dart`. | Imports **tokens only** — see below. Literals 9 → 0. |
| `billsplit` | `ColorScheme.fromSeed(Colors.teal)` plus 15 ad hoc literals that mostly bypassed the theme entirely. | `buildLightTheme()`; error family → `error`/`onError`/`errorContainer`, muted text → `onSurfaceVariant`. Literals 15 → 4. |
| `diet-guard`, `macro-cam` | scales drifted from the six-repo consensus | **still outstanding** — adopt `design_system` |
Two deliberate exceptions, so nobody "fixes" them back:
- **`epopeja_karta` adopts `AppPalette`, not `buildDarkTheme()`.** Its nine
slots were already byte-identical to the frozen palette, so only the
transcription was local. It is one dense screen with a test asserting
nothing scrolls, and the shared theme's larger type scale plus
`dividerTheme.space` overflows it by 34px. Typography there is a product
decision; colour is the identity, and colour is what the system owns.
Importing tokens leaves the rendered `ThemeData` identical, so the no-scroll
test passes by construction rather than by hitting a pixel target.
- **`billsplit` keeps its four category-dot colours** (`deepOrange`/`amber`/
`blueGrey`/`teal` for alcohol/mixer/deposit/other). They encode *category
identity*, not a theme role, and a single-accent system has no four distinct
hues to lend. Folding them into `primary`/`secondary`/`tertiary` would make
the categories stop being distinguishable, which is their only job. **This
is the open categorical-ramp question** — the design system currently has no
answer for "N mutually distinguishable hues", and it needs one before any
chart, tag or category UI can be built on it.
### Remaining Flutter adopters
`home_inventory`, `dufs-cloud`, `habit_stack`, `diet-guard`, `macro-cam`,
`wake-alarm/phone_app`. Each drops its local `theme.dart` for the tag-pinned
dep, as todo, untools, focus_owner, kuhylog, epopeja_karta and billsplit now
do. These six were never off-palette — they transcribe the right values by
hand — so this is duplication cleanup, not a visual fix.
### Phase 2 — Python/Tk (`~/utils/gatelock`), SHIPPED (gatelock 0.5.0)
> **Status: done.** `make_button`, `heading`/`row`, `ScrollableSurface` and
> `WidgetGroup` all ship in gatelock 0.5.0 (`c963cd8`, `d82107a`, `d25f288`);
> diet-guard and leetcode-guard are the migrated proof consumers.
> screen-locker (v0.4.0) and wake-alarm (v0.4.1) keep local fan-out copies
> **by design** — only two consumers were bumped to avoid restarting live
> systemd services. That asymmetry is not a regression; do not "fix" it.
> Everything below this line is the original plan, kept as the record of why.
Not a new package: gatelock already owns the tokens (`LockConfig`), the Tk
plumbing and 4 consumers. Add composite widgets, which is where its scope
currently stops.
1. `widgets.py::make_button` — canonical is diet-guard's
`_gatelock_buttons.py::make_button`, whose `variant` API picks text color
*from* the fill and so structurally prevents the `fg`-vs-`on_fill` contrast
bug. leetcode-guard's `_button` (no `<Return>` binding) and screen-locker's
inline `tk.Button` are the regressions being retired.
2. `widgets.py::heading()` / `row()` — from `leetcode_guard/_status_sections.py`.
3. **Export the existing `ScrollableSurface`** and delete
`leetcode_guard/status_view.py::_scrollable`, a hand-rolled reimplementation
that lost `takefocus` and the focus ring. Straight accessibility repair.
4. `widget_group.py::WidgetGroup` — the per-output fan-out reimplemented 4×
(~916 lines: screen-locker 173, leetcode-guard 105, diet-guard 309,
wake-alarm 329). Highest line-count win on this stack.
Proof consumers: `diet-guard` and `leetcode-guard` (donor and worst offender).
Bump **only those two**; leave screen-locker and wake-alarm on their current
pin — Phase 2 is additive, and restarting live services is blast radius for no
gain.
> **Verification gate — non-negotiable.** gatelock backs live systemd
> services. After any change: `/usr/bin/python3 -c "import gatelock"` against
> the real interpreter, not a dev venv. Do not touch the gate window's grab
> path. Then launch each gate under `xvfb-run -s "-screen 0 1366x768x24"` and
> confirm buttons render and **`<Return>` activates** them.
### Phase 3 — TypeScript (`~/utils/web_ui`), SHIPPED (web_ui-v0.3.1)
> **Status: done** — see `phase3-record.md` for what shipped and, importantly,
> why `FilterBar` was *not* extracted (a name collision, not a duplicate).
> Both proof consumers (dufs-cloud, awesome-mcp-explorer) are migrated.
> Everything below this line is the original plan, kept as the record of why.
Lowest confirmed duplication (2 components, 2 repos) and the only stack needing
a brand-new consumption mechanism, so it carries the worst effort-to-payoff
ratio — sequenced last on purpose.
1. `tokens.css` — one `:root` block. Fixes the worst fork found: **7 repos
define 7 different vocabularies for the same palette** (`--surface-1` vs
`--panel` vs `--card`; `--text` vs `--ink` vs `--fg` vs `--bone`; spacing as
`--space-N` vs `--sp-N` vs `--sp-xs`). europe-county-map and iron-and-anvil
have **zero** custom properties.
2. `RangeSlider` — canonical is dufs-cloud's, whose pure
`fractionFromPointer(rect, clientX)` is testable without layout (jsdom has
none). awesome-mcp-explorer's copy has drifted 196 lines.
3. `FilterBar` + `filter-sort.ts` — reconcile dufs-cloud (174) vs
awesome-mcp-explorer (225).
**Consumption mechanism (decided 2026-08-14):** a git dep
`"@kuhyx/web-ui": "github:kuhyx/utils#web_ui-v0.1.0"`, matching the Dart/Python
tag convention rather than introducing npm workspaces — but shipping a
**prebuilt `dist/`** (tsc → ESM + `.d.ts`) committed in the tag. Raw `.tsx` in
`node_modules` would need per-repo bundler config, since Vite does not
transpile dependencies by default; a committed `dist/` keeps consumers at zero
config.
Proof consumers: `dufs-cloud` and `awesome-mcp-explorer`.
## Standing risks

View File

@ -1,95 +0,0 @@
# Pointer-free + small-screen: per-stack patterns
Split out of [`README.md`](README.md), which covers the palette and the
per-stack *theming* pattern. This file is the other half: how to satisfy the
operability requirements in [`operability.md`](operability.md) in Flutter, on
the web, and in Python/Tkinter.
The rules themselves are in [`tokens.md`](tokens.md) (*Pointer-free
operability*, *Screen size*). This is how to implement them per stack. Both are
machine-checked — a static lint in pre-commit plus a render test in each repo's
suite — so treat these as the shape the checks expect.
### Flutter
```dart
// Reach: never a bare GestureDetector for an action.
InkWell(onTap: select, child: cell) // focusable + Enter/Space
// A destructive action needs a focusable control, not just onLongPress:
IconButton(icon: Icon(Icons.delete), onPressed: confirmDelete)
// App-level accelerators. On the Chrome --app desktop surface, avoid chords
// Chrome reserves (Ctrl+N/T/W/Shift+N) — they never reach Flutter.
Shortcuts(shortcuts: {
SingleActivator(LogicalKeyboardKey.keyS, control: true): SaveIntent(),
SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
}, child: Actions(actions: {...}, child: child));
// Size: budget height, clamp width.
final short = MediaQuery.sizeOf(context).height < 700; // 768 minus chrome
ConstrainedBox(constraints: BoxConstraints(maxWidth: kProseMaxWidth), child: prose);
```
Any screen whose content can grow needs a `SingleChildScrollView`/`ListView` —
a `Column` with one `Expanded` child does not scroll, it just collapses the
flexible child until it is unusable. Bottom sheets need `isScrollControlled:
true` plus an inner scroll view.
Note on **Flutter web** (todo-app and diet-guard's desktop surface are the web
build in a Chrome `--app` window, not the Linux embedder): the semantics tree is
not built unless assistive tech is detected, so `Semantics` is not a substitute
for real focusability — use focusable widgets, and treat `Semantics` as
additive.
### Web
`:focus-visible` must be styled everywhere, and never removed:
```css
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
/* Never `outline: none` without an equally visible replacement. */
```
Verify at the required viewports with no horizontal scroll and no *inner*
scrollbar: `1366x768` and `1024x600` at minimum. Prefer a compact baseline that
grows, over a desktop layout that must shrink.
### Python/Tkinter
Font sizes are **negative** (see `tokens.md` — positive means points and
inflates everything ~37%). The focus ring and both scales live on
`gatelock.LockConfig` so all four lockers inherit them:
```python
# focused ring — NOT highlightbackground, which is the *unfocused* ring
widget.configure(highlightcolor=cfg.focus_ring, highlightthickness=2)
widget.configure(font=(cfg.font_family, -cfg.type_body)) # negative == pixels
```
Tk specifics that are easy to get wrong, all verified against Tk 8.6's own
class bindings:
- `tk.Button` binds `<space>` on X11 but **not** `<Return>`; `Entry`/`Spinbox`
bind `<Return>` to nothing. Bind `<Return>` yourself for submit.
- `tk.Text` traps `<Tab>` (inserts a literal tab, refocuses itself) and makes
`<Shift-Tab>` a no-op. Rebind both to move focus, or the box is a dead end.
- `tk.Canvas` has no class key bindings, so a Canvas scroll viewport is not even
a focus stop. Bind `<Prior>`/`<Next>`/arrows, **and** add a `<FocusIn>` handler
on children that scrolls the focused child into view — clipping does not
unmap children, so focus walks into invisible fields by default.
- `OptionMenu`/`Menubutton` default to `takefocus=0`. On lock surfaces they are
banned anyway (a posted menu steals the grab); use radio buttons.
- `ttk.Notebook` needs an explicit `enable_traversal()` for `Ctrl+Tab` /
`Ctrl+PageDown` / `Alt`+mnemonic.
- Verify the focus ring by *walking* it (`tk_focusNext`), not by reading code.
Measure the height rather than eyeballing it — this is how the meal-gate
overflow was found, and it is what the render half of the gate does:
```bash
xvfb-run -s "-screen 0 1366x768x24" python3 -m your_pkg.tests.measure_layout
# assert frame.winfo_reqheight() <= available_pane_height
```
Measure both empty **and** fully populated (a day of meals logged, history rows
present) — the empty case is not the worst case.

View File

@ -1,69 +0,0 @@
# Pointer-free operability and screen size (required)
Split out of [`tokens.md`](tokens.md), which freezes the palette and the
scales. These are the *behavioural* requirements that use those tokens — a
token file should be readable as a table of values, and these are rules with
reasons attached.
Per-stack implementations of everything here are in
[`README.md`](README.md#pointer-free--small-screen-per-stack-patterns).
## Pointer-free operability (required)
**Every action must be reachable and activatable with the keyboard alone.** No
mouse, no touchpad, no touch. This is not an accessibility nicety here: several
of these apps are *lockers* that hold a global input grab with VT switching
disabled, so a control only a pointer can reach is not an inconvenience — it is
a bricked machine.
Six things must hold on every surface:
1. **No pointer-only handler.** Any `onTap`/`onLongPress`/`<Button-1>`/click
handler needs a keyboard-reachable equivalent on the same action. A bare
`GestureDetector` and an `onLongPress`-only destructive action are both
defects. Long-press in particular has *no* keyboard analogue — never make it
the only path to an action.
2. **Everything interactive is a focus stop.** Widgets that opt out of the focus
ring (`takefocus=0`, which Tk's `Menubutton`/`OptionMenu` default to) are
unreachable. Verify by walking the real ring, not by reading the code.
3. **Focus is visible.** See the focus-ring token below — the platform default
is a black ring, which vanishes on `ink`.
4. **Focus never lands somewhere invisible.** If a container scrolls, focus
entering a clipped child must scroll it into view. Clipping does not remove a
widget from the focus ring, so this is the default failure, not an edge case.
5. **Scrolling is keyboard-driven.** A scroll container needs `PageUp`/`PageDown`
and arrow keys, not just a draggable thumb and a wheel.
6. **Confirm/submit and cancel/back have accelerators.** `Enter` submits, `Escape`
cancels. On Tk, note `Enter` does **not** activate a `tk.Button` on X11 (only
`Space` does) and is bound to nothing on `Entry`/`Spinbox` — you must bind it.
### The focus-ring token
`focus-ring` is `#B8862E` (= `accent`), 2px at 1px offset. It is defined in
[`tokens.md`](tokens.md#focus-ring) with the rest of the palette, because
`scripts/palette_check.py` parses that file — a token it cannot see is a token
nothing compares across the four stacks.
Platform defaults are wrong on this palette: Tk ships
`highlightcolor="#000000"` with `highlightthickness=1`, i.e. a black ring on
`ink` (`#211D1B`) — invisible. Set `focus-ring` explicitly. Never
`highlightthickness=0` on something focusable.
⚠️ On Tk, `highlightbackground` is the **unfocused** ring and `highlightcolor`
is the **focused** one. Setting only `highlightbackground` inverts the
affordance — the widget outlines when it is *not* focused and goes black when
it *is*. Set `highlightcolor`.
### Escape hatches vs. deliberate gating
Some apps intentionally resist dismissal (an alarm you must solve a challenge to
silence, a meal gate you must log a meal to clear). That gating is a feature and
this rule does not override it. What the rule requires is that the *sanctioned*
paths — solve the challenge, use the budgeted escape hatch, submit the form — are
fully keyboard-operable. Making a gate keyboard-reachable is not weakening it.
## Screen size (required)
Moved to `screen-size.md` (250-line cap): the 1366x768 / 1024x600 targets, the
height-budgeting rules, and why centring unscrollable content clips
symmetrically. Still part of this spec — read it for any layout work.

View File

@ -1,122 +0,0 @@
# Shipped record: palette drift, Phase 2, Phase 3
Companion to [`nielsen-audit.md`](nielsen-audit.md), which is the live audit
grid and the list of what is still open. This file is the history: work that
is **done**, kept because the *decisions* in it are load-bearing — the two
deliberate exceptions below exist so nobody "fixes" them back, and the
corrections found by measuring are why the current plan differs from the
original one.
Same convention as [`phase3-record.md`](phase3-record.md), which records the
web phase in the same way.
### Flutter — palette drift: DONE 2026-08-14
Standing decision: every app uses **exactly** the frozen palette; where copies
disagree, the most popular wins. That was unambiguous — 9 of 10 theme files
already used the gold `#B8862E` family. All four drifted repos are migrated.
| Repo | Drift that was fixed | How |
|---|---|---|
| `testsAndMisc/focus_owner` | **entirely off-palette**: cool `#5B9DD9` accent, `#1B1D21` field, `#D9776B` danger. Its doc comment claimed it matched the other `com.kuhy.*` apps; it did not. The same six constants were also **duplicated verbatim** in `main.dart:16-21` — the file said they had been "lifted out", but the originals were never deleted. | `theme.dart` now aliases `AppPalette`, so the ~80 call sites keep their names; both copies gone. Literals 15 → 2 (`Colors.transparent`). Verified on the Pixel 6a. |
| `kuhylog` | the only repo using `ColorScheme.fromSeed` (blue `#3B82F6`) — the opposite of what every other theme file documents. | `KuhylogTheme.of()` delegates to `buildLightTheme`/`buildDarkTheme`. Kept as a wrapper for its `visualDensity`, flat `cardTheme` and `scoreColor`. Literals 1 → 0. |
| `epopeja_karta` | `ColorScheme` inlined in `app.dart`, no `theme.dart`. | Imports **tokens only** — see below. Literals 9 → 0. |
| `billsplit` | `ColorScheme.fromSeed(Colors.teal)` plus 15 ad hoc literals that mostly bypassed the theme entirely. | `buildLightTheme()`; error family → `error`/`onError`/`errorContainer`, muted text → `onSurfaceVariant`. Literals 15 → 4. |
| `diet-guard`, `macro-cam` | scales drifted from the six-repo consensus | **still outstanding** — adopt `design_system` |
Two deliberate exceptions, so nobody "fixes" them back:
- **`epopeja_karta` adopts `AppPalette`, not `buildDarkTheme()`.** Its nine
slots were already byte-identical to the frozen palette, so only the
transcription was local. It is one dense screen with a test asserting
nothing scrolls, and the shared theme's larger type scale plus
`dividerTheme.space` overflows it by 34px. Typography there is a product
decision; colour is the identity, and colour is what the system owns.
Importing tokens leaves the rendered `ThemeData` identical, so the no-scroll
test passes by construction rather than by hitting a pixel target.
- **`billsplit` keeps its four category-dot colours** (`deepOrange`/`amber`/
`blueGrey`/`teal` for alcohol/mixer/deposit/other). They encode *category
identity*, not a theme role, and a single-accent system has no four distinct
hues to lend. Folding them into `primary`/`secondary`/`tertiary` would make
the categories stop being distinguishable, which is their only job. **This
is the open categorical-ramp question** — the design system currently has no
answer for "N mutually distinguishable hues", and it needs one before any
chart, tag or category UI can be built on it.
### Remaining Flutter adopters
`home_inventory`, `dufs-cloud`, `habit_stack`, `diet-guard`, `macro-cam`,
`wake-alarm/phone_app`. Each drops its local `theme.dart` for the tag-pinned
dep, as todo, untools, focus_owner, kuhylog, epopeja_karta and billsplit now
do. These six were never off-palette — they transcribe the right values by
hand — so this is duplication cleanup, not a visual fix.
### Phase 2 — Python/Tk (`~/utils/gatelock`), SHIPPED (gatelock 0.5.0)
> **Status: done.** `make_button`, `heading`/`row`, `ScrollableSurface` and
> `WidgetGroup` all ship in gatelock 0.5.0 (`c963cd8`, `d82107a`, `d25f288`);
> diet-guard and leetcode-guard are the migrated proof consumers.
> screen-locker (v0.4.0) and wake-alarm (v0.4.1) keep local fan-out copies
> **by design** — only two consumers were bumped to avoid restarting live
> systemd services. That asymmetry is not a regression; do not "fix" it.
> Everything below this line is the original plan, kept as the record of why.
Not a new package: gatelock already owns the tokens (`LockConfig`), the Tk
plumbing and 4 consumers. Add composite widgets, which is where its scope
currently stops.
1. `widgets.py::make_button` — canonical is diet-guard's
`_gatelock_buttons.py::make_button`, whose `variant` API picks text color
*from* the fill and so structurally prevents the `fg`-vs-`on_fill` contrast
bug. leetcode-guard's `_button` (no `<Return>` binding) and screen-locker's
inline `tk.Button` are the regressions being retired.
2. `widgets.py::heading()` / `row()` — from `leetcode_guard/_status_sections.py`.
3. **Export the existing `ScrollableSurface`** and delete
`leetcode_guard/status_view.py::_scrollable`, a hand-rolled reimplementation
that lost `takefocus` and the focus ring. Straight accessibility repair.
4. `widget_group.py::WidgetGroup` — the per-output fan-out reimplemented 4×
(~916 lines: screen-locker 173, leetcode-guard 105, diet-guard 309,
wake-alarm 329). Highest line-count win on this stack.
Proof consumers: `diet-guard` and `leetcode-guard` (donor and worst offender).
Bump **only those two**; leave screen-locker and wake-alarm on their current
pin — Phase 2 is additive, and restarting live services is blast radius for no
gain.
> **Verification gate — non-negotiable.** gatelock backs live systemd
> services. After any change: `/usr/bin/python3 -c "import gatelock"` against
> the real interpreter, not a dev venv. Do not touch the gate window's grab
> path. Then launch each gate under `xvfb-run -s "-screen 0 1366x768x24"` and
> confirm buttons render and **`<Return>` activates** them.
### Phase 3 — TypeScript (`~/utils/web_ui`), SHIPPED (web_ui-v0.3.1)
> **Status: done** — see `phase3-record.md` for what shipped and, importantly,
> why `FilterBar` was *not* extracted (a name collision, not a duplicate).
> Both proof consumers (dufs-cloud, awesome-mcp-explorer) are migrated.
> Everything below this line is the original plan, kept as the record of why.
Lowest confirmed duplication (2 components, 2 repos) and the only stack needing
a brand-new consumption mechanism, so it carries the worst effort-to-payoff
ratio — sequenced last on purpose.
1. `tokens.css` — one `:root` block. Fixes the worst fork found: **7 repos
define 7 different vocabularies for the same palette** (`--surface-1` vs
`--panel` vs `--card`; `--text` vs `--ink` vs `--fg` vs `--bone`; spacing as
`--space-N` vs `--sp-N` vs `--sp-xs`). europe-county-map and iron-and-anvil
have **zero** custom properties.
2. `RangeSlider` — canonical is dufs-cloud's, whose pure
`fractionFromPointer(rect, clientX)` is testable without layout (jsdom has
none). awesome-mcp-explorer's copy has drifted 196 lines.
3. `FilterBar` + `filter-sort.ts` — reconcile dufs-cloud (174) vs
awesome-mcp-explorer (225).
**Consumption mechanism (decided 2026-08-14):** a git dep
`"@kuhyx/web-ui": "github:kuhyx/utils#web_ui-v0.1.0"`, matching the Dart/Python
tag convention rather than introducing npm workspaces — but shipping a
**prebuilt `dist/`** (tsc → ESM + `.d.ts`) committed in the tag. Raw `.tsx` in
`node_modules` would need per-repo bundler config, since Vite does not
transpile dependencies by default; a committed `dist/` keeps consumers at zero
config.
Proof consumers: `dufs-cloud` and `awesome-mcp-explorer`.

View File

@ -93,24 +93,23 @@ the signal. A categorical ramp has no meaning to lean on, so hue separation *is*
the requirement. Treating this as drift and "correcting" it back toward the
wedge would destroy the only property it has.
Chosen by search under four hard constraints, not by eye: pairwise CIE ΔE ≥ 20
under normal vision *and* simulated deuteranopia/protanopia/tritanopia, ≥ 3:1
against **both** backgrounds, monotonically decreasing lightness, and muted
saturation.
Chosen by search under four hard constraints, not by eye
(`unified-design-system/scripts/ramp_check.py` re-runs the proof):
**Do not copy the measured margins into this file.** Run the check — it prints
every one of them and fails if any regresses:
```
python3 unified-design-system/scripts/ramp_check.py
```
Two consequences worth keeping in prose, because the numbers alone do not say
them. The both-backgrounds rule is the binding constraint: colours legible on
a near-black *and* a near-white field only exist around L\* 44–59, which is why
the ramp is mid-toned rather than spanning light to dark. And because lightness
falls monotonically, hue and lightness encode redundantly, so `cat-1…6` still
reads as an ordinal scale in greyscale or under severe CVD.
1. **Pairwise CIE ΔE ≥ 20** between every pair — measured under normal vision
*and* simulated deuteranopia, protanopia and tritanopia. Worst observed: 34.6
normal, 26.0 deuteranopia, 25.6 protanopia, 27.4 tritanopia.
2. **≥ 3:1 contrast against both backgrounds** (`ink` and `paper`), since the
ramp is theme-independent — it does not flip with `prefers-color-scheme`.
This is the binding constraint: colours legible on both a near-black and a
near-white field only exist in L\* ≈ 44–59, which is why the ramp is
mid-toned throughout rather than spanning light to dark.
3. **Monotonically decreasing lightness** (58 → 44), so hue and lightness encode
redundantly. The ramp therefore still reads as an ordinal scale in greyscale
or under severe CVD, which is what lets `cat-1…6` carry an ordered scale
(grades A→F) as well as an unordered one.
4. **Muted saturation**, to sit with the rest of the palette rather than
vibrating against it.
Use them **in order** for ordered data, and *by position* for unordered data —
never pick "the green one" because green means good, which is the semantic
@ -201,19 +200,61 @@ at the same z-level.
Icons adjacent to text render at ~72% opacity of the text's color, or use the
`muted` role instead of the full-strength text role — never equal contrast.
## Focus ring
## Pointer-free operability (required)
**Every action must be reachable and activatable with the keyboard alone.** No
mouse, no touchpad, no touch. This is not an accessibility nicety here: several
of these apps are *lockers* that hold a global input grab with VT switching
disabled, so a control only a pointer can reach is not an inconvenience — it is
a bricked machine.
Six things must hold on every surface:
1. **No pointer-only handler.** Any `onTap`/`onLongPress`/`<Button-1>`/click
handler needs a keyboard-reachable equivalent on the same action. A bare
`GestureDetector` and an `onLongPress`-only destructive action are both
defects. Long-press in particular has *no* keyboard analogue — never make it
the only path to an action.
2. **Everything interactive is a focus stop.** Widgets that opt out of the focus
ring (`takefocus=0`, which Tk's `Menubutton`/`OptionMenu` default to) are
unreachable. Verify by walking the real ring, not by reading the code.
3. **Focus is visible.** See the focus-ring token below — the platform default
is a black ring, which vanishes on `ink`.
4. **Focus never lands somewhere invisible.** If a container scrolls, focus
entering a clipped child must scroll it into view. Clipping does not remove a
widget from the focus ring, so this is the default failure, not an edge case.
5. **Scrolling is keyboard-driven.** A scroll container needs `PageUp`/`PageDown`
and arrow keys, not just a draggable thumb and a wheel.
6. **Confirm/submit and cancel/back have accelerators.** `Enter` submits, `Escape`
cancels. On Tk, note `Enter` does **not** activate a `tk.Button` on X11 (only
`Space` does) and is bound to nothing on `Entry`/`Spinbox` — you must bind it.
### The focus-ring token
| Token | Value | Notes |
| ------------ | ---------- | -------------------------------------------- |
| `focus-ring` | `#B8862E` (= `accent`) | 2px, offset 1px. |
Why the platform default is not good enough, and the Tk
`highlightcolor`/`highlightbackground` trap, are in
[`operability.md`](operability.md#the-focus-ring-token).
Platform defaults are wrong on this palette: Tk ships
`highlightcolor="#000000"` with `highlightthickness=1`, i.e. a black ring on
`ink` (`#211D1B`) — invisible. Set `focus-ring` explicitly. Never
`highlightthickness=0` on something focusable.
## Operability and screen size
⚠️ On Tk, `highlightbackground` is the **unfocused** ring and `highlightcolor`
is the **focused** one. Setting only `highlightbackground` inverts the
affordance — the widget outlines when it is *not* focused and goes black when it
*is*. Set `highlightcolor`.
Keyboard-only reachability and the small-screen budget are requirements, not
suggestions: several of these apps are lockers that hold a global input grab,
so a control only a pointer can reach is a bricked machine. Both, plus the
`focus-ring` token, are in [`operability.md`](operability.md).
### Escape hatches vs. deliberate gating
Some apps intentionally resist dismissal (an alarm you must solve a challenge to
silence, a meal gate you must log a meal to clear). That gating is a feature and
this rule does not override it. What the rule requires is that the *sanctioned*
paths — solve the challenge, use the budgeted escape hatch, submit the form — are
fully keyboard-operable. Making a gate keyboard-reachable is not weakening it.
## Screen size (required)
Moved to `screen-size.md` (250-line cap): the 1366x768 / 1024x600 targets, the
height-budgeting rules, and why centring unscrollable content clips
symmetrically. Still part of this spec — read it for any layout work.