Compare commits

...

111 Commits
v1.0.5 ... main

Author SHA1 Message Date
7153630a2e Audit icons: add 1-word hover tooltips
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Todo: fe70b845
2026-11-22 18:30:40 +01:00
f20e2ab16f Put my logo everywhere
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Todo: 7808ee0a
2026-11-21 10:06:22 +01:00
a96babd8f8 Bump Flutter to 3.50.1
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:38:50 +01:00
5d83ff561e deploy.sh pulls and runs from ~/src/todo
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Revert the AGENTS.md deploy line: kuhy has an uncommitted edit there,
so changing the file blocked the pull. deploy.sh itself now redirects a
worktree run to the main checkout, past phone_deploy's exit-49 guard.

Todo: 2556952d

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:50:20 +01:00
d5764fce7b Deploy from main checkout, not the worktree
phone_deploy refuses a production install from a worktree (exit 49),
so the board's deploy of this repo always failed on the phone target.

Todo: 2556952d

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:48:03 +01:00
660d82282c get rid of github ci/cd version check of package…
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Todo: 2556952d
2026-11-19 18:11:08 +01:00
300d50ab11 chore: enable dart-flutter plugin
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-19 17:59:25 +01:00
ea216d4a59 Sync pulls peers at once, off the UI thread
Some checks failed
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
The board reported a 3.9 s sync.run spinner on the Pixel (todo:0c575b891b).
Eight ~2 MB peer logs were fetched, parsed on the UI isolate and merged one
by one, each merge rewriting the whole local store; a device without a
GitHub token still mirrored to GitHub (404s); settings and analytics waited
for the note sync.

Now changed peers download together, logs over 64 KB parse on an isolate
(inline on web), peers merge into one local write, the revision map and
listing share a round trip, the mirror is skipped without a token, and
settings/analytics run alongside the notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 11:25:22 +01:00
fafefabab6 MCP reads reuse a sync done within 2 s
A board fetch makes 15 MCP calls and each one synced with Firebase
(0.5-1 s), so a fetch took 12 s. Reads skip the sync when one ended
within readFreshness; writes always pull and push.

Todo: 475dc1d1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXu5EV5tPkCTEu6nxf
2026-11-19 11:17:50 +01:00
5acd9d4863 Bump flutter, gradle, sync pins; probe retries
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
crdt_sync_flutter 0.9.1, sync_settings_ui 0.8.4 (data_transfer_flutter
0.2.3 lifts the file_picker 13.3.3 hold, so 13.4.0 and the exception go),
Flutter 3.50.0 (.fvmrc + release-apk.yml), Gradle 9.9.1.

LinuxSystemProbe.processCmdlines retried nothing when a pid exited between
readdir and Dart's lstat of it, failing the whole listing (seen in the
suite). It now relists up to three times.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 11:07:19 +01:00
9d2a5a0bd3 list_tasks no_repo lists repo-less notes
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The board reads open notes through list_tasks, which hides notes
without a repo, so kuhy's ideas never reached it.

Todo: 475dc1d1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXu5EV5tPkCTEu6nxf
2026-11-19 10:53:18 +01:00
3a747c2e51 Report errors and slow waits to the board
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
crdt_sync_flutter 0.9.0's installAppErrors in main(): uncaught errors and
every spinner shown over 1 s (WaitWatch: sync.run, mirror.test) upload to
RTDB /todo/errors/<device> with the versionCode, where the PC app-errors
ingest files board tickets (kuhyx/utils DOCS-app-errors.md).

The app moves to material_ui first: sync_settings_ui 0.8.x and
design_system 0.4.x sit on it, and Flutter 3.50 deprecates
flutter/material. Pins: crdt_sync 0.14.1, csf 0.9.0, ssui 0.8.3,
gda 0.5.1, design_system 0.4.1, image 4.13.1, mcp_dart 2.4.4.
file_picker stays 13.3.3, held by data_transfer_flutter 0.2.2
(allowlisted, self-clearing).

appRoute takes a route name so each report names its screen; the
release build passes APP_BUILD/APP_VERSION. Nothing new on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:07:58 +01:00
1f7c31357b Point at android_ui for phone UI driving
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Tap and type by label via ~/src/testsAndMisc's android_ui CLI or its MCP server, instead of coordinates. No code copied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:46:39 +01:00
b350b3e8c1 Tidy MCP deadline guard for analyzer
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Guard moves to request_guard.dart (file-length gate); README notes
the token reload, deadline and timeouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:06:05 +01:00
e885465f55 todo-mcp unit raises LimitNOFILE to 65536
The 1024 soft limit was exhausted in the 2026-11-16 outage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:04:41 +01:00
be6bf6fc48 MCP closes requests that outlive a deadline
Dart's HttpServer never notices a client that hung up on a request
still in flight, so abandoned calls held their sockets (1010 in
CLOSE-WAIT, fd limit hit). POST/DELETE open past 90 s now get 503 and
close; the library's server is private, so idleTimeout stays default.
A zone guard keeps late write errors from killing the process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:04:40 +01:00
b2ffc346c3 Bound every Firebase and token HTTP call
package:http has no timeout; a dead connection wedged sync forever.
CliSession now wraps its client: 30 s to headers, 30 s per body chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:01:50 +01:00
0ce9c42ff6 MCP tokens load once, keep last good set
A read error no longer clears the accepted tokens; with no good
load the answer is 503, not 403. A request costs one stat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 07:59:31 +01:00
de5ad7d2dd MCP calls time out instead of wedging
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
A sync stuck on a dead connection held the one-at-a-time queue forever. Abandoned board polls piled up as CLOSE-WAIT sockets until the process hit its fd limit, the tokens file could no longer be opened, and a valid token read as HTTP 403.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 07:50:43 +01:00
cd50fd0ae2 Wrapper imports the passphrase path, not Flutter
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dart build cli failed: wrapper_server pulled crdt_sync_flutter (dart:ui)
through e2e_passphrase_source. The path const moves to a dart-only file.

Todo: 656f0d08
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-15 21:28:19 +01:00
19f930a93a CLI caches the E2E key (0600)
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Argon2id ran on every CLI/MCP call; the derived key is now cached
owner-only in the data dir.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:59:34 +01:00
f7e24bbb1a Desktop adopts the E2E passphrase once
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The wrapper serves ~/.config/crdt-sync/password once on
/sync-e2e-passphrase; the web app stores it in its keystore, so desktop
todo never asks. Android still unlocks via the lock tile.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:56:07 +01:00
4423937f5c E2E: key cache, CLI password, lock tile
Argon2id runs once per device (keystore key cache); the CLI/MCP read
~/.config/crdt-sync/password; pull-only merges old and encrypted
prefixes; the settings lock tile follows the last sync and resyncs on
save. Pins crdt_sync 0.14.0, crdt_sync_flutter 0.8.0, sync_settings_ui
0.7.2.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:52:15 +01:00
f4913daaa8 E2E-encrypt todo sync
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Todo: fda71ed1

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:39:05 +01:00
c9eb4d6cff Bump sqflite_common_ffi to 2.4.7
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:17:09 +01:00
1010d96426 deploy.sh: wait out phone_deploy load guard
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:57:08 +01:00
319f18d33a deploy.sh: one phone lease owner per run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:53:55 +01:00
c3ac6ec05d deploy.sh: SDK env and release key for phone
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Ship and systemd units skip ~/.zshenv, so default ANDROID_HOME, and
copy the shared key.properties into a fresh checkout so the release
build installs over CI builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:47:43 +01:00
0e56cddd47 Add scripts/deploy.sh and the deploy command
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Deploys the MCP service, the desktop pacman package and the phone
release build, each behind its own health check; exits non-zero unless
all pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:15:23 +01:00
203e61d6ac Text-free sync settings via ssui 0.7.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Bump sync_settings_ui 0.7.0 and github_device_auth 0.4.0 (glyph +
spoken label). Guard covers the Sync settings screen; degraded sync
gets its own warning glyph; tooltip delegate and copy button tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:32:02 +01:00
edf6969949 Template picker: glyph prefix, not float label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:22:22 +01:00
5ea7ba7b73 Text-free list, editor, sync and image cues
Glyph + spoken label replaces every app-written string the guard
found: empty states, tile meta, sheet dates/fields, date presets,
template/section headings, status footer, snackbars, GitHub and
cloud-image results, upload/download badges, Material tooltips.
Guard tests (text_free_*_test) walk the painted tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:17:03 +01:00
091e68a2d9 Text-free UI: glyph chips, icon-only actions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 01:02:25 +01:00
a30e7b34a9 CLI: --set-text replaces a note's text
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Keeps every other field; text from --text or stdin, empty refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:56:23 +01:00
17d6d2a533 Bump file_picker, idb_shim, sqflite_common_ffi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:56:22 +01:00
4e8ccd6bfd Lean gradle.properties for warm daemon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZUTC9Zzdzsx7VW7dm
2026-11-10 17:51:44 +01:00
6bd2923f0a Instant page routes; coalesce watch re-emits
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXdsB7CQPNXVN829G1
2026-11-10 15:57:03 +01:00
4c77dd5d2e Bulk update: diff generated fields only
planBulkUpdate compared fresh field values with the stored text, so a
peer's "...00Z" created_at (or a web build's millisecond date) read as a
change and got a fresh clock, erasing the created_by node signal; a
record without a priority field got one written. Compare the note's own
generated fields before and after instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXdsB7CQPNXVN829G1
2026-11-10 15:41:35 +01:00
757c54beda Multi-select notes with an icon action bar
An app-bar toggle enters selection mode: a tap toggles a note (tint +
check on grid tiles, ListTile.selected + check in the list), Ctrl/Cmd-
click toggles and Shift-click range-selects on desktop, long-press
outside the mode still opens the per-note sheet. While anything is
selected an icon-only bottom bar sets status or priority for the whole
selection in one bulkUpdate, assigns plain notes to a repo picked from
the repos on notes or typed as owner/name, or clears the selection. A
refused assign (note already in a repo) flashes a block icon. Labels
are semantic only; menus pass an empty tooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXdsB7CQPNXVN829G1
2026-11-10 15:39:13 +01:00
5c1bf75bf9 Bulk note writes and assign-to-repo helper
NoteRepository.bulkUpdate sets status/priority on many notes in one
store write (mergeLogs + replaceAll; only changed fields plus updated_at
get a clock). saveReplacing saves one note and tombstones others in one
write. assignToRepo moves plain notes into the repo's open note as
"## title" sections via addRepoTask, demoting body headings below "##"
so a template note stays one section; notes already in a repo are
refused. The seeded watch stream moved to log_watch.dart for the
250-line cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXdsB7CQPNXVN829G1
2026-11-10 15:38:54 +01:00
57019eec30 Track who filed a note (created_by)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
New optional note field created_by (kuhy|claude), stored like by/repo and
omitted when unset so older builds stay wire-compatible. App UI stamps kuhy;
MCP add_task and the CLI stamp claude. list/get/search output includes it.
Human notes sort above Claude's; Claude notes are hidden behind a per-device
eye toggle. CLI --backfill-created-by [--dry-run] classifies old notes by the
node that wrote created_at, writing only the created_by field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:18:19 +01:00
cc9789f530 Start exactly the merged item
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The board orders cards by column, so a cancelled older item with the
same title could be listed last and was started instead of the item
the merge added (T1866). Start now targets <id8>-<sections - 1> only.

Todo: 64d39ab5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:28:17 +01:00
135f3f07ea Start a merged task outside the MCP lock
The board refreshes its notes through this MCP server, and add_task
held the server's serial lock while waiting for the board to show
the merged section, so the board could never see it (T1865). The
Start now runs after the lock is released.

Todo: 64d39ab5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:24:24 +01:00
ba25e8f176 Wait for the board before a merged Start
The board's note cache lags ~10 s after a merge, so Start found
"no startable item" (T1863); it now waits up to 30 s for the merged
section's card. A Start POST slower than its timeout that did take
effect was reported "board unreachable" (T1864); it now re-reads the
board and reports ok when the card left Start.

Todo: 64d39ab5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:18:30 +01:00
beb1d1a49f crdt_sync 0.12.1: serialized FileLogPersistence writes
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:29:03 +01:00
75248e9cde Add new_note to add_task with merge and start
new_note files a separate note per repo; an exact section-title
match in another open note merges into it and starts it via the
board, unless that note is running, none or low priority.

Todo: 64d39ab5

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:24:41 +01:00
9a8e7aefd2 Fix flaky image_store_io_test "without picker cop…
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Todo: 2961b5ff
2026-11-09 08:37:03 +01:00
75788c7bdb Bump Gradle wrapper to 9.9.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYDm7szKeXoi7rinEy
2026-11-09 08:22:15 +01:00
1baaf236d4 Bump design_system to 0.3.1
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 18:32:58 +01:00
dc96bff3df Bump crdt_sync, sync_settings_ui, deps
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 18:11:53 +01:00
b92d133c17 Add todo app git hooks
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 14:28:08 +01:00
a0c1938d8d Split notes on first non-blank line
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 14:14:16 +01:00
cbe3d9be59 One open note per repo, merge tool
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 14:11:21 +01:00
67212cd7ec One list: repo groups, repo search, compact filter
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 13:40:20 +01:00
9b42ff8ba2 Bump crdt_sync_dart, sync_settings_ui
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
crdt_sync_dart 0.11.3, sync_settings_ui 0.5.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 12:15:11 +01:00
dc547763fc Bump Flutter to 3.47.9, Gradle to 9.8.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 12:01:25 +01:00
4a30a52375 Move TODOs to todo app
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ24SUudEMNQAxdYb8
2026-11-02 11:20:34 +01:00
860d789864 Use google_account_token plugin
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Replace the app-local AccountManager channel with the shared plugin
(google_account_token-v0.1.0); kServerClientId stays put.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 11:15:28 +01:00
d09978a338 Add one-command MCP go-live + live verify
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVUTaKFW8m7YrvWbzV
2026-11-02 10:45:45 +01:00
cf01784241 TODO: flaky image_store_io attach test
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 10:28:26 +01:00
0ff3d6f95d Sign in via AccountManager, drop google_sign_in
System account chooser plus getAuthToken with an
audience:server:client_id token; no Google client library.
Pins bumped to newest stable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 10:24:59 +01:00
d14b7e03e3 install_hooks: resolve hooks dir via common git dir
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 10:24:59 +01:00
2a9332094a MCP: Dart task server replaces Python todo_mcp
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 09:36:44 +01:00
9e18821c7b Remove TODO-fit-to-screen-layout.md: implemented by the notes grid
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 09:28:27 +01:00
f7ea0ffb3d Notes list: 2-column tile grid on phones, whole rows fill the screen
Below 600dp the notes list is a compact tile grid (title + priority/status
cues). Tile height is derived so whole rows exactly fill the viewport between
the status and navigation bars; past a screenful it scrolls vertically (no
paging). Body and dates moved into the long-press sheet. Wider windows keep
the list. Not using design_system FitGrid: it is square-celled and pages
horizontally.

Pins: design_system v0.3.0 (newest tag); also bumped crdt_sync_dart 0.11.2,
sync_settings_ui 0.4.2, file_picker 13.3.1, idb_shim 2.11.1,
sqflite_common_ffi 2.4.5, web 1.1.2 because the freshness gate was already
red on them at HEAD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:28:18 +01:00
2ffae26f93 Capture feedback: haptic + checkmark on commit, motion tokens for routes and wizard bar
- Committing a captured note (New note tap with a persisted draft) fires
  HapticFeedback.lightImpact and plays a ~600 ms checkmark beside the counter;
  empty drafts and keystrokes confirm nothing.
- appRoute: one shared page route (fade + rise, AppDuration.slow) replaces all
  seven MaterialPageRoute sites; guard test keeps it that way.
- Wizard progress bar animates on AppDuration.base / AppCurve.standard.
- Everything honours disableAnimations; the haptic and the (static) checkmark
  still fire. Removes the finished dopamine-ux prompt (sound step rejected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:28:13 +01:00
377ec17356 Design audit closed: 6px gaps → 8 on the 4/8 grid; track fit-to-screen TODO
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Filter-sheet tests now scroll Apply into view (tapApply): the sheet is
scrollable and Apply legitimately sits below the fold on a 600px viewport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:18:40 +01:00
9349747629 Repo tasks: repo/done_check/by/evidence fields, filter chips, CLI close/list/search
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Four optional note fields (repo, done_check, by, evidence) in the crdt_sync
record, written only when set, so editing a plain idea stays wire-identical
to v3 (note_repository_sync_compat_test). The log is schemaless: no stored
schema version; the legacy sqlite reader stays at v3.

NoteFilter gains a sources facet (ideas / every repo task / one repo);
search also matches the repo. The notes list shows only open ideas by
default (no badge); the filter sheet adds Ideas, Repo tasks and one chip
per repo when repo tasks exist. The per-note sheet shows the task fields
read-only. BACKLOG.md markers carry the new attributes, entity-escaped.

CLI: --repo --done-check --by on add, --close <id> --evidence (refused
without), --list [--repo] [--status], --search, and every id flag takes a
unique 8-character prefix. --list prints id8, status, priority, repo, title.

install_hooks.sh: the wrapper finds pre-commit's generated hook next to
itself, so commits from a git worktree (where .git is a file) work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 08:26:26 +01:00
64bce89d87 Launcher: label Todo (Android, desktop entry, PKGBUILD), icon fitted to the shared 340px ink circle
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012kQ5PCKqBHAkAVkPSvp6dk
2026-10-23 14:38:14 +02:00
c71b98c08b Desktop: no stray browser window from extensions; keyboard stays down after backing out of a note
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 12:00:26 +02:00
341a943277 CLI: --set-status <id> <status> re-statuses a note and pushes
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 17:22:58 +02:00
41947463c5 Bump flutter 3.47.7, gradle 9.8.1, pub deps to latest
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 15:41:06 +02:00
56cb1b3594 Add headless note CLI (bin/todo_note.dart) reusing app CRDT sync
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 15:35:46 +02:00
f7df3cbbd1 Repo-contract rollout and dependency bumps (github_device_auth v0.3.2, url_launcher 6.3.3)
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-04 18:23:25 +02:00
9f2ffdb8a9 Attach any file to a note, of any size, not only images
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
📎 now picks any file (Android: Camera / Gallery / File; desktop: an
unfiltered dialog) and the desktop page accepts any dropped file. Photo and
screenshot formats up to 64 MB are still re-encoded and shown inline;
everything else is stored byte for byte on dufs beside the images and linked
as [name](url), shown as a row with its size that opens in the platform's
app (Android) or a new browser tab (desktop). BACKLOG.md rewrites file links
to ~/data/cloud/todo-images/ like image links.

There is no size cap, so no layer holds a file in memory: uploads and
downloads stream through DufsImageClient, writes land in a .tmp renamed when
whole (an interrupted download no longer leaves a truncated file that looks
done), the desktop page POSTs the browser's own Blob with fetch, and Android's
"File" uses file_picker, because file_selector's Android side reads the whole
file into memory on the UI thread. Verified with a 1 GB file end to end on
desktop (peak RSS +36 MB) and on an API 36 emulator.

The wrapper serves attachments from the origin that holds the GitHub token
and the notes, so only script-free types open inline (nosniff), the rest
download; writes carrying another site's Origin are refused (this also
closes cross-site overwrites of the backup files); and attachment routes run
concurrently so a long upload or a playing video cannot stall the page.

Also: cupertino_icons 2.0.0 (unused, but the freshness gate blocks the
pubspec otherwise), open_file 4.0.0 and file_picker 13.1.0 pinned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:17:06 +02:00
05056cf8c2 Rename ImageRef to AttachmentRef ahead of non-image attachments
A ref is about to name any file stored under todo-images/, not only a
re-encoded JPEG. Mechanical rename of the type and its file; no behaviour
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:59:34 +02:00
2bbfe0b663 Desktop: launch Chrome with --password-store=basic so a locked keyring cannot blank the window
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 16:31:08 +02:00
8aa365919b Take Flutter 3.47.5 and Gradle 9.8.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 14:21:25 +02:00
0798f7b1d0 Attach images to notes, stored on dufs and kept offline
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 14:11:15 +02:00
9edcc76569 Bump Flutter to 3.47.4 and flutter_secure_storage to 11.1.1
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 17:19:48 +02:00
753e410fb4 Export the backlog to ~/src/todo, not the pre-reorganisation ~/todo
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 17:13:21 +02:00
3fd326516b Export the backlog to ~/src/todo, not ~/todo
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Both desktop writers build the directory by string interpolation
(`Directory('$home/todo')`), which the ~ reorganisation's reference
rewriter cannot see. The first export after the move recreated a stray
~/todo and tripped the home-tidy root allowlist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwtowrowDXx6ccmWVPkCaF
2026-09-11 20:33:07 +02:00
a0d37c4df8 Re-point paths for the ~ reorganisation (home-tidy)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Also bumps Flutter 3.47.3, flutter_secure_storage 11.1.0, idb_shim 2.9.9,
sqflite_common_ffi 2.4.3, very_good_analysis 11 and mcp 2.2.0 so the
freshness gate lets this through; v11 adds async_return_with_no_await, so
the 18 flagged return sites now await explicitly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwtowrowDXx6ccmWVPkCaF
2026-09-11 19:49:03 +02:00
951b00e263 Grade the todo MCP against 3.14 too, not just run on it
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
ruff and mypy were still grading `mcp/` against 3.10 while `requires-python`
had already moved to 3.14, so `datetime.timezone.utc` survived where
`datetime.UTC` is now correct (UP017). `pin_ci_python.py` rewrites the knobs;
ruff's `--select UP,I,F401 --fix` did the rest.

`mcp/` has no ruff hook in `.pre-commit-config.yaml`, so it also carries six
pre-existing CPY001 (missing copyright notice) findings. Those fire identically
at py310 and are left alone -- they are not this change's to fix.

24 tests pass at 100% line and branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:46:10 +02:00
f3facdd2ee One Python, always the newest
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 19:41:02 +02:00
6dbfb78f79 Refresh the gate workflow from the shared template
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 16:55:53 +02:00
4bc1ab6ef6 Pin the CI toolchain to the SDK this repo actually builds with
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
`.fvmrc` says 3.47.2 and nothing read it: `subosito/flutter-action` takes its
own `flutter-version:`, and the fleet had drifted to 3.44.6, 3.44.8, 3.44.9,
3.47.0 and 3.47.1 with no one tracking it. kuhylog is the proof it matters --
its runner on 3.44.9 predates the `@awaitNotRequired` annotation, so the same
`unawaited(Navigator.push(...))` is a violation on one SDK and required on the
other, and CI went red on a commit that is clean locally.

The freshness gate reads these pins now (utils@98213cb), so this cannot drift
again in silence.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 15:06:09 +02:00
5f29dfebf7 Latest stable dependencies, and the gate that keeps them there
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Three git-tag pins move (crdt_sync_dart v0.10.0 -> v0.11.1, design_system
v0.1.0 -> v0.2.1, github_device_auth v0.3.0 -> v0.3.1) and every caret in the
pubspec becomes an exact pin, flutter_secure_storage 10.3.1 -> 11.0.0 being
the one that matters. That version demands compileSdk 37, which needs AGP >
9.1.0, which needs Gradle >= 9.5.0, so those three move in this commit too.

**mcp 1.x -> 2.1.1 in the MCP subproject is a real breaking change.** FastMCP
was renamed MCPServer and moved to `mcp.server.mcpserver`; the decorator and
`run()` API are unchanged, so the migration is the import and the constructor.
Verified by driving the server over stdio: `initialize` and `tools/list` both
answer, all three tools still enumerate. 24 tests at 100% coverage.

`very_good_analysis` 10.3 adds a `cascade_invocations` finding on the
port-in-use message in bin/todo_desktop.dart. Fixed, not suppressed.

300 Dart tests green, `flutter analyze` clean, release APK builds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 14:46:50 +02:00
KRZYSZTOF RUDNICKI
0a0fe88b09 Bump sync_settings_ui to v0.4.0, fixing Connect Firebase hanging forever
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
connectWithPassword() had no try/catch around firebaseFactory(), unlike
connectWithGoogle() right next to it. A thrown FirebaseAuthError (wrong
password, 400 from identitytoolkit) escaped uncaught out of the button's
async onPressed, so the screen sat on "Signing in..." forever with no
error shown -- reproduced live via the browser console. Fixed upstream in
kuhyx/utils (sync_settings_ui-v0.4.0), which also required moving
crdt_sync onto v0.11.0. Verified: wrong password now shows
"Firebase rejected that account: <reason>" and re-enables the button
instead of hanging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-25 14:46:46 +02:00
59ee407d80 Adopt the four markdown namespaces and gate them
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Renames this repo's markdown onto README.md / CLAUDE*.md / DOCS*.md /
TODO*.md so a future session can tell a live task from a finished
record without reading the file to find out.

TODO files carry the literal "REMOVE ME AFTER FINISH" and are deleted
when the work lands. Enforced by the md-naming pre-commit hook and CI
workflow, both delegating to the shared gate in kuhyx/utils so this
repo's idea of a valid name cannot drift from every other repo's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A47aX5DJwmA3QFn3pkEWi7
2026-08-24 15:54:35 +02:00
fca5deebe6 Add dopamine-ux session prompt to prompts/
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Copy of the canonical prompt in ~/utils/dopamine-ux/, distributed here so the
repo can be opened and the prompt run directly. Derived from a survey of this
repo plus "The Dopamine Architecture" (london-post.co.uk).

Each prompt states its own completion protocol: when finished, the session
deletes this copy in the implementation commit and logs a DONE row in
~/utils/dopamine-ux/00-INDEX.md. Partial completion is never recorded as done.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FdApz7EZ1zDfvtvvi1idDv
2026-08-16 21:12:52 +02:00
f46b65750e Use the shared github_device_auth package
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
todo was the donor for both halves of the GitHub device flow -- its
`lib/sync/github_device_auth.dart` was byte-identical to home_inventory's,
and `lib/ui/device_code_dialog.dart` was the public version of the modal
diet-guard and wake-alarm each carried privately. All of it now lives in
`github_device_auth` in the kuhyx/utils monorepo.

The package is not a straight copy of what left here: it takes the more
capable variant of each divergence found across the four apps, so this app
gains two fixes it never had --

  * `pollForToken` retries a transient `ClientException` instead of
    failing, because GitHub can close the connection at the moment the
    user authorizes (wake-alarm's fix)
  * the dialog catches `on Object`, not `on Exception`, so an
    `ArgumentError` surfaces as an error message instead of leaving the
    dialog spinning forever

The local `test/github_device_auth_test.dart` is deleted; its cases live in
the package now, where they gate all four consumers. 300 tests pass and
`test/github_mirror_device_flow_test.dart` -- which drives the shared
dialog end to end -- is among them.

Deployed to the phone as versionCode 17 via phone_deploy.sh (signer
verified, `adb install -r`, no uninstall): launches with all 109 notes
intact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U4Rj3s7K2qzrLNgJqqPhno
2026-08-15 16:15:10 +02:00
f4272d01b9 Route todo's snackbars through the shared showToast/showError
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
The package shipped feedback helpers while todo still had a private
_showSnack and a raw SnackBar in note_editor -- exactly the duplication
the extraction was meant to end, left live in a repo that had just
adopted the package.

Two deliberate behaviour changes come with it: the duration goes 2s ->
3s for toasts and 5s for errors (an error the user missed is an error
they will hit again), and messages now replace rather than queue, since
a queued snackbar describes an action the user moved on from seconds
ago. No test asserted on either, and the one snackbar assertion in the
suite checks that capture is *not* interrupted by one, which still holds.

Failures now read as failures: the mode-switch rejection in note_editor
and a failed sync in capture_screen use showError, while a successful
sync and the not-configured hint stay neutral toasts. Spending the danger
hue on routine confirmations is how a real failure becomes invisible.

Verified: flutter analyze clean, 308 tests pass at 100% coverage
(1964/1964). The release APK built and installed, but on-device
re-verification could not complete: the 23:00 night curfew removed the
package ~80ms after install, because dev.kuhy.todo is in the focus-mode
day WHITELIST but not NIGHT_WHITELIST. Enforcer working as designed, not
an app fault -- reverify after 05:00.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XS1m7b1piBtAL22USLW6jL
2026-08-14 23:09:24 +02:00
e6e1052c59 Adopt the shared design_system package, dropping theme.dart and confirm.dart
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Both files were donors for the new package rather than casualties of it:
theme.dart was byte-identical to untools' copy (md5 6cf8e82d), and
confirm.dart's confirmDestructive() was the ready-made pattern for the
~35 AlertDialogs inlined across the fleet. Keeping local copies after
promoting them upstream is exactly how the two would drift apart again,
so they are deleted and imported from design_system-v0.1.0 instead.

test/confirm_test.dart moves upstream with its subject -- the package
covers that behaviour (Escape and the barrier both refuse, Cancel is
autofocused so a reflexive Return cannot delete) as part of its own
100% gate. test/theme_test.dart stays as a consumer-side smoke check
that the dependency actually resolves to the frozen palette.

Verified: flutter analyze clean (bar one pre-existing bin/ style info),
308 tests pass at 100% coverage (1962/1962 -- the drop from 2005 is
exactly the promoted lines), and the release APK is installed and
running on the Pixel 6a with all 108 notes intact, the gold #B8862E
focus ring rendering from the package's inputDecorationTheme, and no
crashes in logcat.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XS1m7b1piBtAL22USLW6jL
2026-08-14 22:59:59 +02:00
85a45daaee Share one note form between capture and the detail screen
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Editing an existing note looked nothing like capturing a new one: it
always showed the template dropdown, the View/Guided/Raw pills and the
priority/status row. The cause was one missing argument -- both screens
already embedded the same NoteEditor, but NoteDetailScreen never passed
advancedMode, which defaults to true in the widget while the app-wide
AppSettings.advancedMode defaults to false.

Extract the shared form as three single-purpose components rather than
one widget owning several jobs:

- note_meta_row.dart renders the priority/status row (was
  capture_meta_row.dart; drops the private _MetaDropdown duplicate the
  detail screen carried, which used DropdownButtonFormField where the
  shared one uses DropdownButton).
- note_form_chrome_gate.dart owns chrome visibility and nothing else,
  replacing the _chromeVisible flag both screens copy-pasted.
- note_form.dart composes those two with NoteEditor.

appSettings is now a required parameter through NotesListScreen and
NoteDetailScreen. Required, not defaulted: a silent default is exactly
what caused this, so it must not be reintroducible.

Also in the capture app bar: drop the decorative Icons.list_alt_outlined
beside the note count, since the adjacent Icons.list button already names
what is counted, and move the count to the right of that button. The
finalize-and-clear action becomes Icons.check instead of Icons.add -- it
never saved anything (every keystroke is already persisted), so a plus
sign misdescribed it.

314 tests, 100% line coverage. Verified in a running web build that edit
and capture render identically with advanced mode both off and on.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:48:39 +02:00
4e66de5467 Exclude platform dirs from analysis; refresh the lockfile
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
analysis_options.yaml: keep the analyzer out of android/ios/web/windows/
macos/linux. A no-op today — those directories hold no Dart (checked: 0
files each, and `flutter analyze` reports the same two pre-existing infos
either way) — but it stops generated platform Dart from ever entering the
lint surface.

pubspec.lock: transitive bumps (matcher 0.12.19->0.12.20, test_api,
leak_tracker and friends) picked up by the `flutter pub get` runs during
the file-cap refactor. No direct dependency changed.

Both had sat uncommitted through that refactor because I misattributed
them to kuhy and deliberately left them unstaged; they are this machine's
work, so they belong in the history.

Verified: flutter analyze clean (same 2 pre-existing infos), 313 tests
pass, file-length gate exits 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:20:51 +02:00
34b2c1c87c Fix three gate defects found reviewing the cap refactor
Moving bump_patch_version.sh into .pre-commit-config.yaml introduced three
bugs, all reproduced in clean clones of HEAD before fixing and re-verified
after:

1. DATA LOSS. pre-commit stashes unstaged changes and restores them with
   `git apply`. The bump rewrites pubspec.yaml inside that window, so an
   uncommitted edit near the `version:` line made the restore conflict:
   the commit aborted AND the developer's edit vanished from the working
   tree, recoverable only from $PRE_COMMIT_HOME. Only non-mutating checks
   belong in that file.

2. A commit rejected by the file-length gate still had its version bumped
   and staged, riding into the next successful commit. `always_run: true`
   with no `fail_fast` meant "ordered last" did not mean "runs last only
   on success" -- which is exactly what the comment above it claimed.

3. `files: ^pubspec\.yaml$` narrowed the crdt_sync override check from
   unconditional to staged-only, so a poisoned pubspec arriving by pull or
   merge was invisible to every later commit that did not touch pubspec.
   The hand-written hook this replaced checked it every time; that
   narrowing quietly widened the hole the check exists to close.

The fix keeps the framework for the read-only gates and puts the mutation
back outside it: install_hooks.sh now writes a wrapper that runs
pre-commit's generated hook first and bump_patch_version.sh only if it
passed. Plus fail_fast, and always_run on the crdt check.

Also fixes three stale references this refactor created: a load-bearing
layout comment citing the renamed _buildRaw, bin/todo_desktop.dart naming
two split-away test files, and CLAUDE.md giving two different suite
runtimes.

Verified: unstaged pubspec edit preserved through a commit; a rejected
commit leaves nothing staged; a merged-in override is caught on an
unrelated commit. 313 tests, 100% coverage, gate exits 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:13:31 +02:00
5856617cbf Mark refactor_claude_todo.md done for this repo
The survey counts at the top described a state that no longer exists, so the
file contradicted the repo it lives in. The counts stay as the record of what
was refactored; a banner above them states the outcome and how it was
verified.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:51:07 +02:00
25e2c9bb20 Split CLAUDE.md and the performance doc; the whole repo is under the cap
CLAUDE.md 925 -> 165. 789 of those lines were a verbatim paste of upstream's
flutter/flutter rules.md -- 85% of an always-loaded file given over to a
document nobody edits. It moves to five topic files under docs/, linked
rather than @-imported: inlining it back would pass the cap while keeping it
in context on every turn, which is the cost the cap exists to remove.

Every `###`/`####` heading in the upstream block survives the split; the two
that do not are its own wrapper headings, replaced by the per-file titles
(verified by diffing the sorted heading lists).

desktop-performance-findings.md 278 -> 73 + 216. It was already narratively
two-part; the author signposted "Part 2" explicitly at the seam.

Also updates two things that had drifted: the suite is 313 tests at 100%
coverage (not 238), and Conventions now documents the cap, where the gate
lives, and the two patterns used to split without breaking callers
(re-export barrels, and `part` files where a private State must stay in one
library).

`bash ~/utils/scripts/check_file_length.sh --all` now exits 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:46:54 +02:00
95c358cb5c Split sync_service_test.dart; all code and tests now under the cap
356 -> sync_service_test (133) + sync_service_revision_test (96) +
sync_service_fakes (163).

The underscores came off every shared fake: Dart privacy is library-scoped,
so `_FakeRemote` declared in one file is invisible to the next. `_peerLog`
became `buildPeerLog` rather than `peerLog`, because two tests declare a
local variable of that name and the helper would have been shadowed by its
own caller.

The `_revisionTrackingTests()` indirection is gone -- that function existed
only to keep main() readable, which is now the file boundary's job.

Verified: 313 tests pass, 100% coverage. Only CLAUDE.md and
docs/desktop-performance-findings.md remain over 250 lines.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:44:32 +02:00
10a546f6d6 Split nine oversized test files under the cap
Every split is by test-group/concern, with the shared setup moved to a
sibling helper the splits import. All 313 tests are preserved -- the count
is unchanged and `test('…')` names are byte-identical to the originals
(verified by diffing the sorted name lists).

  note_repository_test      677 -> 4 files + note_repository_helpers
  capture_screen_test       660 -> 4 files + capture_screen_harness
  note_editor_test          502 -> 3 files + note_editor_harness
  port_guard_test           405 -> 3 files + port_guard_fakes
  wrapper_server_test       402 -> 2 files + wrapper_server_harness
  settings_screen_test      391 -> 2 files + settings_screen_harness
  github_mirror_screen_test 365 -> 2 files + github_mirror_harness
  notes_list_screen_test    347 -> 2 files + notes_list_harness
  analytics_service_test    300 -> 2 files + analytics_helpers

Helpers are deliberately NOT named `*_test.dart`; the runner would collect
them and fail on the missing `main()`.

Three things did not survive a mechanical split and were handled explicitly:

  * wrapper_server's `enabledOrigin` closes over the `late root` that setUp
    assigns, so a top-level function cannot see it. It is now a
    WrapperHarness class with an install() that registers the setUp/tearDown
    pair -- the only structural change in this commit.
  * note_repository's splits each repeat `setUpAll(sqfliteFfiInit)`, and
    analytics' each repeat `@TestOn('vm')`. Omitting either fails quietly
    (uninitialised sqflite / wrong platform) rather than loudly.
  * capture_screen's `recordingMock` was declared mid-file between two
    tests, so it moved to the harness rather than being dropped.

Verified: 313 tests pass (same as before the refactor), 100% coverage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:42:13 +02:00
d145f92a07 Split note_repository.dart, taking coverage to 100%
429 -> 249 lines:

  note_query.dart   NoteSort, NoteFilter, and the pure predicates behind
                    them (matchesFilter, comparatorFor). All of it takes
                    notes and a filter and returns a decision, which is what
                    made it the natural seam.
  note_import.dart  ImportOutcome and the in-memory LogPersistence used by
                    openInMemory.

note_repository.dart re-exports both, so no call site changed.

Also drops ImportOutcome.total, which nothing called. It was uncovered
before this split too -- the larger file's percentage hid it. With it gone
the suite reports 100% line coverage (2005 lines), up from the 99.9%
baseline measured at the start of this refactor.

lib/ and bin/ are now fully under the cap. 313 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:32:06 +02:00
381afd1d77 Split the last three oversized lib/bin files
github_mirror_screen.dart  368 -> 232 + device_code_dialog.dart (109) and
                             a widget part
  wrapper_server.dart        336 -> 223 + wrapper_sync_routes.dart, the two
                             credential-provisioning routes
  bin/todo_desktop.dart      253 -> 199 + lib/desktop/browser_launcher.dart

The fixed port moved into browser_launcher.dart as kWrapperPort, with the
entry point aliasing it, so the "must not move" reason is stated once next
to the code that acts on it.

lib/ and bin/ are now entirely under the cap. The two remaining analyze
infos (bin/todo_desktop.dart cascade_invocations,
capture_screen_sync.dart unnecessary_unawaited) are pre-existing --
verified by analyzing e0eb8b9 in a worktree, which reports the same two.

Verified: 313 tests pass, coverage unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:29:35 +02:00
d4c8162e0e Split capture_screen.dart into ten files under the cap
739 -> 249 lines. As with note_editor, the ~600-line State class needed
decomposing rather than moving:

  capture_draft.dart         the note being captured and its write-through
                             to storage -- the model behind "every keystroke
                             is already persisted". Lazy row creation stays
                             here; the screen just logs that it happened.
  capture_sync_runner.dart   one sync pass, with no BuildContext. This also
                             de-duplicates the two callers: the manual button
                             and the background tick ran byte-identical
                             runSync blocks differing only in the snackbar
                             and the 'auto' log flag.
  capture_status.dart        SyncStatusStore (the persisted last outcome) and
                             describeSyncResult.
  capture_app_bar.dart       the app bar.
  capture_meta_row.dart      the priority/status pickers.
  capture_status_footer.dart the two status lines.
  capture_screen_{widget,sync}.dart
                             parts, for the same reason as note_editor's.

The mounted checks are preserved exactly, including the one in
SyncStatusStore.restore that must fire AFTER its await rather than before
(writing the notifier post-dispose is the bug it exists to prevent), which
is why it takes a stillLive callback instead of a bool.

Verified: 313 tests pass, analyze clean, every capture file at 100%
coverage. lib/ and bin/ are now down to three files over the cap.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:25:51 +02:00
63725e726f Split note_editor.dart into nine files under the cap
702 -> 220 lines, decomposed rather than just moved, because a single
~600-line State class was the actual problem:

  note_editor_document.dart   the text model -- template, controllers, and
                              which of the two sources (raw body vs. section
                              fields) is authoritative. None of it needed a
                              BuildContext or a setState, which is what made
                              it the honest seam. The raw<->guided conversions
                              and the initial-template detection moved here as
                              tryAdoptGuided/materialiseToRaw/forInitialText.
  note_editor_wizard.dart     the two-step priority+template wizard, which now
                              owns its own step state instead of parking three
                              fields on the editor.
  note_editor_step_page.dart  the guided per-step view.
  note_editor_chrome.dart     the template picker + mode toggle.
  note_editor_raw_field.dart  the raw-mode text field.
  note_editor_mode.dart       the mode enum, re-exported so callers are
                              unaffected.
  note_editor_{widget,views}  parts, not libraries: createState returns a
                              private class, so the widget and its State
                              cannot be split across libraries.

The layout comments about Expanded/expands:true are load-bearing (nesting
broke the constraint chain in release builds before), so they travelled with
the code they describe rather than being summarised away.

Verified: 313 tests pass, flutter analyze clean. Covered lines went UP,
1922 -> 1958, because the wizard's state is now exercised in a widget of its
own; every new file reports 100%.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:12:04 +02:00
9d2aa1c178 Enforce the 250-line file cap, and split the first four files
Wires the shared gate (~/utils/scripts/check_file_length.sh) into a new
.pre-commit-config.yaml as a local hook, checking only the files in the
commit and failing rather than warning. No baseline, no allowlist.

The repo had a hand-written .git/hooks/pre-commit running two checks;
both are ported verbatim into the config rather than dropped, with the
version bump ordered last so it cannot rewrite pubspec.yaml for a commit
a gate is still about to reject. scripts/install_hooks.sh now installs
pre-commit (and removes the legacy hook) instead of writing its own.

.github/workflows/file-length.yml runs the same check on push, kept
separate from release-apk.yml so an over-long file fails lint rather than
blocking an APK release.

Splits the four cleanest violations, all behaviour-preserving:

  note_template.dart      370 -> 203 + parser (186)
  firebase_backend.dart   308 -> barrel (24) + project/store/client
  port_guard.dart         315 -> 232 + linux_system_probe (100)
  notes_list_screen.dart  698 -> 225 + 5 widget/nav files

Where a file had external callers, the original path stays as a barrel
that re-exports the split parts, so no call site changed.

Verified: 313 tests pass, coverage identical at 99.9% / 1922 lines
(per-file too -- notes_list's 281 covered lines are now 81+75+51+41+22+11),
flutter analyze clean, and a staged 260-line file makes git commit fail.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 16:01:24 +02:00
2c97a9c19c Update refactor_claude_todo.md counts after gate exemption fixes
Some checks are pending
release-apk / release (APK) (push) Waiting to run
Git-ignored files, vendored agent-skill bundles and the CI checkout dir are
now exempt, since no commit could ever fix them. Repo counts and the ranked
violation lists are regenerated accordingly; the global baseline drops from
657 to 597.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 15:59:20 +02:00
e0eb8b9ea9 Add refactor_claude_todo.md: 250-line file-length cap
Some checks are pending
release-apk / release (APK) (push) Waiting to run
A ready-to-use prompt describing the goal (every file at most 250 lines,
code and prose alike), this repo's actual violations ranked by Fowler ROI
(lines x commits/yr), how to split each kind, and the requirement to wire in
the shared pre-commit gate so files stay small permanently.

Generated from a measured survey of every repo; the gate itself lives in
~/utils (file_length/ + scripts/check_file_length.sh).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 14:25:42 +02:00
49a94c9550 Migrate Sync settings to the shared sync_settings_ui package
Some checks failed
release-apk / release (APK) (push) Has been cancelled
Splits the old single Settings screen into two: "Enable advanced" plus
links to a Sync settings route (Firebase + notes backup, now the shared
sync_settings_ui package used across every kuhy app that syncs) and an
Advanced sync (GitHub) route. GitHub stays app-local rather than moving
into the shared package: connecting it here also triggers a real note sync
via runSync(), not just a settings save, which the generic package
intentionally doesn't do for any app.

313/313 tests passing, 100% line coverage on both new/changed screens,
flutter analyze clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-12 23:25:16 +02:00
fd1865db78 Speed up release-apk CI: cache Gradle, build arm64 only
Some checks are pending
release-apk / release (APK) (push) Waiting to run
The "Build signed APK" step was ~292s of the ~350s total run, entirely
spent on a cold Gradle build (no dependency/build cache) compiling and
dexing a fat APK with armeabi-v7a and x86_64 native code that no device
this app has ever run on needs — BL9000, the only install target, is
arm64-v8a (confirmed via adb).

Adds gradle/actions/setup-gradle for Gradle's dependency+build cache
(flutter-action's cache only covers the Flutter SDK/pub packages, not
Gradle) and restricts the build to --target-platform android-arm64.
Verified locally: build succeeds, signer unchanged (CN=kuhy), output
APK 22.1MB vs 61.6MB for the fat build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 21:38:13 +02:00
ce2ea5b410 Simplify capture UI behind an advanced-mode toggle, add usage analytics
Hide priority/status/template/mode chrome and routine sync-status text
behind a Firebase-synced "Enable advanced" setting (default off); remove
the Capture title and Save button in favor of autosave + a plain reset
icon; sort notes by priority then recency; add interaction-only usage
analytics buffered locally and flushed to Firebase alongside note sync.

Code review (self + follow-up verification pass) found and fixed 3 real
bugs during this work: a widget-key placement bug that discarded an
in-progress draft when advancedMode was toggled mid-typing, a data-loss
bug in the analytics buffer's flush-and-clear logic under concurrent
cap-eviction, and two spots where an expired/wrong-account Firebase
session (FirebaseAuthError) escaped a narrower catch clause and would
have failed an otherwise-successful sync pass.

Also fixes an unrelated pre-existing test-isolation bug in
wrapper_server_test.dart, which was reading the real
~/.config/todo/firebase_auth.json instead of a test-scoped path.

320 tests, 100% line coverage on all touched files (one pre-existing,
out-of-scope 5-line gap in settings_screen.dart unrelated to this
change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 21:30:40 +02:00
415 changed files with 31184 additions and 9835 deletions

5
.claude/settings.json Normal file
View File

@ -0,0 +1,5 @@
{
"enabledPlugins": {
"dart-flutter@dart-flutter": true
}
}

View File

@ -0,0 +1,2 @@
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
# workflow. This marker stops the fleet installer from re-adding it.

3
.fvmrc Normal file
View File

@ -0,0 +1,3 @@
{
"flutter": "3.50.1"
}

33
.github/workflows/file-length.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: file-length
# The 250-line cap, enforced on push as well as at commit time. The local
# pre-commit hook can be skipped (a fresh clone that never ran
# scripts/install_hooks.sh has no hooks at all), so the cap needs a second
# gate that no one can forget to install.
#
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
# long should fail lint, not block publishing an APK.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
file-length:
name: file length <= 250 lines
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same cap. Checking it out beats vendoring a copy
# here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the cap
run: bash .utils/scripts/check_file_length.sh --all

38
.github/workflows/md-naming.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: md-naming
# The four markdown namespaces, enforced on push as well as at commit time.
# The local pre-commit hook can be skipped (a fresh clone that never ran
# `pre-commit install` has no hooks at all), so the convention needs a second
# gate that no one can forget to install.
#
# Deliberately a SEPARATE workflow from any release job: a badly named doc
# should fail lint, not block publishing an artifact.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
md-naming:
name: markdown naming convention
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same namespaces. Checking it out beats vendoring a
# copy here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the naming convention
run: bash .utils/scripts/check_md_naming.sh --all
# Warns only: no machine can prove a task is finished, so an old TODO
# gets a nudge, never a failure.
- name: Warn about stale TODOs
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py

View File

@ -47,10 +47,17 @@ jobs:
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
flutter-version: 3.44.8 flutter-version: 3.50.1
channel: stable channel: stable
cache: true cache: true
# Caches Gradle's dependency + build cache (not covered by
# flutter-action's cache, which only covers the Flutter SDK/pub
# packages). This is what the ~5min "Build signed APK" step was mostly
# spending on a cold runner: every run re-downloaded the Gradle
# wrapper and every AGP/Kotlin/dependency artifact from scratch.
- uses: gradle/actions/setup-gradle@v4
- name: Read version from pubspec - name: Read version from pubspec
id: ver id: ver
run: | run: |
@ -91,11 +98,21 @@ jobs:
- run: flutter pub get - run: flutter pub get
# arm64-v8a only: this is a personal single-device (BL9000) sideload
# distribution, not a Play Store multi-device release, and every
# device it has ever installed on is arm64-v8a (`adb shell getprop
# ro.product.cpu.abi`). A fat APK spent most of its build time
# compiling/dexing/packaging armeabi-v7a and x86_64 native code that
# is never installed anywhere. If this ever needs to run on a
# non-arm64 device, drop --target-platform to rebuild the fat APK.
- name: Build signed APK - name: Build signed APK
run: | run: |
flutter build apk --release \ flutter build apk --release \
--target-platform android-arm64 \
--build-name="${{ steps.ver.outputs.semver }}" \ --build-name="${{ steps.ver.outputs.semver }}" \
--build-number="${{ steps.vc.outputs.code }}" --build-number="${{ steps.vc.outputs.code }}" \
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
# Fail closed. `findByName("release") ?: debug` silently falls back to # Fail closed. `findByName("release") ?: debug` silently falls back to
# the debug key if key.properties is misplaced, producing a green build # the debug key if key.properties is misplaced, producing a green build

25
.github/workflows/repo-contract.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: repo-contract
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
# contract is enforced on push too. Mirrors md-naming.yml.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
repo-contract:
name: repo contract
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the repo contract
run: bash .utils/scripts/check_repo_contract.sh

3
.gitignore vendored
View File

@ -50,3 +50,6 @@ todo-backlog.md
# Android Gradle build output # Android Gradle build output
/android/build/ /android/build/
# pytest-cov scratch file from the mcp/ subproject.
.coverage

View File

@ -1,10 +1,11 @@
{ {
"mcpServers": { "mcpServers": {
"todo": { "todo": {
"type": "stdio", "type": "http",
"command": "${HOME}/.venvs/todo-mcp/bin/python", "url": "http://127.0.0.1:8735/mcp",
"args": ["-m", "todo_mcp._mcp"], "headers": {
"env": {} "Authorization": "Bearer ${TODO_MCP_TOKEN}"
}
} }
} }
} }

125
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,125 @@
# Pre-commit hooks for todo.
#
# This repo previously used a hand-written .git/hooks/pre-commit installed by
# scripts/install_hooks.sh. It moved to the pre-commit framework when the
# 250-line file-length gate was added, so the *checks* live in one place with
# one install path.
#
# Only non-mutating checks belong here. pre-commit stashes unstaged changes
# for the duration of the run and restores them with `git apply` afterwards;
# a hook that rewrites a tracked file inside that window makes the restore
# conflict, which aborts the commit AND drops the developer's uncommitted
# edit. scripts/bump_patch_version.sh rewrites pubspec.yaml, so it stays out
# of this file and runs from the wrapper hook instead -- see
# scripts/install_hooks.sh.
#
# fail_fast so a later check cannot run after an earlier one has already
# rejected the commit.
#
# Install with: scripts/install_hooks.sh
# The hooks are `language: system` because they are plain bash/python already
# on this machine; pre-commit must not build an isolated env for them.
fail_fast: true
repos:
- repo: local
hooks:
# Gate first: a local crdt_sync override left in place makes CI build a
# library this checkout has never tested against, silently and in both
# directions. Blocking the commit is the only thing that prevents it.
#
# always_run/pass_filenames rather than `files:`: a poisoned pubspec can
# arrive by pull, merge or --no-verify, and a staged-only trigger would
# then never look at it again for any commit that does not happen to
# touch pubspec.yaml. The old hand-written hook checked it every time;
# narrowing that to staged-only silently widened the hole this gate
# exists to close.
- id: no-crdt-sync-override
name: no local crdt_sync dependency_override
entry: scripts/check_no_crdt_sync_override.sh
language: system
pass_filenames: false
always_run: true
# The shared 250-line cap. Checks only the files in the commit, so an
# unrelated commit never breaks; exits 1 rather than warning. No
# baseline and no allowlist -- those are suppressions. The exemption
# list (generated/vendored/data files) lives with the checker in
# ~/src/utils/file_length/config.py so the gate and the survey cannot
# disagree.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
# Shared gate in ~/src/utils owns the namespaces and the exemption list, so
# one repo's idea of a valid name cannot drift from every other repo's.
# Since the 2026-09-11 reorganisation ~ holds eleven visible entries and
# home-tidy sweeps anything else to inbox/ within the hour. The migration's
# rewriter matched *literal* /home/kuhy/<name> strings, so paths assembled
# at run time survived it -- the todo wrapper exported to a dead ~/todo for
# a day while its MCP read ~/src/todo. This gate matches the shape, so it
# stays correct as repos come and go.
- id: home-path-layout
name: home-relative paths stay inside the ~ layout
entry: bash scripts/check_home_paths.sh
language: system
pass_filenames: true
- id: md-naming
name: markdown naming convention
entry: scripts/check_md_naming.sh
language: system
files: \.(md|markdown)$
- id: todo-closer
name: close Todo trailer tasks
entry: scripts/todo_hooks.sh closer
language: system
stages: [post-commit]
always_run: true
pass_filenames: false
- id: todo-import-pr-merge
name: import PR Todo sections (pull)
entry: scripts/todo_hooks.sh import-pr post-merge
language: system
stages: [post-merge]
always_run: true
pass_filenames: false
- id: todo-import-pr-rewrite
name: import PR Todo sections (pull --rebase)
entry: scripts/todo_hooks.sh import-pr post-rewrite
language: system
stages: [post-rewrite]
always_run: true
pass_filenames: false
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
# so the question is mechanically answerable at all.
#
# `files:` is what keeps this cheap: a commit touching only source makes
# ZERO network requests, and manifest commits mostly hit a 6h disk cache.
#
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
# answer and passes with a loud banner; `--no-verify` is banned here, so
# a hook that hard-failed on a flaky connection would leave no way to
# commit at all. Local only: no CI workflow runs this.
- id: dependency-freshness
name: dependencies on newest stable
entry: scripts/check_dependency_freshness.sh
language: system
pass_filenames: true
files: >-
(pubspec\.(yaml|lock)|pyproject\.toml|requirements.*\.txt|uv\.lock
|package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version)$
- id: repo-contract
name: repo contract (CLAUDE.md Commands + test_changed)
entry: scripts/check_repo_contract.sh
language: system
pass_filenames: false
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$

235
AGENTS.md Normal file
View File

@ -0,0 +1,235 @@
# CLAUDE.md — todo
Offline-first, CRDT-synced notes app. Flutter, targets **Android + web**.
The **desktop app is the web build**, served by a small local wrapper
(`bin/todo_desktop.dart`) and shown in a Chrome `--app` window. Flutter's Linux
embedder was removed: it manages only ~20fps at 4K while the same Dart code in
Chrome sustains ~144fps. See `docs/DOCS-desktop-performance-findings.md` for the
measurements. Do not re-add `linux/` — `flutter create --platforms linux` would
silently bring the slow path back.
Capture an idea instantly (persisted on every keystroke), browse/filter notes,
and sync peer-to-peer through a GitHub repo used as dumb storage.
- Package name: `todo` (Dart SDK `^3.12.2`).
- Git remote: `origin` → `github.com/kuhyx/todo-app`.
- The note **content** also syncs to a separate private repo `kuhyx/syncs`
(under `todo-sync/`) via the in-app GitHub sync (changeset files); that is
data, not this codebase.
## Git workflow (repo-specific — overrides global rules)
- **Never open pull requests. Always commit and work directly on `main` and
`git push` to `origin/main`.** Do not create feature branches for normal work.
- End commit messages with the standard
`Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>` trailer.
## Commands
- Run tests + coverage: `flutter test --coverage` (suite runs in under a minute; keep it
quick — see Testing below).
- Coverage summary: `lcov --list coverage/lcov.info`.
- Static analysis: `flutter analyze` (must be clean before committing).
- Format: `dart format lib/ test/`.
- Run the desktop app: `./run.sh` (builds the web bundle, starts the wrapper,
opens Chrome). Mobile: `flutter run` with a connected Android device.
- The wrapper serves on a **fixed** port 8730 with a **fixed** Chrome profile
dir. Both must stay fixed: the GitHub token (`localStorage`) and the notes
(IndexedDB) are keyed by origin and live in that profile, so changing either
silently logs you out and hides your notes. Because the port cannot move,
`lib/desktop/port_guard.dart` decides what to do when it is already taken:
reap a wrapper with no window attached (so an upgrade can't leave you on old
code), join one that still has a window, and refuse to touch anything else.
- Release APK: `flutter build apk --release` (signs with the debug key; debug
builds are janky — always measure smoothness on a release build).
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.
- MCP server (`lib/mcp/`, :8735): tests `flutter test test/mcp/`, deploy `mcp/install.sh`; see `mcp/README.md`.
- run: `./run.sh` (desktop; mobile: `flutter run`)
- test: `flutter test --reporter=compact`
- test-changed: `scripts/test_changed.sh`
- lint: `flutter analyze`
- coverage: `flutter test --coverage --reporter=compact`
- coverage-gaps: `coverage-gaps coverage/lcov.info`
- deploy: `scripts/deploy.sh` (MCP service, desktop pacman package, phone release; exits non-zero unless every health check passes)
## Architecture
Three layers under `lib/`, each single-purpose:
- `data/` — domain + local storage.
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
Optional repo-task fields `repo`/`doneCheck`/`by`/`evidence`: a note
with `repo` is a repo task, one without is a plain idea.
- `note_repository.dart`: CRDT storage over the schemaless `crdt_sync`
`LogStore`; `note_record.dart` maps a note to record fields `text`,
`priority`, `status`, `created_at`, `updated_at` (+ `repo`, `done_check`,
`by`, `evidence`, written only when set, so an idea's record stays
v3-identical: `note_repository_sync_compat_test.dart`). The old sqlite
schema (v3) survives only in `legacy_sqlite_migration.dart`. Also defines
`NoteFilter` (query / priorities / statuses / repo / date ranges,
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
`importNotes` (safe newer-wins merge by id).
- `sync/` — GitHub-as-storage sync.
- `sync_service.dart`: each device owns one file
`todo-sync/changesets/<nodeId>.json`
holding its full CRDT changeset. No two devices write the same file ⇒ no
git merge conflicts; convergence is the CRDT layer's job (pull every other
device's changeset and `merge()`, which is commutative + idempotent).
- `github_client.dart`: thin GitHub contents-API client (injectable
`http.Client`). `github_device_auth.dart`: OAuth device flow to mint a
token. `sync_settings.dart`: persisted owner/repo/token/clientId.
- `notes_markdown.dart`: round-trippable single-file export/import format
(HTML-comment `<!-- @note id=… priority=… status=… … -->` markers).
- `images/` + `attachments/` — attached images and files (see "Images and other attachments" below).
- `ui/` — screens, all take an injected `NoteRepository`.
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
with the structured template; lazy note creation on first keystroke.
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
sheet. One open note per repo (`data/repo_note.dart`). **Default view hides Done/Abandoned and shows no filter badge**
(looks unfiltered). Under 600dp wide (`kNotesGridMaxWidth`) the notes are
a 2-column `NotesGrid` of compact `NoteGridTile`s (title + priority/status
cues; body and dates are in the long-press sheet). The tile height is
derived so whole rows exactly fill the viewport; past one screenful it
scrolls vertically (no paging). Wider windows (desktop) keep the list.
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
Export/Import backup actions.
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
paths and `runApp`.
### Note template (default content of every new note)
`lib/data/note_template.dart` is the **single source of truth** — the stepper,
the editor and the tests are all template-driven, so changing that list changes
every surface. A new note pre-fills a title line plus
`what / where / must / done / verify / read first`.
The set was cut from twelve sections to seven in 2026-07 after auditing 514 real
sessions (`docs/DOCS-llm-design-spec-audit.md`): `estimate`, `ask`, `nice`, `tech`,
`never` and `depends` were measurably never read, and `verify` was added because
"test it yourself, on the phone" was the single most repeated correction in the
corpus. Do not re-add a section without evidence that it gets used.
`NoteTemplate.retiredLabels` lists the dropped headings. `parse()` reports any
note containing one as **non-conforming** so it opens in the raw editor — without
that, the stepper would fold a retired section into its neighbour on the next
save. `tool/migrate_backlog.dart` converts an old export (Settings → Export →
migrate → Settings → Import).
### Images and other attachments
A note never holds attachment bytes, only a line pointing at
`https://kuhy-cloud.duckdns.org/todo-images/<noteId>/<uuid>.<ext>`: an image
as `![](…)`, any other file as `[name](…)` (`lib/images/attachment_ref.dart`
owns the path, `attachment_links.dart` the links), so sync and older builds are
untouched. Anything picked or dropped goes through `AttachmentIngest`: a
JPEG/PNG/GIF/WebP/BMP/TIFF of at most 64 MB is re-encoded (≤2560 px, JPEG q85,
EXIF stripped after applying its rotation — `image_processing.dart`); every
other file, of any size, is kept byte-for-byte. There is deliberately **no
size cap**, so nothing may hold a file in memory: uploads and downloads stream
(`DufsImageClient`), the desktop page POSTs the browser's own Blob with
`fetch` (`file_post_web.dart`), and writes land in a `.tmp` renamed when whole.
`ImageCacheStore` keeps every linked attachment on-device (offline) plus a
`.pending` marker per queued upload, and `reconcile` uploads, prefetches and
evicts (never an empty ref set, never within 10 min; stale `.tmp`s too).
Android talks to dufs directly with the `todo` login's password (Settings →
Cloud images) and opens files with `open_file`; the desktop page never talks
to dufs — the wrapper's `/images/*` routes do, with
`~/.config/dufs/logins/todo.env`, created by
`~/src/dufs-cloud/scripts/add_dufs_login.sh todo /todo-images rw`. The wrapper
serves attachments from the same origin as the notes and the GitHub token, so
only script-free types (raster images, PDF, plain text, audio, video) are shown
inline, always `nosniff`; everything else is a download
(`wrapper_attachment_serving.dart`). Attachment routes run concurrently, the
rest of the wrapper one request at a time. BACKLOG.md rewrites links to
`~/data/cloud/todo-images/…` so an agent can open them.
## Testing
- **The suite must stay quick and fully green.** It is currently **604 tests at
100% line coverage** (3305 lines), ~40s on this machine with
`--concurrency=3` (unbounded concurrency under `capped.sh`'s 4 GiB gets its
test processes SIGTERMed while the wrapper still exits 0 — check the last
line says "All tests passed"). Don't regress either.
(The "~5s" figure this file used to quote had drifted well before the port
guard was added; measure before quoting a new one.)
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
built on `StreamController`s, **not** a real DB. A real `sqlite_crdt` DB
schedules timers that never drain under the widget tester's fake clock
("A Timer is still pending"); the fake avoids that.
- Pitfalls learned the hard way (keep following these):
- **Avoid `pumpAndSettle` when a widget animates forever** — an autofocused
`TextField`'s cursor blink never settles, and an open device-code dialog
keeps a pending poll timer. Use explicit `pump(Duration)` there.
`pumpAndSettle` is fine once nothing is animating (e.g. a route/dialog pop,
or a dialog already showing a static error).
- Inject fakes rather than touching the platform: `MockClient`
(`package:http/testing.dart`) for HTTP; the `file_selector` and
`url_launcher` **platform interfaces** (`MockPlatformInterfaceMixin`) for
the picker/launcher; stub `SystemChannels.platform` for clipboard.
- To exercise the configured sync path, pass a `MockClient` via
`CaptureScreen(httpClient: …)` / `SettingsScreen(httpClient: …)` — the real
`SyncService` then runs without network.
- `getChangeset()` serialises HLCs as `String`; `merge()` needs `Hlc.parse`
and fresh mutable maps (QueryRows are read-only) — see the changeset test.
- Use `// coverage:ignore-line` / `ignore-start`/`ignore-end` only for
genuinely unreachable code (e.g. a private static-only constructor, or a
mobile-only `Platform.isAndroid` branch that can't run on the Linux test
host), with a one-line reason.
## Conventions
- Run `dart format` + `flutter analyze` (clean) before every commit.
- Comments explain intent/trade-offs, not syntax.
- Keep the app buttery-smooth and low on CPU/RAM — it's a quick-capture tool.
- **Every file is at most 250 lines**, source and prose alike. Enforced by a
pre-commit hook (`scripts/check_file_length.sh`, delegating to the shared
gate in `~/src/utils`) and by `.github/workflows/file-length.yml`, so it fails
the commit rather than being a note anyone can ignore. Install the hook on
a fresh clone with `scripts/install_hooks.sh`.
- **Only non-mutating checks go in `.pre-commit-config.yaml`.** pre-commit
stashes unstaged changes and restores them with `git apply`; a hook that
rewrites a tracked file inside that window makes the restore conflict,
which aborts the commit *and drops the developer's uncommitted edit*. That
is why `bump_patch_version.sh` runs from the wrapper hook that
`install_hooks.sh` writes, after pre-commit has exited and only when it
passed — see the comments in both files. There is deliberately no
baseline and no allowlist — split the file instead. Exemptions (generated,
vendored, data files) live with the checker so the gate and the survey
cannot disagree.
- Where a split would otherwise break callers, keep the original path as a
barrel that re-exports the parts (`note_template.dart`,
`firebase_backend.dart`, `note_repository.dart` all do this). Where a
widget and its private `State` must stay one library, use `part` files
(`note_editor_*.dart`, `capture_screen_*.dart`).
## Flutter/Dart AI rules
Upstream's Flutter/Dart guidance used to be pasted in below this line, which
made 85% of this always-loaded file a document nobody edits. It now lives in
`docs/`, linked rather than inlined so the part loaded on every turn stays
about *this repo*:
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
- [State, routing and data](docs/DOCS-flutter-rules-state-and-data.md)
- [Code generation, testing, theming and assets](docs/DOCS-flutter-rules-testing-and-assets.md)
- [UI: theming, layout and overlays](docs/DOCS-flutter-rules-ui.md)
- [Colour, type, documentation and accessibility](docs/DOCS-flutter-rules-design.md)
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
## Driving the app on the phone
Tap and type by label, never by coordinate, with `android_ui` from
`~/src/testsAndMisc` (not copied here):
```bash
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
-s 23181JEGR08034 --display self dump
```
The same driver is the `android-ui` MCP server
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
`.mcp.json`). Tools and error contract:
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.

925
CLAUDE.md
View File

@ -1,925 +0,0 @@
# CLAUDE.md — todo
Offline-first, CRDT-synced notes app. Flutter, targets **Android + web**.
The **desktop app is the web build**, served by a small local wrapper
(`bin/todo_desktop.dart`) and shown in a Chrome `--app` window. Flutter's Linux
embedder was removed: it manages only ~20fps at 4K while the same Dart code in
Chrome sustains ~144fps. See `docs/desktop-performance-findings.md` for the
measurements. Do not re-add `linux/` — `flutter create --platforms linux` would
silently bring the slow path back.
Capture an idea instantly (persisted on every keystroke), browse/filter notes,
and sync peer-to-peer through a GitHub repo used as dumb storage.
- Package name: `todo` (Dart SDK `^3.12.2`).
- Git remote: `origin` → `github.com/kuhyx/todo-app`.
- The note **content** also syncs to a separate private repo `kuhyx/syncs`
(under `todo-sync/`) via the in-app GitHub sync (changeset files); that is
data, not this codebase.
## Git workflow (repo-specific — overrides global rules)
- **Never open pull requests. Always commit and work directly on `main` and
`git push` to `origin/main`.** Do not create feature branches for normal work.
- End commit messages with the standard
`Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>` trailer.
## Commands
- Run tests + coverage: `flutter test --coverage` (suite runs in 1–2min; keep it
quick — see Testing below).
- Coverage summary: `lcov --list coverage/lcov.info`.
- Static analysis: `flutter analyze` (must be clean before committing).
- Format: `dart format lib/ test/`.
- Run the desktop app: `./run.sh` (builds the web bundle, starts the wrapper,
opens Chrome). Mobile: `flutter run` with a connected Android device.
- The wrapper serves on a **fixed** port 8730 with a **fixed** Chrome profile
dir. Both must stay fixed: the GitHub token (`localStorage`) and the notes
(IndexedDB) are keyed by origin and live in that profile, so changing either
silently logs you out and hides your notes. Because the port cannot move,
`lib/desktop/port_guard.dart` decides what to do when it is already taken:
reap a wrapper with no window attached (so an upgrade can't leave you on old
code), join one that still has a window, and refuse to touch anything else.
- Release APK: `flutter build apk --release` (signs with the debug key; debug
builds are janky — always measure smoothness on a release build).
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.
## Architecture
Three layers under `lib/`, each single-purpose:
- `data/` — domain + local storage.
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
- `note_repository.dart`: CRDT storage over `sqlite_crdt`. Schema is at
**version 3** with `onCreate`/`onUpgrade` migrations (v1→v2 adds the
`status` column; v2→v3 backfills legacy priority `0`→medium). Also defines
`NoteFilter` (query / priorities / statuses / created+updated date ranges,
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
`importNotes` (safe newer-wins merge by id).
- `sync/` — GitHub-as-storage sync.
- `sync_service.dart`: each device owns one file
`todo-sync/changesets/<nodeId>.json`
holding its full CRDT changeset. No two devices write the same file ⇒ no
git merge conflicts; convergence is the CRDT layer's job (pull every other
device's changeset and `merge()`, which is commutative + idempotent).
- `github_client.dart`: thin GitHub contents-API client (injectable
`http.Client`). `github_device_auth.dart`: OAuth device flow to mint a
token. `sync_settings.dart`: persisted owner/repo/token/clientId.
- `notes_markdown.dart`: round-trippable single-file export/import format
(HTML-comment `<!-- @note id=… priority=… status=… … -->` markers).
- `ui/` — screens, all take an injected `NoteRepository`.
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
with the structured template; lazy note creation on first keystroke.
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
sheet. **Default view hides Done/Abandoned and shows no filter badge**
(looks unfiltered).
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
Export/Import backup actions.
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
paths and `runApp`.
### Note template (default content of every new note)
`lib/data/note_template.dart` is the **single source of truth** — the stepper,
the editor and the tests are all template-driven, so changing that list changes
every surface. A new note pre-fills a title line plus
`what / where / must / done / verify / read first`.
The set was cut from twelve sections to seven in 2026-07 after auditing 514 real
sessions (`docs/llm-design-spec-audit.md`): `estimate`, `ask`, `nice`, `tech`,
`never` and `depends` were measurably never read, and `verify` was added because
"test it yourself, on the phone" was the single most repeated correction in the
corpus. Do not re-add a section without evidence that it gets used.
`NoteTemplate.retiredLabels` lists the dropped headings. `parse()` reports any
note containing one as **non-conforming** so it opens in the raw editor — without
that, the stepper would fold a retired section into its neighbour on the next
save. `tool/migrate_backlog.dart` converts an old export (Settings → Export →
migrate → Settings → Import).
## Testing
- **The suite must stay quick and fully green.** It is currently **238 tests at
100% line coverage**, running in 1–2min on this machine. Don't regress either.
(The "~5s" figure this file used to quote had drifted well before the port
guard was added; measure before quoting a new one.)
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
built on `StreamController`s, **not** a real DB. A real `sqlite_crdt` DB
schedules timers that never drain under the widget tester's fake clock
("A Timer is still pending"); the fake avoids that.
- Pitfalls learned the hard way (keep following these):
- **Avoid `pumpAndSettle` when a widget animates forever** — an autofocused
`TextField`'s cursor blink never settles, and an open device-code dialog
keeps a pending poll timer. Use explicit `pump(Duration)` there.
`pumpAndSettle` is fine once nothing is animating (e.g. a route/dialog pop,
or a dialog already showing a static error).
- Inject fakes rather than touching the platform: `MockClient`
(`package:http/testing.dart`) for HTTP; the `file_selector` and
`url_launcher` **platform interfaces** (`MockPlatformInterfaceMixin`) for
the picker/launcher; stub `SystemChannels.platform` for clipboard.
- To exercise the configured sync path, pass a `MockClient` via
`CaptureScreen(httpClient: …)` / `SettingsScreen(httpClient: …)` — the real
`SyncService` then runs without network.
- `getChangeset()` serialises HLCs as `String`; `merge()` needs `Hlc.parse`
and fresh mutable maps (QueryRows are read-only) — see the changeset test.
- Use `// coverage:ignore-line` / `ignore-start`/`ignore-end` only for
genuinely unreachable code (e.g. a private static-only constructor, or a
mobile-only `Platform.isAndroid` branch that can't run on the Linux test
host), with a one-line reason.
## Conventions
- Run `dart format` + `flutter analyze` (clean) before every commit.
- Comments explain intent/trade-offs, not syntax.
- Keep the app buttery-smooth and low on CPU/RAM — it's a quick-capture tool.
## Flutter/Dart AI rules
_Appended from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md) via `/home/kuhy/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically to stay current._
## AI rules for Flutter
You are an expert in Flutter and Dart development. Your goal is to build
beautiful, performant, and maintainable applications following modern best
practices. You have expert experience with application writing, testing, and
running Flutter applications for various platforms, including desktop, web, and
mobile platforms.
### Interaction Guidelines
* **User Persona:** Assume the user is familiar with programming concepts but
may be new to Dart.
* **Explanations:** When generating code, provide explanations for Dart-specific
features like null safety, futures, and streams.
* **Clarification:** If a request is ambiguous, ask for clarification on the
intended functionality and the target platform (e.g., command-line, web,
server).
* **Dependencies:** When suggesting new dependencies from `pub.dev`, explain
their benefits.
* **Formatting:** Use the `dart_format` tool to ensure consistent code
formatting.
* **Fixes:** Use the `dart_fix` tool to automatically fix many common errors,
and to help code conform to configured analysis options.
* **Linting:** Use the Dart linter with a recommended set of rules to catch
common issues. Use the `analyze_files` tool to run the linter.
### Project Structure
* **Standard Structure:** Assumes a standard Flutter project structure with
`lib/main.dart` as the primary application entry point.
### Flutter style guide
* **SOLID Principles:** Apply SOLID principles throughout the codebase.
* **Concise and Declarative:** Write concise, modern, technical Dart code.
Prefer functional and declarative patterns.
* **Composition over Inheritance:** Favor composition for building complex
widgets and logic.
* **Immutability:** Prefer immutable data structures. Widgets (especially
`StatelessWidget`) should be immutable.
* **State Management:** Separate ephemeral state and app state. Use a state
management solution for app state to handle the separation of concerns.
* **Widgets are for UI:** Everything in Flutter's UI is a widget. Compose
complex UIs from smaller, reusable widgets.
* **Navigation:** Use a modern routing package like `auto_route` or `go_router`.
For more guidelines around navigation, see the section on [routing](#routing).
### Package Management
* **Pub Tool:** To manage packages, use the `pub` tool, if available.
* **External Packages:** If a new feature requires an external package, use the
`pub_dev_search` tool, if it is available. Otherwise, identify the most
suitable and stable package from pub.dev.
* **Adding Dependencies:** To add a regular dependency, use the `pub` tool, if
it is available. Otherwise, run `flutter pub add <package_name>`.
* **Adding Dev Dependencies:** To add a development dependency, use the `pub`
tool, if it is available, with `dev:<package name>`. Otherwise, run `flutter
pub add dev:<package_name>`.
* **Dependency Overrides:** To add a dependency override, use the `pub` tool, if
it is available, with `override:<package name>:1.0.0`. Otherwise, run `flutter
pub add override:<package_name>:1.0.0`.
* **Removing Dependencies:** To remove a dependency, use the `pub` tool, if it
is available. Otherwise, run `dart pub remove <package_name>`.
### Code Quality
* **Code structure:** Adhere to maintainable code structure and separation of
concerns (e.g., UI logic separate from business logic).
* **Naming conventions:** Avoid abbreviations and use meaningful, consistent,
descriptive names for variables, functions, and classes.
* **Conciseness:** Write code that is as short as it can be while remaining
clear.
* **Simplicity:** Write straightforward code. Code that is clever or
obscure is difficult to maintain.
* **Error Handling:** Anticipate and handle potential errors. Don't let your
code fail silently.
* **Styling:**
* Line length: Lines should be 80 characters or fewer.
* Use `PascalCase` for classes, `camelCase` for
members/variables/functions/enums, and `snake_case` for files.
* **Functions:**
* Keep functions short and with a single purpose.
Strive for less than 20 lines.
* **Testing:** Write code with testing in mind. Use the `file`, `process`, and
`platform` packages, if appropriate, so you can inject in-memory and fake
versions of the objects.
* **Logging:** Use the `logging` package instead of `print`.
### Dart Best Practices
* **Effective Dart:** Follow the official Effective Dart guidelines
(https://dart.dev/effective-dart)
* **Class Organization:** Define related classes within the same library file.
For large libraries, export smaller, private libraries from a single top-level
library.
* **Library Organization:** Group related libraries in the same folder.
* **API Documentation:** Add documentation comments to all public APIs,
including classes, constructors, methods, and top-level functions.
* **Comments:** Write clear comments for complex or non-obvious code. Avoid
over-commenting.
* **Trailing Comments:** Don't add trailing comments.
* **Async/Await:** Ensure proper use of `async`/`await` for asynchronous
operations with robust error handling.
* Use `Future`s, `async`, and `await` for asynchronous operations.
* Use `Stream`s for sequences of asynchronous events.
* **Null Safety:** Write code that is soundly null-safe. Leverage Dart's null
safety features. Avoid `!` unless the value is guaranteed to be non-null.
* **Pattern Matching:** Use pattern matching features where they simplify the
code.
* **Records:** Use records to return multiple types in situations where defining
an entire class is cumbersome.
* **Switch Statements:** Prefer using exhaustive `switch` statements or
expressions, which don't require `break` statements.
* **Exception Handling:** Use `try-catch` blocks for handling exceptions, and
use exceptions appropriate for the type of exception. Use custom exceptions
for situations specific to your code.
* **Arrow Functions:** Use arrow syntax for simple one-line functions.
### Flutter Best Practices
* **Immutability:** Widgets (especially `StatelessWidget`) are immutable; when
the UI needs to change, Flutter rebuilds the widget tree.
* **Composition:** Prefer composing smaller widgets over extending existing
ones. Use this to avoid deep widget nesting.
* **Private Widgets:** Use small, private `Widget` classes instead of private
helper methods that return a `Widget`.
* **Build Methods:** Break down large `build()` methods into smaller, reusable
private Widget classes.
* **List Performance:** Use `ListView.builder` or `SliverList` for long lists to
create lazy-loaded lists for performance.
* **Isolates:** Use `compute()` to run expensive calculations in a separate
isolate to avoid blocking the UI thread, such as JSON parsing.
* **Const Constructors:** Use `const` constructors for widgets and in `build()`
methods whenever possible to reduce rebuilds.
* **Build Method Performance:** Avoid performing expensive operations, like
network calls or complex computations, directly within `build()` methods.
### API Design Principles
When building reusable APIs, such as a library, follow these principles.
* **Consider the User:** Design APIs from the perspective of the person who will
be using them. The API should be intuitive and easy to use correctly.
* **Documentation is Essential:** Good documentation is a part of good API
design. It should be clear, concise, and provide examples.
### Application Architecture
* **Separation of Concerns:** Aim for separation of concerns similar to MVC/MVVM, with defined Model,
View, and ViewModel/Controller roles.
* **Logical Layers:** Organize the project into logical layers:
* Presentation (widgets, screens)
* Domain (business logic classes)
* Data (model classes, API clients)
* Core (shared classes, utilities, and extension types)
* **Feature-based Organization:** For larger projects, organize code by feature,
where each feature has its own presentation, domain, and data subfolders. This
improves navigability and scalability.
### Lint Rules
Include the package in the `analysis_options.yaml` file. Use the following
`analysis_options.yaml` file as a starting point:
```yaml
include: package:flutter_lints/flutter.yaml
linter:
rules:
# Add additional lint rules here:
# avoid_print: false
# prefer_single_quotes: true
```
#### State Management
* **Built-in Solutions:** Prefer Flutter's built-in state management solutions.
Do not use a third-party package unless explicitly requested.
* **Streams:** Use `Streams` and `StreamBuilder` for handling a sequence of
asynchronous events.
* **Futures:** Use `Futures` and `FutureBuilder` for handling a single
asynchronous operation that will complete in the future.
* **ValueNotifier:** Use `ValueNotifier` with `ValueListenableBuilder` for
simple, local state that involves a single value.
```dart
// Define a ValueNotifier to hold the state.
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
// Use ValueListenableBuilder to listen and rebuild.
ValueListenableBuilder<int>(
valueListenable: _counter,
builder: (context, value, child) {
return Text('Count: $value');
},
);
```
* **ChangeNotifier:** For state that is more complex or shared across multiple
widgets, use `ChangeNotifier`.
* **ListenableBuilder:** Use `ListenableBuilder` to listen to changes from a
`ChangeNotifier` or other `Listenable`.
* **MVVM:** When a more robust solution is needed, structure the app using the
Model-View-ViewModel (MVVM) pattern.
* **Dependency Injection:** Use simple manual constructor dependency injection
to make a class's dependencies explicit in its API, and to manage dependencies
between different layers of the application.
* **Provider:** If a dependency injection solution beyond manual constructor
injection is explicitly requested, `provider` can be used to make services,
repositories, or complex state objects available to the UI layer without tight
coupling (note: this document generally defaults against third-party packages
for state management unless explicitly requested).
#### Data Flow
* **Data Structures:** Define data structures (classes) to represent the data
used in the application.
* **Data Abstraction:** Abstract data sources (e.g., API calls, database
operations) using Repositories/Services to promote testability.
#### Routing
* **GoRouter:** Use the `go_router` package for declarative navigation, deep
linking, and web support.
* **GoRouter Setup:** To use `go_router`, first add it to your `pubspec.yaml`
using the `pub` tool's `add` command.
```dart
// 1. Add the dependency
// flutter pub add go_router
// 2. Configure the router
final GoRouter _router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'details/:id', // Route with a path parameter
builder: (context, state) {
final String id = state.pathParameters['id']!;
return DetailScreen(id: id);
},
),
],
),
],
);
// 3. Use it in your MaterialApp
MaterialApp.router(
routerConfig: _router,
);
```
* **Authentication Redirects:** Configure `go_router`'s `redirect` property to
handle authentication flows, ensuring users are redirected to the login screen
when unauthorized, and back to their intended destination after successful
login.
* **Navigator:** Use the built-in `Navigator` for short-lived screens that do
not need to be deep-linkable, such as dialogs or temporary views.
```dart
// Push a new screen onto the stack
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const DetailsScreen()),
);
// Pop the current screen to go back
Navigator.pop(context);
```
#### Data Handling & Serialization
* **JSON Serialization:** Use `json_serializable` and `json_annotation` for
parsing and encoding JSON data.
* **Field Renaming:** When encoding data, use `fieldRename: FieldRename.snake`
to convert Dart's camelCase fields to snake_case JSON keys.
```dart
// In your model file
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(fieldRename: FieldRename.snake)
class User {
final String firstName;
final String lastName;
User({required this.firstName, required this.lastName});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
```
#### Logging
* **Structured Logging:** Use the `log` function from `dart:developer` for
structured logging that integrates with Dart DevTools.
```dart
import 'dart:developer' as developer;
// For simple messages
developer.log('User logged in successfully.');
// For structured error logging
try {
// ... code that might fail
} catch (e, s) {
developer.log(
'Failed to fetch data',
name: 'myapp.network',
level: 1000, // SEVERE
error: e,
stackTrace: s,
);
}
```
### Code Generation
* **Build Runner:** If the project uses code generation, ensure that
`build_runner` is listed as a dev dependency in `pubspec.yaml`.
* **Code Generation Tasks:** Use `build_runner` for all code generation tasks,
such as for `json_serializable`.
* **Running Build Runner:** After modifying files that require code generation,
run the build command:
```shell
dart run build_runner build --delete-conflicting-outputs
```
### Testing
* **Running Tests:** To run tests, use the `run_tests` tool if it is available,
otherwise use `flutter test`.
* **Unit Tests:** Use `package:test` for unit tests.
* **Widget Tests:** Use `package:flutter_test` for widget tests.
* **Integration Tests:** Use `package:integration_test` for integration tests.
* **Assertions:** Prefer using `package:checks` for more expressive and readable
assertions over the default `matchers`.
#### Testing Best practices
* **Convention:** Follow the Arrange-Act-Assert (or Given-When-Then) pattern.
* **Unit Tests:** Write unit tests for domain logic, data layer, and state
management.
* **Widget Tests:** Write widget tests for UI components.
* **Integration Tests:** For broader application validation, use integration
tests to verify end-to-end user flows.
* **integration_test package:** Use the `integration_test` package from the
Flutter SDK for integration tests. Add it as a `dev_dependency` in
`pubspec.yaml` by specifying `sdk: flutter`.
* **Mocks:** Prefer fakes or stubs over mocks. If mocks are absolutely
necessary, use `mockito` or `mocktail` to create mocks for dependencies. While
code generation is common for state management (e.g., with `freezed`), try to
avoid it for mocks.
* **Coverage:** Aim for high test coverage.
### Visual Design & Theming
* **UI Design:** Build beautiful and intuitive user interfaces that follow
modern design guidelines.
* **Responsiveness:** Ensure the app is mobile responsive and adapts to
different screen sizes, working perfectly on mobile and web.
* **Navigation:** If there are multiple pages for the user to interact with,
provide an intuitive and easy navigation bar or controls.
* **Typography:** Stress and emphasize font sizes to ease understanding, e.g.,
hero text, section headlines, list headlines, keywords in paragraphs.
* **Background:** Keep backgrounds flat and simple — no noise texture or
gradients. Follow the `unified-design-system` skill (safe-design-rules
rule 17: simple-on-complex); let content and typography carry visual
interest instead of background texture.
* **Shadows:** Follow the `unified-design-system` skill's shadow policy: no
shadows at all in dark UI (differentiate elevation with lighter surface
fills, not shadows); in light UI, shadows are for floating/overlay
elements only (menus, dialogs), never for inline cards, and never mixed
with a border on the same surface.
* **Icons:** Incorporate icons to enhance the user’s understanding and the
logical navigation of the app.
* **Interactive Elements:** Buttons/controls signal state via color and fill
changes, not a "glow" shadow — one depth technique per surface, per
`unified-design-system`.
#### Theming
* **Centralized Theme:** Define a centralized `ThemeData` object to ensure a
consistent application-wide style.
* **Light and Dark Themes:** Implement support for both light and dark themes,
ideal for a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`,
`ThemeMode.system`).
* **Color Scheme Generation:** Do NOT use `ColorScheme.fromSeed` for this
app's palette — it can't reproduce hand-picked values exactly. Build
`ThemeData` from explicit `ColorScheme.dark(...)`/`.light(...)` using the
frozen, identical-everywhere tokens in the `unified-design-system` skill
(`~/.claude/skills/unified-design-system/references/tokens.md`).
```dart
final ThemeData lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
// ... other theme properties
);
```
* **Color Palette:** Include a wide range of color concentrations and hues in
the palette to create a vibrant and energetic look and feel.
* **Component Themes:** Use specific theme properties (e.g., `appBarTheme`,
`elevatedButtonTheme`) to customize the appearance of individual Material
components.
* **Custom Fonts:** For custom fonts, use the `google_fonts` package. Define a
`TextTheme` to apply fonts consistently.
```dart
// 1. Add the dependency
// flutter pub add google_fonts
// 2. Define a TextTheme with a custom font
final TextTheme appTextTheme = TextTheme(
displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold),
titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500),
bodyMedium: GoogleFonts.openSans(fontSize: 14),
);
```
#### Assets and Images
* **Image Guidelines:** If images are needed, make them relevant and meaningful,
with appropriate size, layout, and licensing (e.g., freely available). Provide
placeholder images if real ones are not available.
* **Asset Declaration:** Declare all asset paths in your `pubspec.yaml` file.
```yaml
flutter:
uses-material-design: true
assets:
- assets/images/
```
* **Local Images:** Use `Image.asset` for local images from your asset
bundle.
```dart
Image.asset('assets/images/placeholder.png')
```
* **Network images:** Use NetworkImage for images loaded from the network.
* **Cached images:** For cached images, use NetworkImage a package like
`cached_network_image`.
* **Custom Icons:** Use `ImageIcon` to display an icon from an `ImageProvider`,
useful for custom icons not in the `Icons` class.
* **Network Images:** Use `Image.network` to display images from a URL, and
always include `loadingBuilder` and `errorBuilder` for a better user
experience.
```dart
// When using network images, always provide an errorBuilder.
Image.network(
'https://picsum.photos/200/300',
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(child: CircularProgressIndicator());
},
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.error);
},
)
```
### UI Theming and Styling Code
* **Responsiveness:** Use `LayoutBuilder` or `MediaQuery` to create responsive
UIs.
* **Text:** Use `Theme.of(context).textTheme` for text styles.
* **Text Fields:** Configure `textCapitalization`, `keyboardType`, and
`placeholder`.
### Material Theming Best Practices
#### Embrace `ThemeData` and Material 3
* **Use `ColorScheme.fromSeed()`:** Use this to generate a complete, harmonious
color palette for both light and dark modes from a single seed color.
* **Define Light and Dark Themes:** Provide both `theme` and `darkTheme` to your
`MaterialApp` to support system brightness settings seamlessly.
* **Centralize Component Styles:** Customize specific component themes (e.g.,
`elevatedButtonTheme`, `cardTheme`, `appBarTheme`) within `ThemeData` to
ensure consistency.
* **Dark/Light Mode and Theme Toggle:** Implement support for both light and
dark themes using `theme` and `darkTheme` properties of `MaterialApp`. The
`themeMode` property can be dynamically controlled (e.g., via a
`ChangeNotifierProvider`) to allow for toggling between `ThemeMode.light`,
`ThemeMode.dark`, or `ThemeMode.system`.
```dart
// main.dart
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
textTheme: const TextTheme(
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.dark,
),
),
home: const MyHomePage(),
);
```
#### Implement Design Tokens with `ThemeExtension`
For custom styles that aren't part of the standard `ThemeData`, use
`ThemeExtension` to define reusable design tokens.
* **Create a Custom Theme Extension:** Define a class that extends
`ThemeExtension<T>` and include your custom properties.
* **Implement `copyWith` and `lerp`:** These methods are required for the
extension to work correctly with theme transitions.
* **Register in `ThemeData`:** Add your custom extension to the `extensions`
list in your `ThemeData`.
* **Access Tokens in Widgets:** Use `Theme.of(context).extension<MyColors>()!`
to access your custom tokens.
```dart
// 1. Define the extension
@immutable
class MyColors extends ThemeExtension<MyColors> {
const MyColors({required this.success, required this.danger});
final Color? success;
final Color? danger;
@override
ThemeExtension<MyColors> copyWith({Color? success, Color? danger}) {
return MyColors(success: success ?? this.success, danger: danger ?? this.danger);
}
@override
ThemeExtension<MyColors> lerp(ThemeExtension<MyColors>? other, double t) {
if (other is! MyColors) return this;
return MyColors(
success: Color.lerp(success, other.success, t),
danger: Color.lerp(danger, other.danger, t),
);
}
}
// 2. Register it in ThemeData
theme: ThemeData(
extensions: const <ThemeExtension<dynamic>>[
MyColors(success: Colors.green, danger: Colors.red),
],
),
// 3. Use it in a widget
Container(
color: Theme.of(context).extension<MyColors>()!.success,
)
```
#### Styling with `WidgetStateProperty`
* **`WidgetStateProperty.resolveWith`:** Provide a function that receives a
`Set<WidgetState>` and returns the appropriate value for the current state.
* **`WidgetStateProperty.all`:** A shorthand for when the value is the same for
all states.
```dart
// Example: Creating a button style that changes color when pressed.
final ButtonStyle myButtonStyle = ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color>(
(Set<WidgetState> states) {
if (states.contains(WidgetState.pressed)) {
return Colors.green; // Color when pressed
}
return Colors.red; // Default color
},
),
);
```
### Layout Best Practices
#### Building Flexible and Overflow-Safe Layouts
##### For Rows and Columns
* **`Expanded`:** Use to make a child widget fill the remaining available space
along the main axis.
* **`Flexible`:** Use when you want a widget to shrink to fit, but not
necessarily grow. Don't combine `Flexible` and `Expanded` in the same `Row` or
`Column`.
* **`Wrap`:** Use when you have a series of widgets that would overflow a `Row`
or `Column`, and you want them to move to the next line.
##### For General Content
* **`SingleChildScrollView`:** Use when your content is intrinsically larger
than the viewport, but is a fixed size.
* **`ListView` / `GridView`:** For long lists or grids of content, always use a
builder constructor (`.builder`).
* **`FittedBox`:** Use to scale or fit a single child widget within its parent.
* **`LayoutBuilder`:** Use for complex, responsive layouts to make decisions
based on the available space.
#### Layering Widgets with Stack
* **`Positioned`:** Use to precisely place a child within a `Stack` by anchoring it to the edges.
* **`Align`:** Use to position a child within a `Stack` using alignments like `Alignment.center`.
#### Advanced Layout with Overlays
* **`OverlayPortal`:** Use this widget to show UI elements (like custom
dropdowns or tooltips) "on top" of everything else. It manages the
`OverlayEntry` for you.
```dart
class MyDropdown extends StatefulWidget {
const MyDropdown({super.key});
@override
State<MyDropdown> createState() => _MyDropdownState();
}
class _MyDropdownState extends State<MyDropdown> {
final _controller = OverlayPortalController();
@override
Widget build(BuildContext context) {
return OverlayPortal(
controller: _controller,
overlayChildBuilder: (BuildContext context) {
return const Positioned(
top: 50,
left: 10,
child: Card(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text('I am an overlay!'),
),
),
);
},
child: ElevatedButton(
onPressed: _controller.toggle,
child: const Text('Toggle Overlay'),
),
);
}
}
```
### Color Scheme Best Practices
#### Contrast Ratios
* **WCAG Guidelines:** Aim to meet the Web Content Accessibility Guidelines
(WCAG) 2.1 standards.
* **Minimum Contrast:**
* **Normal Text:** A contrast ratio of at least **4.5:1**.
* **Large Text:** (18pt or 14pt bold) A contrast ratio of at least **3:1**.
#### Palette Selection
* **Primary, Secondary, and Accent:** Define a clear color hierarchy.
* **The 60-30-10 Rule:** A classic design rule for creating a balanced color scheme.
* **60%** Primary/Neutral Color (Dominant)
* **30%** Secondary Color
* **10%** Accent Color
#### Complementary Colors
* **Use with Caution:** They can be visually jarring if overused.
* **Best Use Cases:** They are excellent for accent colors to make specific
elements pop, but generally poor for text and background pairings as they can
cause eye strain.
#### Example Palette
* **Primary:** #0D47A1 (Dark Blue)
* **Secondary:** #1976D2 (Medium Blue)
* **Accent:** #FFC107 (Amber)
* **Neutral/Text:** #212121 (Almost Black)
* **Background:** #FEFEFE (Almost White)
### Font Best Practices
#### Font Selection
* **Limit Font Families:** Stick to one or two font families for the entire
application.
* **Prioritize Legibility:** Choose fonts that are easy to read on screens of
all sizes. Sans-serif fonts are generally preferred for UI body text.
* **System Fonts:** Consider using platform-native system fonts.
* **Google Fonts:** For a wide selection of open-source fonts, use the
`google_fonts` package.
#### Hierarchy and Scale
* **Establish a Scale:** Define a set of font sizes for different text elements
(e.g., headlines, titles, body text, captions).
* **Use Font Weight:** Differentiate text effectively using font weights.
* **Color and Opacity:** Use color and opacity to de-emphasize less important
text.
#### Readability
* **Line Height (Leading):** Set an appropriate line height, typically **1.4x to
1.6x** the font size.
* **Line Length:** For body text, aim for a line length of **45-75 characters**.
* **Avoid All Caps:** Do not use all caps for long-form text.
#### Example Typographic Scale
```dart
// In your ThemeData
textTheme: const TextTheme(
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
titleLarge: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
bodyLarge: TextStyle(fontSize: 16.0, height: 1.5),
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
labelSmall: TextStyle(fontSize: 11.0, color: Colors.grey),
),
```
### Documentation
* **`dartdoc`:** Write `dartdoc`-style comments for all public APIs.
#### Documentation Philosophy
* **Comment wisely:** Use comments to explain why the code is written a certain
way, not what the code does. The code itself should be self-explanatory.
* **Document for the user:** Write documentation with the reader in mind. If you
had a question and found the answer, add it to the documentation where you
first looked. This ensures the documentation answers real-world questions.
* **No useless documentation:** If the documentation only restates the obvious
from the code's name, it's not helpful. Good documentation provides context
and explains what isn't immediately apparent.
* **Consistency is key:** Use consistent terminology throughout your
documentation.
#### Commenting Style
* **Use `///` for doc comments:** This allows documentation generation tools to
pick them up.
* **Start with a single-sentence summary:** The first sentence should be a
concise, user-centric summary ending with a period.
* **Separate the summary:** Add a blank line after the first sentence to create
a separate paragraph. This helps tools create better summaries.
* **Avoid redundancy:** Don't repeat information that's obvious from the code's
context, like the class name or signature.
* **Don't document both getter and setter:** For properties with both, only
document one. The documentation tool will treat them as a single field.
#### Writing Style
* **Be brief:** Write concisely.
* **Avoid jargon and acronyms:** Don't use abbreviations unless they are widely
understood.
* **Use Markdown sparingly:** Avoid excessive markdown and never use HTML for
formatting.
* **Use backticks for code:** Enclose code blocks in backtick fences, and
specify the language.
#### What to Document
* **Public APIs are a priority:** Always document public APIs.
* **Consider private APIs:** It's a good idea to document private APIs as well.
* **Library-level comments are helpful:** Consider adding a doc comment at the
library level to provide a general overview.
* **Include code samples:** Where appropriate, add code samples to illustrate usage.
* **Explain parameters, return values, and exceptions:** Use prose to describe
what a function expects, what it returns, and what errors it might throw.
* **Place doc comments before annotations:** Documentation should come before
any metadata annotations.
### Accessibility (A11Y)
Implement accessibility features to empower all users, assuming a wide variety
of users with different physical abilities, mental abilities, age groups,
education levels, and learning styles.
* **Color Contrast:** Ensure text has a contrast ratio of at least **4.5:1**
against its background.
* **Dynamic Text Scaling:** Test your UI to ensure it remains usable when users
increase the system font size.
* **Semantic Labels:** Use the `Semantics` widget to provide clear, descriptive
labels for UI elements.
* **Screen Reader Testing:** Regularly test your app with TalkBack (Android) and
VoiceOver (iOS).

1
CLAUDE.md Symbolic link
View File

@ -0,0 +1 @@
AGENTS.md

View File

@ -1,89 +0,0 @@
# Design audit — todo
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
Report only — nothing in this repo was changed by the audit itself.
## Flutter app (lib/)
Theme entry point: `lib/main.dart:36-39` — a single inline `ThemeData` with
`ColorScheme.fromSeed(seedColor: Colors.deepPurple)` and `useMaterial3: true`.
No dedicated theme file, no `darkTheme`, no `textTheme`/component-theme
overrides, no custom shadows or corner radii anywhere in `lib/` (confirmed by
grepping for `BoxShadow`, `elevation`, `BorderRadius`, `Card(` — zero hits
outside framework defaults). This means almost every token rule is satisfied
*by deferring to Material 3's generated palette/type scale*, which is itself a
coherent, deliberately-designed system — that counts as Pass, not as an
absence-of-system finding (contrast the web/Tkinter case where hardcoded
per-file values have no source of truth at all).
### Violations
- **Rule 4 (everything deliberate) / color consistency** — `lib/ui/settings_screen.dart:410` —
`Text(_error!, style: const TextStyle(color: Colors.red))` hardcodes a raw
`Colors.red` instead of the theme's error color. Every other error-state
text in the app uses `theme.colorScheme.error`
(`lib/ui/capture_screen.dart:522`, `lib/ui/notes_list_screen.dart:375`) —
this is the one place that breaks the pattern → change to
`Theme.of(context).colorScheme.error`.
- **Rule 11 (mathematically related measurements)** — the app's spacing is
overwhelmingly on a 4px scale (4/8/12/16/20/24/96 all appear repeatedly),
but a few values break it: `SizedBox(height: 6)` at
`lib/ui/notes_list_screen.dart:411,574,646`; `SizedBox(height: 10)` at
`lib/ui/markdown_view.dart:29`; `EdgeInsets.only(top: 8, bottom: 2)` /
`EdgeInsets.only(bottom: 4)` / `EdgeInsets.only(left: 4, top: 2)` at
`lib/ui/markdown_view.dart:35,49,78` (the `2`s). Round these to the nearest
4px step (6→8, 10→8 or 12, 2→4) for consistency.
- **Rule 21 (line length ~70 chars)** — `lib/ui/markdown_view.dart` (the
rendered-note view) and the raw-mode `TextField` in
`lib/ui/note_editor.dart:520-535` have no max-width constraint; both sit
directly in a `SingleChildScrollView`/`Expanded` that fills the available
width. Per this repo's own `CLAUDE.md`, the desktop build is a Chrome
`--app` window (potentially 4K), so body text lines run the full window
width, far past the 60-80 char readable range. Constrain text columns with
a `ConstrainedBox(maxWidth: ~640)` (or similar) centered in the available
space on wide viewports; mobile widths are already narrow enough to be fine.
### Pass (defers to Material 3 defaults from `main.dart:36-39`, or otherwise verified)
- **Rule 1** (near-black/near-white) — M3's generated tonal palette, not pure black/white.
- **Rule 2** (saturate neutrals) — M3's seed-derived neutrals carry the seed hue.
- **Rule 3** (high contrast for important elements) — `FilledButton`/`IconButton` get M3's on-primary contrast automatically.
- **Rule 6** (letter-spacing/line-height by size) — M3 `TextTheme` scale.
- **Rule 7** (container border contrast) — `OutlineInputBorder()` used throughout (e.g. `lib/ui/settings_screen.dart:244,252,268,278`) resolves via theme, no custom borders.
- **Rule 8** (align with something else) — screen-level body padding is a consistent `EdgeInsets.all(16)` across `lib/ui/capture_screen.dart:451`, `lib/ui/note_detail_screen.dart:67`, `lib/ui/settings_screen.dart:221`.
- **Rule 9** (distinct brightness per palette color) — M3 tonal palette assigns each role a distinct tone.
- **Rule 10** (warm OR cool, not both) — single seed color (`Colors.deepPurple`) drives the whole palette.
- **Rule 14** (space between high-contrast points) — standard Material component spacing, no bounding-box vs. visual-edge mismatches found.
- **Rule 17** (simple on complex) — all surfaces are plain `Scaffold`/`ListView` backgrounds, no background imagery/texture.
- **Rule 19** (outer padding ≥ inner padding) — e.g. `lib/ui/settings_screen.dart:318-331` (Export/Import button row: 12px gap between buttons) sits inside the screen's 16px outer padding; same pattern in `capture_screen.dart`'s priority/status row (12px gap inside 16px body padding).
- **Rule 20** (body text ≥16px) — `bodyLarge` (16px, M3 default) is used for all primary editable/read text (`lib/ui/note_editor.dart:528`, `lib/ui/markdown_view.dart:82-95`); `bodySmall` (12px) is reserved for secondary captions/timestamps only (`lib/ui/capture_screen.dart:511`, `lib/ui/settings_screen.dart:231`), which is the sanctioned M3 caption use, not body text.
- **Rule 22** (button padding horizontal = 2x vertical) — no custom `ButtonStyle` padding overrides found; `FilledButton`/`OutlinedButton` use M3 defaults, which follow this ratio.
- **Rule 23** (two typefaces max) — single default Material/Roboto family; `pubspec.yaml` declares no custom fonts, no `google_fonts` dependency.
- **Rule 25** (avoid adjacent hard divides) — the one `Divider` in the list (`lib/ui/notes_list_screen.dart:232`, `height: 1`) separates list rows only, no stacked borders; the settings-screen `Divider()` (`lib/ui/settings_screen.dart:308`) has 8-24px spacing on both sides, not adjacent to another edge.
- **Rule 27** (don't mix depth techniques) — no custom shadow/elevation overrides anywhere in `lib/`; consistent flat M3 default depth throughout.
- **Rule 28** (icon contrast vs. text) — icons use the default M3 `IconTheme` (tied to `onSurfaceVariant`-class roles), no hardcoded full-contrast icon colors placed next to text were found.
### Not applicable
- **Rule 5** (optical alignment) — no custom-drawn shapes/icons with off-center mass; all icons are stock `Icons.*` glyphs, whose optical centering Material already handles.
- **Rule 12** (order by visual weight) — standard `AppBar` + list/form layouts, not a composition with deliberately varied visual weights to order.
- **Rule 13** (12-column grid) — single-column mobile/narrow-desktop layouts throughout; no multi-column grid exists to check.
- **Rule 15** (closer elements lighter, light+dark) — no custom z-stacked/elevated surfaces with tuned lightness, and no `darkTheme` exists to check the dark-mode half of this rule.
- **Rule 16** (shadow blur ≈ 2x distance) — zero custom `BoxShadow` usage in the codebase (confirmed by grep); nothing to check.
- **Rule 18** (container brightness limits, light/dark) — no custom nested-container brightness steps defined; M3 default surface tones apply, and there is no dark theme to check the 12%-dark-interface half.
- **Rule 24** (nest corners properly) — no custom corner radii anywhere; all components use M3 default shapes.
- **Rule 26** (no shadows in dark interfaces) — no dark theme exists, and no shadows exist in light mode either, so this rule has nothing to trigger on.
### Notes
- No dedicated theme file exists (`ThemeData` is inline in `lib/main.dart`,
32 `.dart` files total) — this is fine at the current size but worth
extracting to `lib/ui/theme.dart` if the theme grows beyond the current
3-line `ThemeData(...)`.
- No `darkTheme` is provided. The 28 rules don't mandate one, so its absence
is not a violation — but if a dark theme is added later, re-check rules 15,
18, and 26 (shadow/lightness/brightness-limit rules only bite once a dark
surface exists).
- The single hardcoded-color violation (`Colors.red`) is also the app's only
spot where a raw `Colors.*` constant appears outside `main.dart`'s seed —
fixing it removes the last non-theme-derived color reference in the app.

View File

@ -1,44 +0,0 @@
# Migration: `sqlite_crdt` → shared `crdt_sync`
todo's note storage and sync were moved off `sqlite_crdt` onto the shared
[`crdt_sync`](https://github.com/kuhyx/utils/tree/main/crdt_sync_dart) library
(pinned tag `crdt_sync_dart-v0.3.0`), so every companion app now syncs through
one library.
## What changed
- **Storage:** `NoteRepository` is backed by `crdt_sync`'s `LogStore` (a
`Log = Map<String, Record>` persisted as JSON). Each `Note` is stored *as* a
`Record` (per-field last-writer-wins + a sticky tombstone), so the on-disk
log **is** the sync wire format — no separate adapter. Filtering/sorting run
in Dart over the in-memory log.
- **Sync:** `SyncService` pushes each device's `Log` to
`todo-sync/notes/<nodeId>.json` in `kuhyx/syncs` (new dir; the old
`changesets/` format is incompatible, so it's a clean cutover). It uses
`crdt_sync`'s `GitHubClient` + `logToJson`/`logFromJson`.
- **Client:** todo's local `lib/sync/github_client.dart` was deleted; it now
uses `crdt_sync`'s `GitHubClient` (which gained `canAccessRepo()` +
`deleteFile()` in v0.3.0). `putFileText` self-resolves the file sha, so the
old SHA-tracking is gone.
## The one-time on-device migration
`NoteRepository.open()` migrates a pre-existing `sqlite_crdt` DB into the log on
first launch, guarded by a persisted `crdt.migratedFromSqlite` flag. Verified
on-device: a real 27-note backlog (+5 tombstones) migrated intact.
`sqlite_crdt` is **retained as a dependency** only to read that legacy DB during
migration — the old `todo.db` is left untouched as a safety net. Remove the dep
in a later cleanup once every device is known-migrated.
## Surprises / non-obvious decisions
- **Seed HLCs from each note's `updatedAt`, not "now".** Two devices migrate
independently; stamping migration-time "now" would let per-field LWW resolve
a pre-cutover edit arbitrarily. Seeding from `updatedAt` keeps
last-real-edit-wins across the cutover.
- **Reuse the legacy `sqlite_crdt` node id** (persisted in prefs) so a device
keeps its `devices/<id>` identity and devices still converge.
- **`watchNotes`/`watchCount` seed in `onListen`**, not lazily in an `async*`
body — otherwise a write between `listen()` and the first generator tick
swallows the initial snapshot.

View File

@ -15,3 +15,40 @@ A few resources to get you started if this is your first Flutter project:
For help getting started with Flutter development, view the For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials, [online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference. samples, guidance on mobile development, and a full API reference.
## Headless note CLI
`bin/todo_note.dart` adds, lists, reads and deletes notes from the PC without
the app, as one more sync node (own `node_id` and CRDT log under
`$XDG_DATA_HOME/todo-cli`, or `~/.local/share/todo-cli`). It needs the desktop
Firebase session at `~/.config/todo/firebase_auth.json` (seed it with
`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app todo`).
```sh
dart run bin/todo_note.dart --text "Title
body" --priority high --status in_progress # prints the new note id
echo "Title" | dart run bin/todo_note.dart # text from stdin
dart run bin/todo_note.dart --list # id, priority, status, title
dart run bin/todo_note.dart --get <id> # full note
dart run bin/todo_note.dart --delete <id>
```
`--list` and `--get` never push; `--data-dir <dir>` selects a throwaway node.
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.
All logic is in `lib/cli/` (tested in `test/cli/`); `--help` lists every flag.
## Driving the app on the phone
Tap and type by label, never by coordinate, with `android_ui` from
`~/src/testsAndMisc` (not copied here):
```bash
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
-s 23181JEGR08034 --display self dump
```
The same driver is the `android-ui` MCP server
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
`.mcp.json`). Tools and error contract:
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.

View File

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

View File

@ -18,7 +18,12 @@ val keystoreProperties = Properties().apply {
android { android {
namespace = "dev.kuhy.todo" namespace = "dev.kuhy.todo"
compileSdk = flutter.compileSdkVersion // Pinned above `flutter.compileSdkVersion` (36 on Flutter 3.47.2):
// flutter_secure_storage 11.0.0, which arrives with crdt_sync_flutter
// v0.3.1, publishes AAR metadata demanding API 37 or later. That in
// turn needs AGP > 9.1.0, which needs Gradle >= 9.5.0 -- see
// settings.gradle.kts and gradle-wrapper.properties.
compileSdk = 37
ndkVersion = flutter.ndkVersion ndkVersion = flutter.ndkVersion
compileOptions { compileOptions {

View File

@ -4,7 +4,7 @@
lose all network access. --> lose all network access. -->
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<application <application
android:label="todo" android:label="Todo"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:allowBackup="true" android:allowBackup="true"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 778 B

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -1,4 +1,7 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
org.gradle.caching=true
org.gradle.parallel=true
kotlin.compiler.execution.strategy=in-process
android.useAndroidX=true android.useAndroidX=true
# This newDsl flag was added by the Flutter template # This newDsl flag was added by the Flutter template
android.newDsl=false android.newDsl=false

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip

View File

@ -19,7 +19,7 @@ pluginManagement {
plugins { plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0" id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false id("com.android.application") version "9.3.2" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false id("org.jetbrains.kotlin.android") version "2.3.20" apply false
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"> <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<rect width="1024" height="1024" fill="#211D1B"/> <rect width="1024" height="1024" fill="#211D1B"/>
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)"> <g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
<path d="M 272 372 L 346 446 L 478 314"/> <path d="M 272 372 L 346 446 L 478 314"/>
<path d="M 594 400 L 752 400"/> <path d="M 594 400 L 752 400"/>
<path d="M 272 620 L 346 694 L 478 562"/> <path d="M 272 620 L 346 694 L 478 562"/>

Before

Width:  |  Height:  |  Size: 449 B

After

Width:  |  Height:  |  Size: 483 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"> <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)"> <g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
<path d="M 272 372 L 346 446 L 478 314"/> <path d="M 272 372 L 346 446 L 478 314"/>
<path d="M 594 400 L 752 400"/> <path d="M 594 400 L 752 400"/>
<path d="M 272 620 L 346 694 L 478 562"/> <path d="M 272 620 L 346 694 L 478 562"/>

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"> <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)"> <g fill="none" stroke="#FFFFFF" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
<path d="M 272 372 L 346 446 L 478 314"/> <path d="M 272 372 L 346 446 L 478 314"/>
<path d="M 594 400 L 752 400"/> <path d="M 594 400 L 752 400"/>
<path d="M 272 620 L 346 694 L 478 562"/> <path d="M 272 620 L 346 694 L 478 562"/>

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 431 B

16
bin/merge_repo_notes.dart Normal file
View File

@ -0,0 +1,16 @@
// One-time: one open note per repo, holding all of that repo's todos.
//
// dart run bin/merge_repo_notes.dart # dry run, prints the map
// dart run bin/merge_repo_notes.dart --apply # does it and pushes
import 'dart:io';
import 'package:todo/cli/merge_repo_notes.dart';
Future<void> main(List<String> argv) async {
exitCode = await runMergeRepoNotes(
argv,
env: Platform.environment,
out: stdout,
err: stderr,
);
}

View File

@ -1,18 +1,18 @@
// coverage:ignore-file // coverage:ignore-file
// Entry point for the desktop wrapper: resolves real paths, starts the server, // Entry point for the desktop wrapper: resolves real paths, starts the server,
// and launches the browser. The serving logic it delegates to is covered by // and launches the browser. The serving logic it delegates to is covered by
// test/wrapper_server_test.dart, and the busy-port recovery it delegates to by // test/wrapper_server_*_test.dart, and the busy-port recovery it delegates to
// test/port_guard_test.dart. Keep this file thin wiring for that reason. // by test/port_guard_*_test.dart. Keep this file thin wiring for that reason.
import 'dart:io'; import 'dart:io';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:todo/desktop/browser_launcher.dart';
import 'package:todo/desktop/port_guard.dart'; import 'package:todo/desktop/port_guard.dart';
import 'package:todo/desktop/wrapper_server.dart'; import 'package:todo/desktop/wrapper_server.dart';
/// Port must stay fixed: the browser keys `localStorage` (the GitHub token) and /// The fixed wrapper port; see [kWrapperPort] for why it cannot move.
/// IndexedDB (the notes) by origin, so a different port looks like a different /// Kept in step with lib/sync/desktop_wrapper.
/// app with no token and no notes. Kept in step with lib/sync/desktop_wrapper. const int _port = kWrapperPort;
const _port = 8730;
/// `errno` for EADDRINUSE. The wrapper is Linux-only (the desktop app is the /// `errno` for EADDRINUSE. The wrapper is Linux-only (the desktop app is the
/// web build served locally), so the numeric value is stable here. /// web build served locally), so the numeric value is stable here.
@ -39,10 +39,12 @@ Future<void> main(List<String> args) async {
// Overridable so a verification run cannot point at the real backlog: an // Overridable so a verification run cannot point at the real backlog: an
// app that starts with an empty store would export over it. // app that starts with an empty store would export over it.
//
// The default comes from [defaultBacklogPath] so it is unit-covered; this
// file is coverage:ignore-file and the path silently broke once already.
final server = WrapperServer( final server = WrapperServer(
webRoot: webRoot, webRoot: webRoot,
backlogPath: backlogPath: _argValue(args, '--backlog-path') ?? defaultBacklogPath(home),
_argValue(args, '--backlog-path') ?? p.join(home, 'todo', 'BACKLOG.md'),
logPath: logPath:
_argValue(args, '--log-path') ?? _argValue(args, '--log-path') ??
p.join(home, '.local', 'share', 'todo-desktop', 'todo_notes.json'), p.join(home, '.local', 'share', 'todo-desktop', 'todo_notes.json'),
@ -69,7 +71,7 @@ Future<void> main(List<String> args) async {
// A bare flag, not a valued option: requiring a dummy value meant passing a // A bare flag, not a valued option: requiring a dummy value meant passing a
// stray positional, which the AOT runtime tries to interpret as a snapshot. // stray positional, which the AOT runtime tries to interpret as a snapshot.
if (!args.contains('--no-browser')) { if (!args.contains('--no-browser')) {
final ranLongEnough = await _launchBrowser(home); final ranLongEnough = await launchBrowser(home);
if (!ranLongEnough) { if (!ranLongEnough) {
// Chrome exits immediately when it hands the URL to an instance that // Chrome exits immediately when it hands the URL to an instance that
// already owns the profile directory (or when a stale SingletonLock is // already owns the profile directory (or when a stale SingletonLock is
@ -113,14 +115,15 @@ Future<bool> _recoverPort(
String home, String home,
List<String> args, List<String> args,
) async { ) async {
final guard = PortGuard(profileDir: _profileDir(home)); final guard = PortGuard(profileDir: profileDir(home));
switch (await guard.resolve(_port)) { switch (await guard.resolve(_port)) {
case AbortWithOwner(:final description): case AbortWithOwner(:final description):
stderr.writeln('port $_port is already in use by $description.'); stderr
stderr.writeln( ..writeln('port $_port is already in use by $description.')
'todo needs this exact port — its notes and GitHub token are stored ' ..writeln(
'per origin. Free the port, then run todo again.', 'todo needs this exact port — its notes and GitHub token are stored '
); 'per origin. Free the port, then run todo again.',
);
exit(1); exit(1);
case AttachToExisting(:final pid): case AttachToExisting(:final pid):
// Re-running the browser command opens a second window rather than // Re-running the browser command opens a second window rather than
@ -138,7 +141,7 @@ Future<bool> _recoverPort(
'todo is already running (pid $pid)' 'todo is already running (pid $pid)'
'${opening ? '; opening a window.' : '.'}', '${opening ? '; opening a window.' : '.'}',
); );
if (opening) await _launchBrowser(home); if (opening) await launchBrowser(home);
return false; return false;
case ReapThenBind(:final pid): case ReapThenBind(:final pid):
stdout.writeln('clearing a stale todo wrapper (pid $pid) on port $_port'); stdout.writeln('clearing a stale todo wrapper (pid $pid) on port $_port');
@ -154,17 +157,6 @@ Future<bool> _recoverPort(
exit(1); exit(1);
} }
/// Browser profile directory for the desktop app.
///
/// Must stay stable: the GitHub token (localStorage) and the notes (IndexedDB)
/// live inside it, so a changing path silently logs the user out and hides
/// their notes. It doubles as the marker for "a window is still attached".
String _profileDir(String home) =>
p.join(home, '.local', 'share', 'todo-desktop', 'profile');
/// Launches the app in a Chrome-family browser with a **stable** profile
/// directory, since the token and notes live in that profile.
/// Returns true when the browser ran long enough to have owned the session.
/// Loads the app once headlessly so it provisions its own sync account. /// Loads the app once headlessly so it provisions its own sync account.
/// ///
/// The account lives in origin-keyed localStorage, which only code running in /// The account lives in origin-keyed localStorage, which only code running in
@ -173,7 +165,7 @@ String _profileDir(String home) =>
/// ///
/// Returns whether the account is present afterwards. /// Returns whether the account is present afterwards.
Future<bool> _provisionSyncAccount(String home) async { Future<bool> _provisionSyncAccount(String home) async {
final browser = _findBrowser(); final browser = findBrowser();
if (browser.isEmpty) { if (browser.isEmpty) {
stderr.writeln('No Chrome-family browser found; cannot provision.'); stderr.writeln('No Chrome-family browser found; cannot provision.');
return false; return false;
@ -185,7 +177,7 @@ Future<bool> _provisionSyncAccount(String home) async {
final process = await Process.start(browser, [ final process = await Process.start(browser, [
'--headless=new', '--headless=new',
'--disable-gpu', '--disable-gpu',
'--user-data-dir=${_profileDir(home)}', '--user-data-dir=${profileDir(home)}',
// Surface the page's own log() output, so a failure inside the app is // Surface the page's own log() output, so a failure inside the app is
// visible in the terminal that started the provisioning run. // visible in the terminal that started the provisioning run.
'--enable-logging=stderr', '--enable-logging=stderr',
@ -203,49 +195,6 @@ Future<bool> _provisionSyncAccount(String home) async {
return true; return true;
} }
/// Returns the first Chrome-family browser on this machine, or ''.
String _findBrowser() {
// Ordered by preference, and deliberately broad: this machine runs Thorium
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
final candidates = [
Platform.environment['TODO_BROWSER'] ?? '',
'/opt/google/chrome/chrome',
'/opt/thorium-browser/thorium-browser',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/brave',
];
return candidates.firstWhere(
(path) => path.isNotEmpty && File(path).existsSync(),
orElse: () => '',
);
}
Future<bool> _launchBrowser(String home) async {
final browser = _findBrowser();
if (browser.isEmpty) {
stderr.writeln(
'No Chrome-family browser found; open '
'http://localhost:$_port manually.',
);
return false;
}
final process = await Process.start(browser, [
'--app=http://localhost:$_port',
'--user-data-dir=${_profileDir(home)}',
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
// Without it the window inherits the browser's class and the taskbar shows
// a browser icon instead of todo's.
'--class=todo',
'--no-first-run',
]);
final started = DateTime.now();
await process.exitCode;
return DateTime.now().difference(started) > const Duration(seconds: 5);
}
String? _argValue(List<String> args, String name) { String? _argValue(List<String> args, String name) {
final index = args.indexOf(name); final index = args.indexOf(name);
if (index == -1 || index + 1 >= args.length) return null; if (index == -1 || index + 1 >= args.length) return null;

21
bin/todo_note.dart Normal file
View File

@ -0,0 +1,21 @@
// Headless note CLI: add, list, search, get, close or delete notes from the PC.
//
// dart run bin/todo_note.dart --text "Title" --repo kuhyx/todo --by claude
// dart run bin/todo_note.dart --list --repo kuhyx/todo
// dart run bin/todo_note.dart --close <id> --evidence "<sha> exit 0"
//
// See `kUsage` in lib/cli/cli_args.dart for every flag. All behaviour lives
// in lib/cli/cli_runner.dart, where the tests reach it.
import 'dart:io';
import 'package:todo/cli/cli_runner.dart';
Future<void> main(List<String> argv) async {
exitCode = await runCli(
argv,
env: Platform.environment,
out: stdout,
err: stderr,
readStdin: () => readInput(stdin, hasTerminal: stdin.hasTerminal),
);
}

View File

@ -0,0 +1,4 @@
# todo's own additions to the fleet-wide allowlist
# (~/src/utils/dependency-freshness.allowlist.yaml).
exceptions: []

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 308 B

After

Width:  |  Height:  |  Size: 309 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 439 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 574 B

After

Width:  |  Height:  |  Size: 579 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 788 B

After

Width:  |  Height:  |  Size: 778 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1023 B

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -10,7 +10,7 @@
# #
# Icon PNGs are pre-rendered and committed under desktop/icons/, so this script # Icon PNGs are pre-rendered and committed under desktop/icons/, so this script
# needs no image tooling at run time. Regenerate them with: # needs no image tooling at run time. Regenerate them with:
# PYTHONPATH=~/testsAndMisc python3 -m python_pkg.app_icons \ # PYTHONPATH=~/src/testsAndMisc python3 -m python_pkg.app_icons \
# generate --app todo --linux-out desktop/icons # generate --app todo --linux-out desktop/icons
# ============================================================================ # ============================================================================
@ -83,7 +83,7 @@ install_desktop_entry() {
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
[Desktop Entry] [Desktop Entry]
Type=Application Type=Application
Name=todo Name=Todo
Comment=Offline-first, CRDT-synced notes Comment=Offline-first, CRDT-synced notes
Exec=$LAUNCH_CMD Exec=$LAUNCH_CMD
Icon=$ICON_NAME Icon=$ICON_NAME

View File

@ -0,0 +1,73 @@
# Linux desktop performance: measured findings
Investigation date: 2026-07-20. Machine: Arch, X11 + i3, NVIDIA proprietary
610.43.03, RTX 3090. DP-0 = 3840x2160 @144 Hz (primary), HDMI-0 = 2560x1440
@144 Hz. Flutter 3.44.6 stable.
## Conclusion
**The previous session was right: Flutter's Linux desktop embedder cannot drive
this machine's 4K display, and switching technology for the desktop app is
justified.**
Two independent defects, neither fixable in application code:
1. **Hard 60 FPS cap.** Flutter's Linux embedder schedules frames at a fixed
60 FPS regardless of the monitor (upstream
[#183703](https://github.com/flutter/flutter/issues/183703), P2, no PR).
2. **~20 FPS at 4K.** Far worse, and the actual cause of the reported lag. At
3840x2160 the app achieves 18.6 fps while each frame costs only ~3 ms of a
16.7 ms budget. The stock `flutter create` counter app behaves identically,
so this is the toolkit, not todo.
Application code is not implicated anywhere: build (Dart) time is 0.1-0.4 ms in
every configuration and at every window size measured.
An earlier revision of this document concluded that a rewrite was **not**
warranted. That conclusion was based only on defect 1 and is superseded by the
4K measurements below.
## Evidence
Measured with a temporary in-app instrument (`lib/frame_stats.dart`, armed by
`TODO_FRAME_STATS=1`) reporting frame-to-frame cadence alongside build/raster
times, driven by a perpetual animation so frames are produced continuously.
| Configuration | Cadence p50 | Achieved | build p50 | raster p50 |
|---|---|---|---|---|
| Release, Skia GL (default) | 16.67 ms | **60.0 fps** | 0.30 ms | 1.50 ms |
| Release, Impeller | 16.67 ms | **60.0 fps** | 0.19 ms | 1.33 ms |
| Release, Impeller + Vulkan | 16.67 ms | **60.0 fps** | 0.26 ms | 1.33 ms |
| Driver vsync off (`__GL_SYNC_TO_VBLANK=0`) | 16.67 ms | **60.0 fps** | 0.28 ms | 1.40 ms |
| picom compositor + Skia GL | 16.67 ms | **60.0 fps** | 0.27 ms | 1.62 ms |
| picom compositor + Impeller | 16.67 ms | **60.0 fps** | 0.30 ms | 1.44 ms |
| **Stock `flutter create` app** (no todo code) | 16.67 ms | **60.0 fps** | 0.12 ms | 1.35 ms |
| **Same Flutter code as a web build, in Chrome** | **7.00 ms** | **142.9 fps** | — | — |
> **Retracted:** an earlier revision of this table had a "real typing +
> scrolling" row. It was invalid. It used `xdotool type --window`, which sends
> synthetic `XSendEvent` keystrokes that GTK/Flutter ignore; the keystrokes
> actually landed in a different application. That run measured an idle app.
> Interaction is measured properly in the next section instead.
Confounds on the web row, stated for honesty: it ran on HDMI-0 (1440p@144) with
a game occupying the 4K GPU, which is why its p95 was 13.90 ms. The desktop
60.0 fps lock, by contrast, is clean, jitter-free and monitor-independent, so
the comparison's conclusion holds — but the web number should be re-confirmed on
the 4K monitor with the GPU idle.
Key readings:
- Cadence p50 **equals** p95 at exactly 16.67 ms in every desktop run — a hard
lock with zero jitter, not contention.
- Total per-frame work is ~1.8 ms against a 6.94 ms 144 Hz budget. The renderer
has **74% headroom at 144 Hz** and 89% at 60 Hz.
- Under real typing and scrolling, **one** frame exceeded the 144 Hz budget in
14 seconds and **zero** exceeded 60 Hz. There is no dropped-frame jank.
- The stock counter app behaves identically, so this is not `todo`'s code.
- Neither renderer choice, nor driver vsync, nor a compositor moves the number.
---
Part 2 — the interaction-lag half of this investigation, and the decision that came out of it — is in
[desktop-performance-interaction-lag.md](desktop-performance-interaction-lag.md).

View File

@ -1,71 +1,9 @@
# Linux desktop performance: measured findings # Linux desktop performance, part 2: interaction lag
Investigation date: 2026-07-20. Machine: Arch, X11 + i3, NVIDIA proprietary The second half of the investigation started in
610.43.03, RTX 3090. DP-0 = 3840x2160 @144 Hz (primary), HDMI-0 = 2560x1440 [desktop-performance-findings.md](desktop-performance-findings.md), which
@144 Hz. Flutter 3.44.6 stable. covers frame rate. Split only to keep each file under the 250-line cap;
the author signposted the two parts explicitly.
## Conclusion
**The previous session was right: Flutter's Linux desktop embedder cannot drive
this machine's 4K display, and switching technology for the desktop app is
justified.**
Two independent defects, neither fixable in application code:
1. **Hard 60 FPS cap.** Flutter's Linux embedder schedules frames at a fixed
60 FPS regardless of the monitor (upstream
[#183703](https://github.com/flutter/flutter/issues/183703), P2, no PR).
2. **~20 FPS at 4K.** Far worse, and the actual cause of the reported lag. At
3840x2160 the app achieves 18.6 fps while each frame costs only ~3 ms of a
16.7 ms budget. The stock `flutter create` counter app behaves identically,
so this is the toolkit, not todo.
Application code is not implicated anywhere: build (Dart) time is 0.1-0.4 ms in
every configuration and at every window size measured.
An earlier revision of this document concluded that a rewrite was **not**
warranted. That conclusion was based only on defect 1 and is superseded by the
4K measurements below.
## Evidence
Measured with a temporary in-app instrument (`lib/frame_stats.dart`, armed by
`TODO_FRAME_STATS=1`) reporting frame-to-frame cadence alongside build/raster
times, driven by a perpetual animation so frames are produced continuously.
| Configuration | Cadence p50 | Achieved | build p50 | raster p50 |
|---|---|---|---|---|
| Release, Skia GL (default) | 16.67 ms | **60.0 fps** | 0.30 ms | 1.50 ms |
| Release, Impeller | 16.67 ms | **60.0 fps** | 0.19 ms | 1.33 ms |
| Release, Impeller + Vulkan | 16.67 ms | **60.0 fps** | 0.26 ms | 1.33 ms |
| Driver vsync off (`__GL_SYNC_TO_VBLANK=0`) | 16.67 ms | **60.0 fps** | 0.28 ms | 1.40 ms |
| picom compositor + Skia GL | 16.67 ms | **60.0 fps** | 0.27 ms | 1.62 ms |
| picom compositor + Impeller | 16.67 ms | **60.0 fps** | 0.30 ms | 1.44 ms |
| **Stock `flutter create` app** (no todo code) | 16.67 ms | **60.0 fps** | 0.12 ms | 1.35 ms |
| **Same Flutter code as a web build, in Chrome** | **7.00 ms** | **142.9 fps** | — | — |
> **Retracted:** an earlier revision of this table had a "real typing +
> scrolling" row. It was invalid. It used `xdotool type --window`, which sends
> synthetic `XSendEvent` keystrokes that GTK/Flutter ignore; the keystrokes
> actually landed in a different application. That run measured an idle app.
> Interaction is measured properly in the next section instead.
Confounds on the web row, stated for honesty: it ran on HDMI-0 (1440p@144) with
a game occupying the 4K GPU, which is why its p95 was 13.90 ms. The desktop
60.0 fps lock, by contrast, is clean, jitter-free and monitor-independent, so
the comparison's conclusion holds — but the web number should be re-confirmed on
the 4K monitor with the GPU idle.
Key readings:
- Cadence p50 **equals** p95 at exactly 16.67 ms in every desktop run — a hard
lock with zero jitter, not contention.
- Total per-frame work is ~1.8 ms against a 6.94 ms 144 Hz budget. The renderer
has **74% headroom at 144 Hz** and 89% at 60 Hz.
- Under real typing and scrolling, **one** frame exceeded the 144 Hz budget in
14 seconds and **zero** exceeded 60 Hz. There is no dropped-frame jank.
- The stock counter app behaves identically, so this is not `todo`'s code.
- Neither renderer choice, nor driver vsync, nor a compositor moves the number.
## Part 2: the interaction lag is a separate, larger problem ## Part 2: the interaction lag is a separate, larger problem

View File

@ -0,0 +1,144 @@
# Flutter AI rules — Colour, type, documentation and accessibility
Colour schemes, fonts, dartdoc conventions and accessibility.
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
cap. Re-fetch periodically to stay current; do not hand-edit._
#### Contrast Ratios
* **WCAG Guidelines:** Aim to meet the Web Content Accessibility Guidelines
(WCAG) 2.1 standards.
* **Minimum Contrast:**
* **Normal Text:** A contrast ratio of at least **4.5:1**.
* **Large Text:** (18pt or 14pt bold) A contrast ratio of at least **3:1**.
#### Palette Selection
* **Primary, Secondary, and Accent:** Define a clear color hierarchy.
* **The 60-30-10 Rule:** A classic design rule for creating a balanced color scheme.
* **60%** Primary/Neutral Color (Dominant)
* **30%** Secondary Color
* **10%** Accent Color
#### Complementary Colors
* **Use with Caution:** They can be visually jarring if overused.
* **Best Use Cases:** They are excellent for accent colors to make specific
elements pop, but generally poor for text and background pairings as they can
cause eye strain.
#### Example Palette
* **Primary:** #0D47A1 (Dark Blue)
* **Secondary:** #1976D2 (Medium Blue)
* **Accent:** #FFC107 (Amber)
* **Neutral/Text:** #212121 (Almost Black)
* **Background:** #FEFEFE (Almost White)
### Font Best Practices
#### Font Selection
* **Limit Font Families:** Stick to one or two font families for the entire
application.
* **Prioritize Legibility:** Choose fonts that are easy to read on screens of
all sizes. Sans-serif fonts are generally preferred for UI body text.
* **System Fonts:** Consider using platform-native system fonts.
* **Google Fonts:** For a wide selection of open-source fonts, use the
`google_fonts` package.
#### Hierarchy and Scale
* **Establish a Scale:** Define a set of font sizes for different text elements
(e.g., headlines, titles, body text, captions).
* **Use Font Weight:** Differentiate text effectively using font weights.
* **Color and Opacity:** Use color and opacity to de-emphasize less important
text.
#### Readability
* **Line Height (Leading):** Set an appropriate line height, typically **1.4x to
1.6x** the font size.
* **Line Length:** For body text, aim for a line length of **45-75 characters**.
* **Avoid All Caps:** Do not use all caps for long-form text.
#### Example Typographic Scale
```dart
// In your ThemeData
textTheme: const TextTheme(
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
titleLarge: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
bodyLarge: TextStyle(fontSize: 16.0, height: 1.5),
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
labelSmall: TextStyle(fontSize: 11.0, color: Colors.grey),
),
```
### Documentation
* **`dartdoc`:** Write `dartdoc`-style comments for all public APIs.
#### Documentation Philosophy
* **Comment wisely:** Use comments to explain why the code is written a certain
way, not what the code does. The code itself should be self-explanatory.
* **Document for the user:** Write documentation with the reader in mind. If you
had a question and found the answer, add it to the documentation where you
first looked. This ensures the documentation answers real-world questions.
* **No useless documentation:** If the documentation only restates the obvious
from the code's name, it's not helpful. Good documentation provides context
and explains what isn't immediately apparent.
* **Consistency is key:** Use consistent terminology throughout your
documentation.
#### Commenting Style
* **Use `///` for doc comments:** This allows documentation generation tools to
pick them up.
* **Start with a single-sentence summary:** The first sentence should be a
concise, user-centric summary ending with a period.
* **Separate the summary:** Add a blank line after the first sentence to create
a separate paragraph. This helps tools create better summaries.
* **Avoid redundancy:** Don't repeat information that's obvious from the code's
context, like the class name or signature.
* **Don't document both getter and setter:** For properties with both, only
document one. The documentation tool will treat them as a single field.
#### Writing Style
* **Be brief:** Write concisely.
* **Avoid jargon and acronyms:** Don't use abbreviations unless they are widely
understood.
* **Use Markdown sparingly:** Avoid excessive markdown and never use HTML for
formatting.
* **Use backticks for code:** Enclose code blocks in backtick fences, and
specify the language.
#### What to Document
* **Public APIs are a priority:** Always document public APIs.
* **Consider private APIs:** It's a good idea to document private APIs as well.
* **Library-level comments are helpful:** Consider adding a doc comment at the
library level to provide a general overview.
* **Include code samples:** Where appropriate, add code samples to illustrate usage.
* **Explain parameters, return values, and exceptions:** Use prose to describe
what a function expects, what it returns, and what errors it might throw.
* **Place doc comments before annotations:** Documentation should come before
any metadata annotations.
### Accessibility (A11Y)
Implement accessibility features to empower all users, assuming a wide variety
of users with different physical abilities, mental abilities, age groups,
education levels, and learning styles.
* **Color Contrast:** Ensure text has a contrast ratio of at least **4.5:1**
against its background.
* **Dynamic Text Scaling:** Test your UI to ensure it remains usable when users
increase the system font size.
* **Semantic Labels:** Use the `Semantics` widget to provide clear, descriptive
labels for UI elements.
* **Screen Reader Testing:** Regularly test your app with TalkBack (Android) and
VoiceOver (iOS).

View File

@ -0,0 +1,163 @@
# Flutter AI rules — language, style and architecture
Dart/Flutter style, package management, code quality, and how a project is laid out.
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
cap. Re-fetch periodically to stay current; do not hand-edit._
### Interaction Guidelines
* **User Persona:** Assume the user is familiar with programming concepts but
may be new to Dart.
* **Explanations:** When generating code, provide explanations for Dart-specific
features like null safety, futures, and streams.
* **Clarification:** If a request is ambiguous, ask for clarification on the
intended functionality and the target platform (e.g., command-line, web,
server).
* **Dependencies:** When suggesting new dependencies from `pub.dev`, explain
their benefits.
* **Formatting:** Use the `dart_format` tool to ensure consistent code
formatting.
* **Fixes:** Use the `dart_fix` tool to automatically fix many common errors,
and to help code conform to configured analysis options.
* **Linting:** Use the Dart linter with a recommended set of rules to catch
common issues. Use the `analyze_files` tool to run the linter.
### Project Structure
* **Standard Structure:** Assumes a standard Flutter project structure with
`lib/main.dart` as the primary application entry point.
### Flutter style guide
* **SOLID Principles:** Apply SOLID principles throughout the codebase.
* **Concise and Declarative:** Write concise, modern, technical Dart code.
Prefer functional and declarative patterns.
* **Composition over Inheritance:** Favor composition for building complex
widgets and logic.
* **Immutability:** Prefer immutable data structures. Widgets (especially
`StatelessWidget`) should be immutable.
* **State Management:** Separate ephemeral state and app state. Use a state
management solution for app state to handle the separation of concerns.
* **Widgets are for UI:** Everything in Flutter's UI is a widget. Compose
complex UIs from smaller, reusable widgets.
* **Navigation:** Use a modern routing package like `auto_route` or `go_router`.
For more guidelines around navigation, see the section on [routing](#routing).
### Package Management
* **Pub Tool:** To manage packages, use the `pub` tool, if available.
* **External Packages:** If a new feature requires an external package, use the
`pub_dev_search` tool, if it is available. Otherwise, identify the most
suitable and stable package from pub.dev.
* **Adding Dependencies:** To add a regular dependency, use the `pub` tool, if
it is available. Otherwise, run `flutter pub add <package_name>`.
* **Adding Dev Dependencies:** To add a development dependency, use the `pub`
tool, if it is available, with `dev:<package name>`. Otherwise, run `flutter
pub add dev:<package_name>`.
* **Dependency Overrides:** To add a dependency override, use the `pub` tool, if
it is available, with `override:<package name>:1.0.0`. Otherwise, run `flutter
pub add override:<package_name>:1.0.0`.
* **Removing Dependencies:** To remove a dependency, use the `pub` tool, if it
is available. Otherwise, run `dart pub remove <package_name>`.
### Code Quality
* **Code structure:** Adhere to maintainable code structure and separation of
concerns (e.g., UI logic separate from business logic).
* **Naming conventions:** Avoid abbreviations and use meaningful, consistent,
descriptive names for variables, functions, and classes.
* **Conciseness:** Write code that is as short as it can be while remaining
clear.
* **Simplicity:** Write straightforward code. Code that is clever or
obscure is difficult to maintain.
* **Error Handling:** Anticipate and handle potential errors. Don't let your
code fail silently.
* **Styling:**
* Line length: Lines should be 80 characters or fewer.
* Use `PascalCase` for classes, `camelCase` for
members/variables/functions/enums, and `snake_case` for files.
* **Functions:**
* Keep functions short and with a single purpose.
Strive for less than 20 lines.
* **Testing:** Write code with testing in mind. Use the `file`, `process`, and
`platform` packages, if appropriate, so you can inject in-memory and fake
versions of the objects.
* **Logging:** Use the `logging` package instead of `print`.
### Dart Best Practices
* **Effective Dart:** Follow the official Effective Dart guidelines
(https://dart.dev/effective-dart)
* **Class Organization:** Define related classes within the same library file.
For large libraries, export smaller, private libraries from a single top-level
library.
* **Library Organization:** Group related libraries in the same folder.
* **API Documentation:** Add documentation comments to all public APIs,
including classes, constructors, methods, and top-level functions.
* **Comments:** Write clear comments for complex or non-obvious code. Avoid
over-commenting.
* **Trailing Comments:** Don't add trailing comments.
* **Async/Await:** Ensure proper use of `async`/`await` for asynchronous
operations with robust error handling.
* Use `Future`s, `async`, and `await` for asynchronous operations.
* Use `Stream`s for sequences of asynchronous events.
* **Null Safety:** Write code that is soundly null-safe. Leverage Dart's null
safety features. Avoid `!` unless the value is guaranteed to be non-null.
* **Pattern Matching:** Use pattern matching features where they simplify the
code.
* **Records:** Use records to return multiple types in situations where defining
an entire class is cumbersome.
* **Switch Statements:** Prefer using exhaustive `switch` statements or
expressions, which don't require `break` statements.
* **Exception Handling:** Use `try-catch` blocks for handling exceptions, and
use exceptions appropriate for the type of exception. Use custom exceptions
for situations specific to your code.
* **Arrow Functions:** Use arrow syntax for simple one-line functions.
### Flutter Best Practices
* **Immutability:** Widgets (especially `StatelessWidget`) are immutable; when
the UI needs to change, Flutter rebuilds the widget tree.
* **Composition:** Prefer composing smaller widgets over extending existing
ones. Use this to avoid deep widget nesting.
* **Private Widgets:** Use small, private `Widget` classes instead of private
helper methods that return a `Widget`.
* **Build Methods:** Break down large `build()` methods into smaller, reusable
private Widget classes.
* **List Performance:** Use `ListView.builder` or `SliverList` for long lists to
create lazy-loaded lists for performance.
* **Isolates:** Use `compute()` to run expensive calculations in a separate
isolate to avoid blocking the UI thread, such as JSON parsing.
* **Const Constructors:** Use `const` constructors for widgets and in `build()`
methods whenever possible to reduce rebuilds.
* **Build Method Performance:** Avoid performing expensive operations, like
network calls or complex computations, directly within `build()` methods.
### API Design Principles
When building reusable APIs, such as a library, follow these principles.
* **Consider the User:** Design APIs from the perspective of the person who will
be using them. The API should be intuitive and easy to use correctly.
* **Documentation is Essential:** Good documentation is a part of good API
design. It should be clear, concise, and provide examples.
### Application Architecture
* **Separation of Concerns:** Aim for separation of concerns similar to MVC/MVVM, with defined Model,
View, and ViewModel/Controller roles.
* **Logical Layers:** Organize the project into logical layers:
* Presentation (widgets, screens)
* Domain (business logic classes)
* Data (model classes, API clients)
* Core (shared classes, utilities, and extension types)
* **Feature-based Organization:** For larger projects, organize code by feature,
where each feature has its own presentation, domain, and data subfolders. This
improves navigability and scalability.
### Lint Rules
Include the package in the `analysis_options.yaml` file. Use the following
`analysis_options.yaml` file as a starting point:
```yaml
include: package:flutter_lints/flutter.yaml
linter:
rules:
# Add additional lint rules here:
# avoid_print: false
# prefer_single_quotes: true
```

View File

@ -0,0 +1,154 @@
# Flutter AI rules — state, routing and data
State management, data flow, routing, JSON serialization and logging.
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
cap. Re-fetch periodically to stay current; do not hand-edit._
#### State Management
* **Built-in Solutions:** Prefer Flutter's built-in state management solutions.
Do not use a third-party package unless explicitly requested.
* **Streams:** Use `Streams` and `StreamBuilder` for handling a sequence of
asynchronous events.
* **Futures:** Use `Futures` and `FutureBuilder` for handling a single
asynchronous operation that will complete in the future.
* **ValueNotifier:** Use `ValueNotifier` with `ValueListenableBuilder` for
simple, local state that involves a single value.
```dart
// Define a ValueNotifier to hold the state.
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
// Use ValueListenableBuilder to listen and rebuild.
ValueListenableBuilder<int>(
valueListenable: _counter,
builder: (context, value, child) {
return Text('Count: $value');
},
);
```
* **ChangeNotifier:** For state that is more complex or shared across multiple
widgets, use `ChangeNotifier`.
* **ListenableBuilder:** Use `ListenableBuilder` to listen to changes from a
`ChangeNotifier` or other `Listenable`.
* **MVVM:** When a more robust solution is needed, structure the app using the
Model-View-ViewModel (MVVM) pattern.
* **Dependency Injection:** Use simple manual constructor dependency injection
to make a class's dependencies explicit in its API, and to manage dependencies
between different layers of the application.
* **Provider:** If a dependency injection solution beyond manual constructor
injection is explicitly requested, `provider` can be used to make services,
repositories, or complex state objects available to the UI layer without tight
coupling (note: this document generally defaults against third-party packages
for state management unless explicitly requested).
#### Data Flow
* **Data Structures:** Define data structures (classes) to represent the data
used in the application.
* **Data Abstraction:** Abstract data sources (e.g., API calls, database
operations) using Repositories/Services to promote testability.
#### Routing
* **GoRouter:** Use the `go_router` package for declarative navigation, deep
linking, and web support.
* **GoRouter Setup:** To use `go_router`, first add it to your `pubspec.yaml`
using the `pub` tool's `add` command.
```dart
// 1. Add the dependency
// flutter pub add go_router
// 2. Configure the router
final GoRouter _router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'details/:id', // Route with a path parameter
builder: (context, state) {
final String id = state.pathParameters['id']!;
return DetailScreen(id: id);
},
),
],
),
],
);
// 3. Use it in your MaterialApp
MaterialApp.router(
routerConfig: _router,
);
```
* **Authentication Redirects:** Configure `go_router`'s `redirect` property to
handle authentication flows, ensuring users are redirected to the login screen
when unauthorized, and back to their intended destination after successful
login.
* **Navigator:** Use the built-in `Navigator` for short-lived screens that do
not need to be deep-linkable, such as dialogs or temporary views.
```dart
// Push a new screen onto the stack
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const DetailsScreen()),
);
// Pop the current screen to go back
Navigator.pop(context);
```
#### Data Handling & Serialization
* **JSON Serialization:** Use `json_serializable` and `json_annotation` for
parsing and encoding JSON data.
* **Field Renaming:** When encoding data, use `fieldRename: FieldRename.snake`
to convert Dart's camelCase fields to snake_case JSON keys.
```dart
// In your model file
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(fieldRename: FieldRename.snake)
class User {
final String firstName;
final String lastName;
User({required this.firstName, required this.lastName});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
```
#### Logging
* **Structured Logging:** Use the `log` function from `dart:developer` for
structured logging that integrates with Dart DevTools.
```dart
import 'dart:developer' as developer;
// For simple messages
developer.log('User logged in successfully.');
// For structured error logging
try {
// ... code that might fail
} catch (e, s) {
developer.log(
'Failed to fetch data',
name: 'myapp.network',
level: 1000, // SEVERE
error: e,
stackTrace: s,
);
}
```
### Code Generation

View File

@ -0,0 +1,151 @@
# Flutter AI rules — Code generation, testing, theming and assets
Code generation, the testing guidance, and the visual-design, theming and asset rules.
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
cap. Re-fetch periodically to stay current; do not hand-edit._
* **Build Runner:** If the project uses code generation, ensure that
`build_runner` is listed as a dev dependency in `pubspec.yaml`.
* **Code Generation Tasks:** Use `build_runner` for all code generation tasks,
such as for `json_serializable`.
* **Running Build Runner:** After modifying files that require code generation,
run the build command:
```shell
dart run build_runner build --delete-conflicting-outputs
```
### Testing
* **Running Tests:** To run tests, use the `run_tests` tool if it is available,
otherwise use `flutter test`.
* **Unit Tests:** Use `package:test` for unit tests.
* **Widget Tests:** Use `package:flutter_test` for widget tests.
* **Integration Tests:** Use `package:integration_test` for integration tests.
* **Assertions:** Prefer using `package:checks` for more expressive and readable
assertions over the default `matchers`.
#### Testing Best practices
* **Convention:** Follow the Arrange-Act-Assert (or Given-When-Then) pattern.
* **Unit Tests:** Write unit tests for domain logic, data layer, and state
management.
* **Widget Tests:** Write widget tests for UI components.
* **Integration Tests:** For broader application validation, use integration
tests to verify end-to-end user flows.
* **integration_test package:** Use the `integration_test` package from the
Flutter SDK for integration tests. Add it as a `dev_dependency` in
`pubspec.yaml` by specifying `sdk: flutter`.
* **Mocks:** Prefer fakes or stubs over mocks. If mocks are absolutely
necessary, use `mockito` or `mocktail` to create mocks for dependencies. While
code generation is common for state management (e.g., with `freezed`), try to
avoid it for mocks.
* **Coverage:** Aim for high test coverage.
### Visual Design & Theming
* **UI Design:** Build beautiful and intuitive user interfaces that follow
modern design guidelines.
* **Responsiveness:** Ensure the app is mobile responsive and adapts to
different screen sizes, working perfectly on mobile and web.
* **Navigation:** If there are multiple pages for the user to interact with,
provide an intuitive and easy navigation bar or controls.
* **Typography:** Stress and emphasize font sizes to ease understanding, e.g.,
hero text, section headlines, list headlines, keywords in paragraphs.
* **Background:** Keep backgrounds flat and simple — no noise texture or
gradients. Follow the `unified-design-system` skill (safe-design-rules
rule 17: simple-on-complex); let content and typography carry visual
interest instead of background texture.
* **Shadows:** Follow the `unified-design-system` skill's shadow policy: no
shadows at all in dark UI (differentiate elevation with lighter surface
fills, not shadows); in light UI, shadows are for floating/overlay
elements only (menus, dialogs), never for inline cards, and never mixed
with a border on the same surface.
* **Icons:** Incorporate icons to enhance the user’s understanding and the
logical navigation of the app.
* **Interactive Elements:** Buttons/controls signal state via color and fill
changes, not a "glow" shadow — one depth technique per surface, per
`unified-design-system`.
#### Theming
* **Centralized Theme:** Define a centralized `ThemeData` object to ensure a
consistent application-wide style.
* **Light and Dark Themes:** Implement support for both light and dark themes,
ideal for a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`,
`ThemeMode.system`).
* **Color Scheme Generation:** Do NOT use `ColorScheme.fromSeed` for this
app's palette — it can't reproduce hand-picked values exactly. Build
`ThemeData` from explicit `ColorScheme.dark(...)`/`.light(...)` using the
frozen, identical-everywhere tokens in the `unified-design-system` skill
(`~/.claude/skills/unified-design-system/references/tokens.md`).
```dart
final ThemeData lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
// ... other theme properties
);
```
* **Color Palette:** Include a wide range of color concentrations and hues in
the palette to create a vibrant and energetic look and feel.
* **Component Themes:** Use specific theme properties (e.g., `appBarTheme`,
`elevatedButtonTheme`) to customize the appearance of individual Material
components.
* **Custom Fonts:** For custom fonts, use the `google_fonts` package. Define a
`TextTheme` to apply fonts consistently.
```dart
// 1. Add the dependency
// flutter pub add google_fonts
// 2. Define a TextTheme with a custom font
final TextTheme appTextTheme = TextTheme(
displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold),
titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500),
bodyMedium: GoogleFonts.openSans(fontSize: 14),
);
```
#### Assets and Images
* **Image Guidelines:** If images are needed, make them relevant and meaningful,
with appropriate size, layout, and licensing (e.g., freely available). Provide
placeholder images if real ones are not available.
* **Asset Declaration:** Declare all asset paths in your `pubspec.yaml` file.
```yaml
flutter:
uses-material-design: true
assets:
- assets/images/
```
* **Local Images:** Use `Image.asset` for local images from your asset
bundle.
```dart
Image.asset('assets/images/placeholder.png')
```
* **Network images:** Use NetworkImage for images loaded from the network.
* **Cached images:** For cached images, use NetworkImage a package like
`cached_network_image`.
* **Custom Icons:** Use `ImageIcon` to display an icon from an `ImageProvider`,
useful for custom icons not in the `Icons` class.
* **Network Images:** Use `Image.network` to display images from a URL, and
always include `loadingBuilder` and `errorBuilder` for a better user
experience.
```dart
// When using network images, always provide an errorBuilder.
Image.network(
'https://picsum.photos/200/300',
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(child: CircularProgressIndicator());
},
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.error);
},
)
```
### UI Theming and Styling Code

View File

@ -0,0 +1,197 @@
# Flutter AI rules — UI: theming, layout and overlays
Material theming, WidgetStateProperty, layout, and overlays.
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
cap. Re-fetch periodically to stay current; do not hand-edit._
* **Responsiveness:** Use `LayoutBuilder` or `MediaQuery` to create responsive
UIs.
* **Text:** Use `Theme.of(context).textTheme` for text styles.
* **Text Fields:** Configure `textCapitalization`, `keyboardType`, and
`placeholder`.
### Material Theming Best Practices
#### Embrace `ThemeData` and Material 3
* **Use `ColorScheme.fromSeed()`:** Use this to generate a complete, harmonious
color palette for both light and dark modes from a single seed color.
* **Define Light and Dark Themes:** Provide both `theme` and `darkTheme` to your
`MaterialApp` to support system brightness settings seamlessly.
* **Centralize Component Styles:** Customize specific component themes (e.g.,
`elevatedButtonTheme`, `cardTheme`, `appBarTheme`) within `ThemeData` to
ensure consistency.
* **Dark/Light Mode and Theme Toggle:** Implement support for both light and
dark themes using `theme` and `darkTheme` properties of `MaterialApp`. The
`themeMode` property can be dynamically controlled (e.g., via a
`ChangeNotifierProvider`) to allow for toggling between `ThemeMode.light`,
`ThemeMode.dark`, or `ThemeMode.system`.
```dart
// main.dart
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
textTheme: const TextTheme(
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.dark,
),
),
home: const MyHomePage(),
);
```
#### Implement Design Tokens with `ThemeExtension`
For custom styles that aren't part of the standard `ThemeData`, use
`ThemeExtension` to define reusable design tokens.
* **Create a Custom Theme Extension:** Define a class that extends
`ThemeExtension<T>` and include your custom properties.
* **Implement `copyWith` and `lerp`:** These methods are required for the
extension to work correctly with theme transitions.
* **Register in `ThemeData`:** Add your custom extension to the `extensions`
list in your `ThemeData`.
* **Access Tokens in Widgets:** Use `Theme.of(context).extension<MyColors>()!`
to access your custom tokens.
```dart
// 1. Define the extension
@immutable
class MyColors extends ThemeExtension<MyColors> {
const MyColors({required this.success, required this.danger});
final Color? success;
final Color? danger;
@override
ThemeExtension<MyColors> copyWith({Color? success, Color? danger}) {
return MyColors(success: success ?? this.success, danger: danger ?? this.danger);
}
@override
ThemeExtension<MyColors> lerp(ThemeExtension<MyColors>? other, double t) {
if (other is! MyColors) return this;
return MyColors(
success: Color.lerp(success, other.success, t),
danger: Color.lerp(danger, other.danger, t),
);
}
}
// 2. Register it in ThemeData
theme: ThemeData(
extensions: const <ThemeExtension<dynamic>>[
MyColors(success: Colors.green, danger: Colors.red),
],
),
// 3. Use it in a widget
Container(
color: Theme.of(context).extension<MyColors>()!.success,
)
```
#### Styling with `WidgetStateProperty`
* **`WidgetStateProperty.resolveWith`:** Provide a function that receives a
`Set<WidgetState>` and returns the appropriate value for the current state.
* **`WidgetStateProperty.all`:** A shorthand for when the value is the same for
all states.
```dart
// Example: Creating a button style that changes color when pressed.
final ButtonStyle myButtonStyle = ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color>(
(Set<WidgetState> states) {
if (states.contains(WidgetState.pressed)) {
return Colors.green; // Color when pressed
}
return Colors.red; // Default color
},
),
);
```
### Layout Best Practices
#### Building Flexible and Overflow-Safe Layouts
##### For Rows and Columns
* **`Expanded`:** Use to make a child widget fill the remaining available space
along the main axis.
* **`Flexible`:** Use when you want a widget to shrink to fit, but not
necessarily grow. Don't combine `Flexible` and `Expanded` in the same `Row` or
`Column`.
* **`Wrap`:** Use when you have a series of widgets that would overflow a `Row`
or `Column`, and you want them to move to the next line.
##### For General Content
* **`SingleChildScrollView`:** Use when your content is intrinsically larger
than the viewport, but is a fixed size.
* **`ListView` / `GridView`:** For long lists or grids of content, always use a
builder constructor (`.builder`).
* **`FittedBox`:** Use to scale or fit a single child widget within its parent.
* **`LayoutBuilder`:** Use for complex, responsive layouts to make decisions
based on the available space.
#### Layering Widgets with Stack
* **`Positioned`:** Use to precisely place a child within a `Stack` by anchoring it to the edges.
* **`Align`:** Use to position a child within a `Stack` using alignments like `Alignment.center`.
#### Advanced Layout with Overlays
* **`OverlayPortal`:** Use this widget to show UI elements (like custom
dropdowns or tooltips) "on top" of everything else. It manages the
`OverlayEntry` for you.
```dart
class MyDropdown extends StatefulWidget {
const MyDropdown({super.key});
@override
State<MyDropdown> createState() => _MyDropdownState();
}
class _MyDropdownState extends State<MyDropdown> {
final _controller = OverlayPortalController();
@override
Widget build(BuildContext context) {
return OverlayPortal(
controller: _controller,
overlayChildBuilder: (BuildContext context) {
return const Positioned(
top: 50,
left: 10,
child: Card(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text('I am an overlay!'),
),
),
);
},
child: ElevatedButton(
onPressed: _controller.toggle,
child: const Text('Toggle Overlay'),
),
);
}
}
```
### Color Scheme Best Practices

View File

@ -2,7 +2,7 @@
## Context ## Context
`~/todo`'s default note template (`lib/data/note_template.dart`, `NoteTemplate.llmDesignSpec`) `~/src/todo`'s default note template (`lib/data/note_template.dart`, `NoteTemplate.llmDesignSpec`)
has 12 sections: title, what, where, tech, must, ask, nice, never, done, depends, has 12 sections: title, what, where, tech, must, ask, nice, never, done, depends,
estimate, refs. It was designed top-down from the `<work_backlog>` format in estimate, refs. It was designed top-down from the `<work_backlog>` format in
`~/.claude/CLAUDE.md`, never validated against what actually gets written or what `~/.claude/CLAUDE.md`, never validated against what actually gets written or what
@ -19,7 +19,7 @@ read, and did leaving it out cause a failure?*
| Source | Size | | Source | Size |
| --- | --- | | --- | --- |
| `~/.claude/projects/**/*.jsonl` | 514 sessions, 495 with real user prompts, **1503 prompts** | | `~/.claude/projects/**/*.jsonl` | 514 sessions, 495 with real user prompts, **1503 prompts** |
| `~/todo/BACKLOG.md` | 49 notes — **25 structured, 24 freeform** | | `~/src/todo/BACKLOG.md` | 49 notes — **25 structured, 24 freeform** |
| note → session join (title match) | **22 note/session pairs**, 21 of 25 notes traced | | note → session join (title match) | **22 note/session pairs**, 21 of 25 notes traced |
| `~/.claude/memories/mistakes.md` + `projects/-home-kuhy/memory/feedback-*.md` | 13 dated mistakes, 33 feedback memories | | `~/.claude/memories/mistakes.md` + `projects/-home-kuhy/memory/feedback-*.md` | 13 dated mistakes, 33 feedback memories |
@ -93,7 +93,7 @@ add fields that cannot work.
| --- | --- | --- | | --- | --- | --- |
| `title` | **keep** | 25/25 | | `title` | **keep** | 25/25 |
| `what` | **keep** | 25/25 — the load-bearing section | | `what` | **keep** | 25/25 — the load-bearing section |
| `where` | **keep, widen** | 25/25. Widen to allow "the fix belongs in another repo" — two corrections were exactly that (*"our INSTALLER, installing files in a WRONG FOLDER"*, *"The real fix is in ~/screen-locker (a different repo)"*) | | `where` | **keep, widen** | 25/25. Widen to allow "the fix belongs in another repo" — two corrections were exactly that (*"our INSTALLER, installing files in a WRONG FOLDER"*, *"The real fix is in ~/src/screen-locker (a different repo)"*) |
| `tech` | **merge into `where`** | Claude reads the manifest anyway in 54% of sessions. Load-bearing only for `where — new app: <name>`, which is where it should live | | `tech` | **merge into `where`** | Claude reads the manifest anyway in 54% of sessions. Load-bearing only for `where — new app: <name>`, which is where it should live |
| `must` | **keep** | 25/25 | | `must` | **keep** | 25/25 |
| `ask` | **remove** | Provably inert: 92% ask rate without it vs 100% with it. Global rules already own this | | `ask` | **remove** | Provably inert: 92% ask rate without it vs 100% with it. Global rules already own this |

View File

@ -120,7 +120,7 @@
<li><code>watchNotes()</code> — a <em>live stream</em>: it re-runs its <code>SELECT&nbsp;*</code> and re-emits <strong>every time the table changes</strong>, so the UI can stay in sync automatically.</li> <li><code>watchNotes()</code> — a <em>live stream</em>: it re-runs its <code>SELECT&nbsp;*</code> and re-emits <strong>every time the table changes</strong>, so the UI can stay in sync automatically.</li>
</ul> </ul>
</li> </li>
<li>A plain-text <strong>Markdown backup</strong> on disk (<code>~/todo/BACKLOG.md</code>), managed by <code>LocalBackup</code>. It's a human-readable third copy you (or an LLM) can read directly. <code>LocalBackup</code> debounces so a burst of typing produces a single file write.</li> <li>A plain-text <strong>Markdown backup</strong> on disk (<code>~/src/todo/BACKLOG.md</code>), managed by <code>LocalBackup</code>. It's a human-readable third copy you (or an LLM) can read directly. <code>LocalBackup</code> debounces so a burst of typing produces a single file write.</li>
</ul> </ul>
<p>The subtle part is how those two were wired together. To keep the backup current, the capture screen subscribed to <code>watchNotes()</code> and handed each emission to the backup:</p> <p>The subtle part is how those two were wired together. To keep the backup current, the capture screen subscribed to <code>watchNotes()</code> and handed each emission to the backup:</p>

View File

@ -29,8 +29,10 @@ echo "==> Compiling the desktop wrapper..."
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies # `dart build cli`, not `dart compile exe`: the package pulls in dependencies
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses # with native build hooks (sqlite3, objective_c), which `dart compile` refuses
# to handle even though the wrapper itself uses none of them. # to handle even though the wrapper itself uses none of them.
# --target is required since bin/ also holds the todo_note CLI: with two
# entry points `dart build cli` refuses to guess and the install aborts.
rm -rf "$SCRIPT_DIR/build/cli" rm -rf "$SCRIPT_DIR/build/cli"
dart build cli -o "$SCRIPT_DIR/build/cli" dart build cli -t "$SCRIPT_DIR/bin/todo_desktop.dart" -o "$SCRIPT_DIR/build/cli"
echo "==> Generating PKGBUILD..." echo "==> Generating PKGBUILD..."
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated # pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated

View File

@ -0,0 +1,51 @@
/// A single, structured analytics event.
///
/// Interaction-only by construction: [params] holds enum values, counts,
/// durations and booleans — never note text or other free-form user input.
/// Callers are trusted to uphold that; see `analytics_service.dart` for the
/// full policy.
class AnalyticsEvent {
/// Creates an [AnalyticsEvent] with the given [name], [params] and
/// [timestamp].
const AnalyticsEvent({
required this.name,
required this.timestamp,
this.params = const {},
});
/// Short, stable event identifier, e.g. `'screen_view'`, `'sort_changed'`.
final String name;
/// When the event happened.
final DateTime timestamp;
/// Structured parameters. Values must be JSON-encodable primitives
/// (String, num, bool, or null) — never note text.
final Map<String, Object?> params;
/// Serializes to a JSON-encodable map for local buffering and the
/// Firebase flush.
Map<String, Object?> toJson() => {
'name': name,
'timestamp': timestamp.toIso8601String(),
'params': params,
};
/// Reconstructs an [AnalyticsEvent] from [toJson]'s output. Returns null
/// for a malformed entry (e.g. a buffer corrupted by a previous crash)
/// rather than throwing — analytics must never crash capture.
static AnalyticsEvent? tryFromJson(Object? json) {
if (json is! Map) return null;
final name = json['name'];
final timestamp = DateTime.tryParse('${json['timestamp']}');
final params = json['params'];
if (name is! String || timestamp == null) return null;
return AnalyticsEvent(
name: name,
timestamp: timestamp,
params: params is Map
? Map<String, Object?>.from(params)
: const <String, Object?>{},
);
}
}

View File

@ -0,0 +1,117 @@
/// Interaction-only usage analytics: what was tapped, selected, opened, for
/// how long — never note text or other free-form input.
///
/// Buffered in `SharedPreferences` (a JSON-encoded list, capped so a device
/// that never reaches Firebase can't grow it without bound) and flushed to
/// the shared `kuhy-syncs` Firebase RTDB project during the same sync pass
/// that already opens an authenticated client for notes and settings — see
/// `run_sync.dart`.
///
/// `SharedPreferences` rather than a new on-disk file or a new table in the
/// notes CRDT database: the desktop build has no filesystem (see
/// `local_backup_factory_web.dart`, which routes through the local wrapper
/// server for that reason), and a schema migration on the notes database
/// carries blast radius onto live user data for a feature that is allowed to
/// be lossy. `SharedPreferences` is already trusted for the sync-status
/// fields in `capture_screen.dart`.
library;
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo/analytics/analytics_event.dart';
/// Where a flushed batch lands in the shared RTDB project, sibling to
/// `changesets/<nodeId>.json` and `settings/advancedMode`.
String analyticsRemotePath(String nodeId, String batchId) =>
'analytics/$nodeId/$batchId';
/// Buffers and flushes [AnalyticsEvent]s.
class AnalyticsService {
/// Creates an [AnalyticsService] for the device identified by [nodeId].
const AnalyticsService({required this.nodeId});
/// This device's id, matching the one `SyncService` uses for its own
/// changeset file — so a batch's origin is traceable without carrying any
/// user-identifying data beyond what already syncs.
final String nodeId;
static const _kBuffer = 'analytics.buffer';
/// Buffer cap: a device that never reaches Firebase must not grow this
/// list without bound (`SharedPreferences` loads synchronously into memory
/// at startup on Android). Oldest events are dropped first — analytics is
/// lossy by nature, and a stalled flush must never slow app launch.
static const maxBufferedEvents = 500;
/// Appends [event] to the local buffer, dropping the oldest event first
/// if already at [maxBufferedEvents].
Future<void> logEvent(AnalyticsEvent event) async {
final prefs = await SharedPreferences.getInstance();
final buffered = _readBuffer(prefs)..add(event);
final trimmed = buffered.length > maxBufferedEvents
? buffered.sublist(buffered.length - maxBufferedEvents)
: buffered;
await _writeBuffer(prefs, trimmed);
}
/// Flushes the current buffer to [client] as one batch.
///
/// Claims the buffer (clears it locally) before the network call, rather
/// than sending then subtracting by count: subtracting assumes the buffer
/// only ever grows during the push, which [logEvent]'s cap-eviction breaks
/// (it can trim from the *front*), so a mid-flush event could be counted
/// as already sent and silently dropped. Claim-then-restore has a simpler
/// failure mode instead: an event logged mid-flush lands in a buffer this
/// call no longer owns and survives untouched; a failed push puts the
/// claimed batch back in front of it, in original order.
///
/// A push failure (offline, not signed in, expired session) leaves the
/// buffer as if nothing happened; the next `runSync()` pass retries.
/// Never throws.
Future<void> flush(FirebaseRestClient? client) async {
if (client == null) return;
final prefs = await SharedPreferences.getInstance();
final pending = _readBuffer(prefs);
if (pending.isEmpty) return;
await _writeBuffer(prefs, const []);
final batchId = DateTime.now().toUtc().millisecondsSinceEpoch.toString();
try {
await client.putFileText(
analyticsRemotePath(nodeId, batchId),
jsonEncode([for (final e in pending) e.toJson()]),
message: 'crdt_sync: analytics batch',
);
} on RemoteSyncError {
// Catches FirebaseSyncError (network) and FirebaseAuthError (session
// expired) alike — both are RemoteSyncError, and only catching the
// narrower sibling type used to let an auth failure escape and turn
// an otherwise-successful sync pass into a reported failure.
final since = _readBuffer(prefs);
await _writeBuffer(prefs, [...pending, ...since]);
}
}
List<AnalyticsEvent> _readBuffer(SharedPreferences prefs) {
final raw = prefs.getString(_kBuffer);
if (raw == null || raw.isEmpty) return [];
final decoded = jsonDecode(raw);
if (decoded is! List) return [];
return [for (final entry in decoded) ?AnalyticsEvent.tryFromJson(entry)];
}
Future<void> _writeBuffer(
SharedPreferences prefs,
List<AnalyticsEvent> events,
) async {
if (events.isEmpty) {
await prefs.remove(_kBuffer);
return;
}
await prefs.setString(
_kBuffer,
jsonEncode([for (final e in events) e.toJson()]),
);
}
}

View File

@ -0,0 +1,6 @@
/// `postFile` for the current platform: the browser's own `fetch` on the
/// desktop web build, so a picked file streams from disk to the wrapper
/// without ever becoming a Dart byte list.
library;
export 'file_post_io.dart' if (dart.library.js_interop) 'file_post_web.dart';

View File

@ -0,0 +1,9 @@
/// Off the web nothing posts files to the wrapper: Android stores them
/// itself.
library;
import 'package:todo/attachments/image_store_api.dart';
/// Always throws; only the desktop page posts files.
Future<({int status, String body})> postFile(Uri url, XFile file) =>
throw UnsupportedError('Only the desktop page posts files');

View File

@ -0,0 +1,23 @@
/// POSTs a picked or dropped file to the desktop wrapper with `fetch`.
///
/// `package:http`'s browser client buffers a request body whole, and
/// `XFile.readAsBytes` copies the file into Dart: either would put a
/// multi-gigabyte attachment in the page's memory. Handing the file's own
/// Blob to `fetch` lets the browser stream it from disk instead.
library;
import 'dart:js_interop';
import 'package:todo/attachments/image_store_api.dart';
import 'package:web/web.dart' as web;
/// POSTs [file] to [url]. [file]'s path is the object URL that file_selector
/// or the drop listener created for it.
Future<({int status, String body})> postFile(Uri url, XFile file) async {
final source = await web.window.fetch(file.path.toJS).toDart;
final blob = await source.blob().toDart;
final response = await web.window
.fetch(url.toString().toJS, web.RequestInit(method: 'POST', body: blob))
.toDart;
return (status: response.status, body: (await response.text().toDart).toDart);
}

View File

@ -0,0 +1,56 @@
/// The phone's copy of the `todo` dufs login password, in the OS keystore.
///
/// Created on the PC by `add_dufs_login.sh todo /todo-images rw` and pasted
/// into Settings → Cloud images. The desktop never uses this: its wrapper
/// reads `~/.config/dufs/logins/todo.env` instead.
library;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:todo/images/dufs_image_client.dart';
/// The login name `add_dufs_login.sh` was run with.
const kDufsImagesUser = 'todo';
/// Reads and writes the password; failures read as "no password".
class ImagePasswordStore {
/// Creates a store over [storage] (injectable for tests).
const ImagePasswordStore({FlutterSecureStorage? storage})
: _storage = storage ?? const FlutterSecureStorage();
final FlutterSecureStorage _storage;
static const _key = 'dufsImagesPassword';
/// The saved password, or '' when none is set or the keystore is
/// unavailable.
Future<String> read() async {
try {
return await _storage.read(key: _key) ?? '';
} on Exception {
return '';
}
}
/// Saves [password] (an empty one deletes it); false if the keystore is
/// unavailable.
Future<bool> write(String password) async {
try {
if (password.isEmpty) {
await _storage.delete(key: _key);
} else {
await _storage.write(key: _key, value: password);
}
return true;
} on Exception {
return false;
}
}
/// The full login, or null when no password is saved.
Future<DufsLogin?> login() async {
final password = await read();
if (password.isEmpty) return null;
return DufsLogin(user: kDufsImagesUser, password: password);
}
}

View File

@ -0,0 +1,7 @@
/// `openImageStore()` for the current platform: app storage + direct dufs on
/// Android, the local wrapper's `/images/*` routes on the desktop web build.
library;
export 'image_store_api.dart';
export 'image_store_io.dart'
if (dart.library.js_interop) 'image_store_web.dart';

View File

@ -0,0 +1,133 @@
/// What the UI asks of attachments (images and any other file),
/// independent of platform.
///
/// Android keeps attachments itself (an `ImageCacheStore` in app storage,
/// talking to dufs directly); the desktop web page delegates everything to
/// the local wrapper's `/images/*` routes. Both implement [ImageStore],
/// picked by the conditional export in `image_store.dart`.
library;
import 'package:file_selector/file_selector.dart' show XFile;
import 'package:flutter/foundation.dart';
import 'package:todo/images/attachment_links.dart';
import 'package:todo/images/attachment_ref.dart';
export 'package:file_selector/file_selector.dart' show XFile;
/// Where to draw an image from right now.
sealed class ImageSource {
const ImageSource();
}
/// A file on this device.
final class LocalImageSource extends ImageSource {
/// Creates a source for the file at [path].
const LocalImageSource(this.path);
/// Absolute path of the cached JPEG.
final String path;
}
/// A same-origin URL served by the desktop wrapper.
final class NetworkImageSource extends ImageSource {
/// Creates a source for [url].
const NetworkImageSource(this.url);
/// The wrapper URL, e.g. `http://localhost:8730/images/<noteId>/<uuid>.jpg`.
final String url;
}
/// Not on this device yet (it downloads on the next reconcile).
final class MissingImageSource extends ImageSource {
/// The one instance.
const MissingImageSource();
}
/// Summary for the settings screen.
class ImageStoreStatus {
/// Creates a status.
const ImageStoreStatus({required this.configured, required this.pending});
/// Whether a dufs login is available to this device.
final bool configured;
/// Images waiting to upload.
final int pending;
}
/// Thrown by [ImageStore.attach] when the image could not be stored at all.
class ImageStoreException implements Exception {
/// Creates an exception carrying [message].
const ImageStoreException(this.message);
/// What went wrong, shown to the user.
final String message;
@override
String toString() => message;
}
/// Stores, shows and syncs the attachments notes link to. Notifies when one
/// becomes available or changes state, so embeds can redraw.
abstract class ImageStore extends ChangeNotifier {
/// Stores [bytes] (any image format) for [noteId] and queues the upload.
///
/// Returns the new ref, or null when [bytes] is not an image. Throws
/// [ImageStoreException] when it cannot be stored.
Future<AttachmentRef?> attach(String noteId, Uint8List bytes);
/// Stores the picked or dropped [file] for [noteId] — re-encoded when it is
/// an image, byte-for-byte otherwise, whatever its size — and queues the
/// upload. Throws [ImageStoreException] when it cannot be stored.
Future<Attachment> attachFile(String noteId, XFile file);
/// Uploads the queue, fetches every attachment [noteTexts] link to that
/// this device lacks, and evicts cached ones no note links to.
Future<void> reconcile(Iterable<String> noteTexts);
/// Where to draw [ref] from.
ImageSource sourceFor(AttachmentRef ref);
/// Whether [ref] is still waiting to upload (always false when unknown).
bool isPending(AttachmentRef ref);
/// Size in bytes of [ref] on this device, or null when it is not here yet.
Future<int?> sizeOf(AttachmentRef ref);
/// Login and queue summary.
Future<ImageStoreStatus> status();
}
/// Every attachment ref across [noteTexts].
Set<AttachmentRef> attachmentRefsAcross(Iterable<String> noteTexts) => {
for (final text in noteTexts) ...attachmentRefsIn(text),
};
/// The store used where none was provided (tests, and any screen built
/// outside the app root): attaching is refused, nothing is ever available.
class NoImageStore extends ImageStore {
@override
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async =>
throw const ImageStoreException('Images are not available here');
@override
Future<Attachment> attachFile(String noteId, XFile file) async =>
throw const ImageStoreException('Attachments are not available here');
@override
Future<void> reconcile(Iterable<String> noteTexts) async {}
@override
ImageSource sourceFor(AttachmentRef ref) => const MissingImageSource();
@override
bool isPending(AttachmentRef ref) => false;
@override
Future<int?> sizeOf(AttachmentRef ref) async => null;
@override
Future<ImageStoreStatus> status() async =>
const ImageStoreStatus(configured: false, pending: 0);
}

View File

@ -0,0 +1,139 @@
/// Android: attachments live in app storage and sync with dufs directly.
library;
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:todo/attachments/image_password_store.dart';
import 'package:todo/attachments/image_store_api.dart';
import 'package:todo/images/attachment_ingest.dart';
import 'package:todo/images/attachment_ref.dart';
import 'package:todo/images/dufs_image_client.dart';
import 'package:todo/images/image_cache_store.dart';
import 'package:todo/images/image_processing.dart';
/// Opens the store under the app-support directory's `images/`.
// coverage:ignore-start
// Platform wiring only: path_provider has no binding in unit tests, which
// construct [IoImageStore] over a temp directory instead.
Future<ImageStore> openImageStore() async {
final support = await getApplicationSupportDirectory();
final root = Directory(p.join(support.path, 'images'));
// Both pickers copy what they return into the cache directory.
final pickerCopies = (await getTemporaryDirectory()).path;
return IoImageStore(ImageCacheStore(root), pickerCopies: pickerCopies);
}
// coverage:ignore-end
/// [ImageStore] over a local [ImageCacheStore], uploading with the login
/// from [ImagePasswordStore].
class IoImageStore extends ImageStore {
/// Creates a store over [cache]. Picked files under [pickerCopies] are the
/// pickers' private copies and are moved rather than copied. The rest is
/// injectable for tests.
IoImageStore(
this.cache, {
this.pickerCopies,
this._passwords = const ImagePasswordStore(),
http.Client Function()? httpClient,
Future<Uint8List?> Function(Uint8List)? prepare,
}) : _httpClient = httpClient ?? http.Client.new,
_prepare = prepare ?? prepareImageInBackground,
_ingest = AttachmentIngest(
cache,
prepare: prepare ?? prepareImageInBackground,
);
/// The on-device attachments and upload queue.
final ImageCacheStore cache;
/// Directory the pickers copy their results into, if known.
final String? pickerCopies;
final ImagePasswordStore _passwords;
final http.Client Function() _httpClient;
final Future<Uint8List?> Function(Uint8List) _prepare;
final AttachmentIngest _ingest;
@override
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async {
final jpeg = await _prepare(bytes);
if (jpeg == null) return null;
final ref = AttachmentRef.create(noteId);
try {
await cache.put(ref, jpeg);
} on FileSystemException catch (e) {
throw ImageStoreException('Could not save the image: ${e.message}');
}
notifyListeners();
// Upload right away when online. An empty ref set never evicts, so this
// cannot race the link reaching the note.
unawaited(_sync(const {}));
return ref;
}
@override
Future<Attachment> attachFile(String noteId, XFile file) async {
final copies = pickerCopies;
final Attachment attachment;
try {
attachment = await _ingest.fromFile(
noteId,
file.name,
File(file.path),
move: copies != null && p.isWithin(copies, file.path),
);
} on FileSystemException catch (e) {
throw ImageStoreException('Could not save ${file.name}: ${e.message}');
}
notifyListeners();
unawaited(_sync(const {}));
return attachment;
}
@override
Future<void> reconcile(Iterable<String> noteTexts) =>
_sync(attachmentRefsAcross(noteTexts));
Future<void> _sync(Set<AttachmentRef> refs) async {
final login = await _passwords.login();
final client = login == null
? null
: DufsImageClient(login, httpClient: _httpClient());
try {
final report = await cache.reconcile(refs, client);
if (report.uploaded + report.downloaded + report.evicted > 0) {
notifyListeners();
}
} finally {
client?.close();
}
}
@override
ImageSource sourceFor(AttachmentRef ref) {
final file = cache.fileFor(ref);
return file.existsSync()
? LocalImageSource(file.path)
: const MissingImageSource();
}
@override
bool isPending(AttachmentRef ref) => cache.isPending(ref);
@override
Future<int?> sizeOf(AttachmentRef ref) async {
final file = cache.fileFor(ref);
return file.existsSync() ? await file.length() : null;
}
@override
Future<ImageStoreStatus> status() async => ImageStoreStatus(
configured: await _passwords.login() != null,
pending: cache.pending().length,
);
}

View File

@ -0,0 +1,29 @@
import 'package:flutter/widgets.dart';
import 'package:todo/attachments/image_store_api.dart';
/// Makes the app's one [ImageStore] reachable from any widget below it,
/// without threading it through every screen constructor.
///
/// Screens built without a scope (most widget tests) get a shared
/// [NoImageStore], so they render and simply cannot attach.
class ImageStoreScope extends InheritedNotifier<ImageStore> {
/// Provides [store] to [child].
const ImageStoreScope({
required ImageStore store,
required super.child,
super.key,
}) : super(notifier: store);
static final ImageStore _none = NoImageStore();
/// The nearest store, subscribing [context] to its changes.
static ImageStore of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ImageStoreScope>()?.notifier ??
_none;
/// The nearest store, without subscribing (for callbacks).
static ImageStore read(BuildContext context) =>
context.getInheritedWidgetOfExactType<ImageStoreScope>()?.notifier ??
_none;
}

View File

@ -0,0 +1,158 @@
/// Desktop (web build): every attachment operation goes through the local
/// wrapper's `/images/*` routes; the page never sees the dufs password.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:todo/attachments/file_post.dart' as file_post;
import 'package:todo/attachments/image_store_api.dart';
import 'package:todo/images/attachment_ref.dart';
import 'package:todo/sync/desktop_wrapper.dart';
/// Opens the store against the wrapper that served this page.
Future<ImageStore> openImageStore() async =>
WebImageStore(origin: servingWrapperOrigin());
/// Sends a file to the wrapper and returns its answer; injectable for tests.
typedef FilePost =
Future<({int status, String body})> Function(Uri url, XFile file);
/// [ImageStore] backed by the desktop wrapper at [origin].
class WebImageStore extends ImageStore {
/// Creates a store talking to [origin]; [httpClient] and [postFile] are
/// injectable.
WebImageStore({
required this.origin,
http.Client? httpClient,
FilePost? postFile,
}) : _http = httpClient ?? http.Client(),
_postFile = postFile ?? file_post.postFile;
/// The wrapper's origin, e.g. `http://localhost:8730`.
final String origin;
final http.Client _http;
final FilePost _postFile;
// Sizes the wrapper reported. A ref's bytes never change (a fresh uuid per
// attachment), so a known size never goes stale.
final Map<AttachmentRef, int> _sizes = {};
// Bumped whenever the wrapper may hold new bytes, so an image that failed
// to load (not downloaded yet) is requested again under a fresh URL.
int _revision = 0;
Uri _images(String rest) => Uri.parse('$origin/images/$rest');
@override
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async {
final ref = AttachmentRef.create(noteId);
final http.Response response;
try {
response = await _http.post(_images(ref.relativePath), body: bytes);
} on Exception {
throw const ImageStoreException(
'The desktop helper is not running; the image was not saved',
);
}
if (response.statusCode == 415) return null;
if (response.statusCode != 204) {
throw ImageStoreException(
'The desktop helper refused the image (${response.statusCode})',
);
}
_revision++;
notifyListeners();
unawaited(_reconcile(const {}));
return ref;
}
@override
Future<Attachment> attachFile(String noteId, XFile file) async {
final url = _images(
'attach',
).replace(queryParameters: {'note': noteId, 'name': file.name});
final ({int status, String body}) response;
try {
response = await _postFile(url, file);
} on Object {
throw ImageStoreException(
'The desktop helper is not running; ${file.name} was not saved',
);
}
if (response.status != 200) {
throw ImageStoreException(
'The desktop helper refused ${file.name} (${response.status})',
);
}
final attachment = Attachment.fromJson(jsonDecode(response.body));
_revision++;
notifyListeners();
unawaited(_reconcile(const {}));
return attachment;
}
@override
Future<void> reconcile(Iterable<String> noteTexts) =>
_reconcile(attachmentRefsAcross(noteTexts));
Future<void> _reconcile(Set<AttachmentRef> refs) async {
try {
final response = await _http.post(
_images('reconcile'),
headers: {'content-type': 'application/json'},
body: jsonEncode({
'refs': [for (final ref in refs) ref.relativePath],
}),
);
if (response.statusCode != 200) return;
final report = jsonDecode(response.body) as Map<String, dynamic>;
if ((report['downloaded'] as int? ?? 0) > 0) {
_revision++;
notifyListeners();
}
} on Exception {
// Best-effort: the next sync, resume or attach reconciles again.
}
}
@override
ImageSource sourceFor(AttachmentRef ref) =>
NetworkImageSource('$origin/images/${ref.relativePath}?r=$_revision');
@override
bool isPending(AttachmentRef ref) => false;
@override
Future<int?> sizeOf(AttachmentRef ref) async {
if (_sizes[ref] case final known?) return known;
try {
final response = await _http.head(_images(ref.relativePath));
final length = response.statusCode == 200
? int.tryParse(response.headers['content-length'] ?? '')
: null;
if (length != null) _sizes[ref] = length;
return length;
} on Exception {
return null;
}
}
@override
Future<ImageStoreStatus> status() async {
try {
final response = await _http.get(_images('status'));
final body = jsonDecode(response.body) as Map<String, dynamic>;
return ImageStoreStatus(
configured: body['configured'] as bool? ?? false,
pending: body['pending'] as int? ?? 0,
);
} on Exception {
return const ImageStoreStatus(configured: false, pending: 0);
}
}
}

226
lib/cli/cli_args.dart Normal file
View File

@ -0,0 +1,226 @@
/// Hand-rolled argument parsing for `bin/todo_note.dart`.
///
/// Deliberately not `package:args`: a handful of flags do not justify a new
/// exact-pinned dependency under the freshness gate.
library;
import 'package:todo/cli/cli_mode.dart';
import 'package:todo/data/note.dart';
export 'package:todo/cli/cli_mode.dart';
export 'package:todo/cli/cli_usage.dart';
/// The parsed command line.
class CliArgs {
/// Creates parsed arguments; see [parse].
const CliArgs({
required this.mode,
this.text,
this.id,
this.priority = Priority.medium,
this.status,
this.dataDir,
this.newNote = false,
this.dryRun = false,
this.opts = (
repo: null,
query: null,
doneCheck: null,
by: null,
evidence: null,
),
});
/// Parses [argv]. Throws [UsageError] on anything it does not understand.
factory CliArgs.parse(List<String> argv) {
final opts = <String, String>{};
String? id;
final modes = <CliMode>{};
for (var i = 0; i < argv.length; i++) {
final arg = argv[i];
String value() {
if (i + 1 >= argv.length) throw UsageError('$arg needs a value');
return argv[++i];
}
switch (arg) {
case '--new-note':
opts[arg] = '';
case '-h' || '--help':
modes.add(CliMode.help);
case '--text' || '--priority' || '--status' || '--data-dir':
case '--repo' || '--done-check' || '--by' || '--evidence':
opts[arg] = value();
case '--list':
modes.add(CliMode.list);
case '--backfill-created-by':
modes.add(CliMode.backfill);
case '--dry-run':
opts[arg] = 'true';
case '--search':
modes.add(CliMode.search);
opts[arg] = value();
case '--get' || '--delete' || '--close':
modes.add(CliMode.values.byName(arg.substring(2)));
id = value();
case '--set-text':
modes.add(CliMode.setText);
id = value();
case '--set-status':
modes.add(CliMode.setStatus);
id = value();
opts[arg] = value();
default:
throw UsageError('unknown argument: $arg');
}
}
if (modes.contains(CliMode.help)) return const CliArgs(mode: CliMode.help);
if (modes.length > 1) {
throw UsageError(
'--list, --search, --get, --delete, --set-status, --set-text, '
'--close and '
'--backfill-created-by are mutually exclusive',
);
}
final mode = modes.isEmpty ? CliMode.add : modes.single;
_checkScopes(opts.keys, mode);
final rawStatus = opts['--set-status'] ?? opts['--status'];
return CliArgs(
mode: mode,
text: opts['--text'],
id: id,
priority: opts['--priority'] == null
? Priority.medium
: _byName(Priority.values, opts['--priority']!, '--priority'),
status: rawStatus == null
? null
: _byName(Status.values, rawStatus, '--status', _statusName),
dataDir: opts['--data-dir'],
newNote:
opts.containsKey('--new-note') &&
(opts['--repo'] != null ||
(throw UsageError('--new-note needs --repo'))),
dryRun: opts.containsKey('--dry-run'),
opts: (
repo: _repo(opts['--repo']),
query: _nonBlank(opts['--search'], '--search'),
doneCheck: _nonBlank(opts['--done-check'], '--done-check'),
by: opts['--by'] == null ? null : _by(opts['--by']!),
evidence: _evidence(opts['--evidence'], mode),
),
);
}
/// The selected mode.
final CliMode mode;
/// Note text from `--text`; null means "read stdin" in [CliMode.add] and
/// [CliMode.setText].
final String? text;
/// Full id or 8+ character prefix of the note an id mode acts on.
final String? id;
/// Priority of a new note.
final Priority priority;
/// New note's status, [CliMode.setStatus]'s target, or a list filter.
final Status? status;
/// Overrides the default data dir (a second, independent node).
final String? dataDir;
/// `--new-note`: the `--repo` task gets its own note.
final bool newNote;
/// Whether `--dry-run` was given: report what would change, change nothing.
final bool dryRun;
/// `--repo`, `--search`, `--done-check`, `--by` and `--evidence` values.
final ({
String? repo,
String? query,
String? doneCheck,
String? by,
String? evidence,
})
opts;
/// The command-line spelling of [status] (`in_progress`, not `inProgress`).
static String statusName(Status status) => _statusName(status);
static const _adding = 'when adding a note';
static const Map<String, (String, Set<CliMode>)> _scopes = {
'--text': ('$_adding or to --set-text', {CliMode.add, CliMode.setText}),
'--done-check': (_adding, {CliMode.add}),
'--by': (_adding, {CliMode.add}),
'--repo': (
'$_adding, to --list or to --search',
{CliMode.add, CliMode.list, CliMode.search},
),
'--evidence': ('to --close', {CliMode.close}),
'--new-note': (_adding, {CliMode.add}),
'--dry-run': ('to --backfill-created-by', {CliMode.backfill}),
};
static void _checkScopes(Iterable<String> flags, CliMode mode) {
for (final flag in flags) {
final scope = _scopes[flag];
if (scope != null && !scope.$2.contains(mode)) {
throw UsageError('$flag only applies ${scope.$1}');
}
}
}
static final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
static String? _repo(String? raw) {
if (raw == null || _repoShape.hasMatch(raw)) return raw;
throw UsageError(
'--repo must look like owner/name (e.g. kuhyx/todo), got "$raw"',
);
}
static String _by(String raw) {
if (kNoteAuthors.contains(raw)) return raw;
throw UsageError(
'--by must be one of ${kNoteAuthors.join('|')}, got "$raw"',
);
}
static String? _evidence(String? raw, CliMode mode) {
if (mode == CliMode.close && (raw == null || raw.trim().isEmpty)) {
throw UsageError(
'--close needs --evidence <commit sha + done check exit code>: '
'a task is only closed with proof',
);
}
return raw;
}
static String? _nonBlank(String? raw, String flag) {
if (raw != null && raw.trim().isEmpty) {
throw UsageError('$flag must not be empty');
}
return raw;
}
static String _statusName(Enum value) =>
value == Status.inProgress ? 'in_progress' : value.name;
static T _byName<T extends Enum>(
List<T> values,
String raw,
String flag, [
String Function(Enum) nameOf = _plainName,
]) {
for (final v in values) {
if (nameOf(v) == raw) return v;
}
throw UsageError(
'$flag must be one of ${values.map(nameOf).join('|')}, got "$raw"',
);
}
static String _plainName(Enum value) => value.name;
}

206
lib/cli/cli_commands.dart Normal file
View File

@ -0,0 +1,206 @@
import 'package:todo/cli/cli_args.dart';
import 'package:todo/cli/cli_session.dart';
import 'package:todo/cli/note_lookup.dart';
import 'package:todo/data/note.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/data/repo_note.dart';
import 'package:todo/data/repo_note_split.dart';
import 'package:todo/sync/sync_service.dart';
import 'package:uuid/uuid.dart';
/// One CLI command per method over an open [CliSession]; each returns the
/// exit code. Id arguments are resolved by [findNote].
class CliCommands {
/// Writes results to the first sink, errors and warnings to the second.
CliCommands(this.session, this._out, this._err);
/// The open session the commands act on.
final CliSession session;
final StringSink _out;
final StringSink _err;
/// Creates a note and pushes it. A `--repo` add joins the repo's open note.
Future<int> add(CliArgs args, String text) async {
final repo = args.opts.repo;
final status = args.status ?? Status.todo;
if (repo != null && kOpenStatuses.contains(status)) {
return await _addRepoTask(args, repo, text);
}
final now = DateTime.now();
final note = Note(
id: const Uuid().v4(),
text: text,
priority: args.priority,
status: status,
createdAt: now,
updatedAt: now,
repo: repo,
doneCheck: args.opts.doneCheck,
by: args.opts.by,
createdBy: 'claude',
);
await session.repository.upsert(note);
if (!await _push('note')) return 1;
_out.writeln(note.id);
return 0;
}
Future<int> _addRepoTask(CliArgs args, String repo, String text) async {
_report(await session.sync(push: true));
final (:title, :body) = splitNote(text);
if (args.newNote) return await _addSeparate(args, repo, title, body);
final added = await addRepoTask(
session.repository,
repo: repo,
title: title,
body: body,
doneCheck: args.opts.doneCheck,
priority: args.priority,
by: args.opts.by,
createdBy: 'claude',
);
await _save(added.note);
if (!await _push('note')) return 1;
if (added.appended) _err.writeln('appended to the open note for $repo');
_out.writeln(added.note.id);
return 0;
}
Future<int> _addSeparate(
CliArgs args,
String repo,
String title,
String body,
) async {
final added = await addSeparateTask(
session.repository,
repo: repo,
title: title,
body: body,
doneCheck: args.opts.doneCheck,
priority: args.priority,
by: args.opts.by,
createdBy: 'claude',
);
await _save(added.note);
if (!await _push('note')) return 1;
if (added.kind == SplitKind.merged) {
_err.writeln(
'merged into the separate note with that title; '
'click Start on the board by hand',
);
}
_out.writeln(added.note.id);
return 0;
}
/// Prints [listLine] for each note matching the filters in [args].
Future<int> list(CliArgs args) async {
_report(await session.sync(push: false));
final notes = await session.repository.listNotes(
filter: NoteFilter(
query: args.opts.query ?? '',
statuses: {?args.status},
repo: args.opts.repo,
),
);
notes.map(listLine).forEach(_out.writeln);
return 0;
}
/// Prints one note in full.
Future<int> get(String ref) async {
_report(await session.sync(push: false));
_out.writeln(
noteDetail(findNote(await session.repository.listNotes(), ref)),
);
return 0;
}
/// Tombstones a note and pushes the deletion.
Future<int> delete(String ref) async {
final note = await _pullAndFind(ref);
await session.repository.delete(note.id);
if (!await _push('deletion')) return 1;
_out.writeln('deleted ${note.id}');
return 0;
}
/// Changes a note's status and pushes it.
Future<int> setStatus(String ref, Status status) async {
final note = await _pullAndFind(ref);
await _save(note.copyWith(status: status));
if (!await _push('status change')) return 1;
_out.writeln('${note.id}\t${CliArgs.statusName(status)}');
return 0;
}
/// Replaces a note's whole text (title is its first line) and pushes it.
Future<int> setText(String ref, String text) async {
final note = await _pullAndFind(ref);
await _save(note.copyWith(text: text));
if (!await _push('text change')) return 1;
_out.writeln('${note.id}\ttext');
return 0;
}
/// Marks a note done with [evidence], keeping it, and pushes it.
Future<int> close(String ref, String evidence) async {
final note = await _pullAndFind(ref);
await _save(note.copyWith(status: Status.done, evidence: evidence));
if (!await _push('close')) return 1;
_out.writeln('closed ${note.id}');
return 0;
}
/// Sets `created_by` where unset (see [NoteRepository.backfillCreatedBy]).
/// Prints one `<id>\t<value>\t<title>` line per note, then the totals. With
/// [dryRun] nothing is written or pushed, and peers are only read.
Future<int> backfillCreatedBy(
Set<String> claudeNodes, {
required bool dryRun,
}) async {
_report(await session.sync(push: !dryRun));
final plan = await session.repository.backfillCreatedBy(
claudeNodes,
dryRun: dryRun,
);
final titles = {
for (final n in await session.repository.listNotes()) n.id: n,
};
for (final MapEntry(:key, :value) in plan.entries) {
final note = titles[key];
final title = note == null ? '' : note.text.split('\n').first;
_out.writeln(
'${key.substring(0, key.length.clamp(0, 8))}\t$value\t$title',
);
}
final claude = plan.values.where((v) => v == 'claude').length;
final kuhy = plan.length - claude;
_out.writeln('${dryRun ? 'dry run' : 'set'}: claude $claude, kuhy $kuhy');
if (dryRun || plan.isEmpty) return 0;
return await _push('backfill') ? 0 : 1;
}
Future<Note> _pullAndFind(String ref) async {
_report(await session.sync(push: true));
return findNote(await session.repository.listNotes(), ref);
}
Future<void> _save(Note note) =>
session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
Future<bool> _push(String what) async {
if (_report(await session.sync(push: true)).pushed) return true;
_err.writeln('error: $what saved locally but nothing was pushed');
return false;
}
SyncResult _report(SyncResult result) {
for (final name in result.skippedFiles) {
_err.writeln('warning: could not merge peer file $name');
}
return result;
}
}

47
lib/cli/cli_mode.dart Normal file
View File

@ -0,0 +1,47 @@
/// What the CLI can be asked to do, and how a bad command line is reported.
library;
/// What the CLI was asked to do.
enum CliMode {
/// Create a note and push it.
add,
/// Print every live note, one per line.
list,
/// Print one note in full.
get,
/// Tombstone one note and push the deletion.
delete,
/// Change one note's status and push it.
setStatus,
/// Replace one note's whole text and push it.
setText,
/// Set a task done with evidence and push it.
close,
/// Print the notes matching a query, as [list] does.
search,
/// Set `created_by` on notes that lack it.
backfill,
/// Print usage.
help,
}
/// Thrown for a malformed command line; maps to exit code 2.
class UsageError implements Exception {
/// Creates a [UsageError] carrying [message].
UsageError(this.message);
/// What was wrong with the arguments.
final String message;
@override
String toString() => message;
}

26
lib/cli/cli_paths.dart Normal file
View File

@ -0,0 +1,26 @@
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:todo/cli/cli_session.dart' show CliSession;
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`.
String defaultDataDir(Map<String, String> env) {
final xdg = env['XDG_DATA_HOME'] ?? '';
final base = xdg.isNotEmpty
? xdg
: p.join(env['HOME'] ?? '', '.local', 'share');
return p.join(base, 'todo-cli');
}
/// Node ids of the installs Claude files notes through: the MCP server and
/// the CLI under the same data root as [defaultDataDir]. Missing ones are
/// skipped.
Set<String> claudeNodeIds(Map<String, String> env) {
final cli = defaultDataDir(env);
return {
for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')])
if (File(p.join(dir, CliSession.nodeIdFileName)) case final f
when f.existsSync())
f.readAsStringSync().trim(),
}..remove('');
}

103
lib/cli/cli_runner.dart Normal file
View File

@ -0,0 +1,103 @@
/// The body of `bin/todo_note.dart`, with every side effect injected.
///
/// Lives in `lib/` so the tests can drive it with a fake RTDB, a temp data
/// dir and in-memory output sinks; the `bin/` entrypoint only wires the real
/// process streams and environment into [runCli].
library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:path/path.dart' as p;
import 'package:todo/cli/cli_args.dart';
import 'package:todo/cli/cli_commands.dart';
import 'package:todo/cli/cli_session.dart';
import 'package:todo/cli/note_lookup.dart';
/// Opens a [CliSession]; swapped in tests to point it at a fake backend.
typedef SessionOpener =
Future<CliSession> Function(
String dataDir, {
required String seedCredentials,
});
/// Reads all of [input] as text, or '' when it is an interactive terminal.
Future<String> readInput(
Stream<List<int>> input, {
required bool hasTerminal,
}) async {
if (hasTerminal) return '';
return (await input.transform(utf8.decoder).join()).trimRight();
}
/// Runs the CLI for [argv] and returns its exit code.
Future<int> runCli(
List<String> argv, {
required Map<String, String> env,
required StringSink out,
required StringSink err,
required Future<String> Function() readStdin,
SessionOpener open = CliSession.open,
}) async {
final CliArgs args;
try {
args = CliArgs.parse(argv);
} on UsageError catch (error) {
err
..writeln('error: $error')
..writeln(kUsage);
return 2;
}
if (args.mode == CliMode.help) {
out.writeln(kUsage);
return 0;
}
String? text;
if (args.mode == CliMode.add || args.mode == CliMode.setText) {
text = args.text ?? await readStdin();
if (text.trim().isEmpty) {
err.writeln('error: empty note (pass --text or pipe text on stdin)');
return 2;
}
}
CliSession? session;
try {
session = await open(
args.dataDir ?? defaultDataDir(env),
seedCredentials: p.join(
env['HOME'] ?? '',
'.config',
'todo',
'firebase_auth.json',
),
);
final cli = CliCommands(session, out, err);
return switch (args.mode) {
CliMode.add => await cli.add(args, text!),
CliMode.list || CliMode.search => await cli.list(args),
CliMode.get => await cli.get(args.id!),
CliMode.setStatus => await cli.setStatus(args.id!, args.status!),
CliMode.setText => await cli.setText(args.id!, text!),
CliMode.close => await cli.close(args.id!, args.opts.evidence!),
CliMode.backfill => await cli.backfillCreatedBy(
claudeNodeIds(env),
dryRun: args.dryRun,
),
// Only delete is left: help returned above.
_ => await cli.delete(args.id!),
};
} on NoteLookupError catch (error) {
err.writeln('error: $error');
return 1;
} on RemoteSyncError catch (error) {
err.writeln('error: $error');
return 1;
} on IOException catch (error) {
err.writeln('error: $error');
return 1;
} finally {
await session?.close();
}
}

235
lib/cli/cli_session.dart Normal file
View File

@ -0,0 +1,235 @@
/// One headless CLI run: a local note log, its node id, and a Firebase client.
///
/// Built only from Flutter-free pieces of the app (the [NoteRepository], the
/// [SyncService] every device runs, and [kProject]) so `dart run` works with
/// no Flutter engine — the same constraint `tool/sync_smoke.dart` lives under.
/// The writes are therefore ordinary CRDT changes from one more device, never
/// records hand-written into RTDB.
library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync/crdt_sync_io.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:todo/cli/file_credential_store.dart';
import 'package:todo/cli/pull_only_store.dart';
import 'package:todo/cli/timeout_client.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/firebase_project.dart';
import 'package:todo/sync/sync_service.dart';
import 'package:uuid/uuid.dart';
export 'package:todo/cli/cli_paths.dart';
/// The open state of one CLI invocation. Call [close] when done.
class CliSession {
/// Wraps already-open parts; [open] is the normal way in. Public so a test
/// can subclass the session and script [sync]'s outcome.
CliSession(
this.dataDir,
this.repository,
this._firebase, {
this.passphraseFile,
this.sharedPasswordFile,
});
/// The fleet-wide crdt-sync password the Python daemons read too
/// (`~/.config/crdt-sync/password`), found from the seed's config root.
final File? sharedPasswordFile;
/// Where the passphrase is read from besides the environment: next to the
/// seeded Firebase session, e.g. `~/.config/todo/e2e_passphrase`.
final File? passphraseFile;
/// File holding this install's persisted CRDT node id.
static const nodeIdFileName = 'node_id';
/// File holding the per-peer revision cache (see [SyncService.stateStore]).
static const syncStateFileName = 'sync_state.json';
/// The CLI's private copy of the Firebase session.
static const credentialsFileName = 'firebase_auth.json';
/// Where the local log, node id and session copy live.
final String dataDir;
/// The note store, exactly the class the app uses.
final NoteRepository repository;
final FirebaseRestClient _firebase;
/// Opens (creating on first use) the session rooted at [dataDir].
///
/// [seedCredentials] is todo's desktop session, read once and never written.
/// [httpClient] replaces the real network client (tests only). Either way
/// every request is bounded by [requestTimeout] (see [TimeoutClient]).
static Future<CliSession> open(
String dataDir, {
required String seedCredentials,
String seedApp = 'todo',
http.Client? httpClient,
Duration requestTimeout = const Duration(seconds: 30),
}) async {
final network = TimeoutClient(
httpClient ?? http.Client(),
timeout: requestTimeout,
);
final dir = Directory(dataDir);
await dir.create(recursive: true);
// Holds a database-write credential: owner-only, like ~/.config/todo.
await Process.run('chmod', ['700', dir.path]);
final repository = await NoteRepository.openWith(
persistence: FileLogPersistence(
File(p.join(dataDir, NoteRepository.logFileName)),
),
nodeId: await _nodeId(dataDir),
);
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
httpClient: network,
store: FileCredentialStore(
file: File(p.join(dataDir, credentialsFileName)),
seedFile: File(seedCredentials),
),
);
if (!await auth.hasSession()) {
await repository.close();
throw FirebaseAuthError(
'no Firebase session: $seedCredentials is missing; re-seed it with '
'`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app $seedApp`',
);
}
final firebase = FirebaseRestClient(
databaseUrl: kProject.databaseUrl,
auth: auth,
httpClient: network,
);
return CliSession(
dataDir,
repository,
firebase,
passphraseFile: File(
p.join(p.dirname(seedCredentials), e2ePassphraseFileName),
),
sharedPasswordFile: File(
p.join(p.dirname(p.dirname(seedCredentials)), 'crdt-sync', 'password'),
),
);
}
/// Pull every peer's log and merge it; with [push], also publish this
/// node's merged log and its revision, exactly as a device's sync tick does.
///
/// Without [push] nothing is written anywhere remote, and the revision cache
/// is bypassed so a read always sees every peer's current log.
Future<SyncResult> sync({required bool push}) async {
final plainService = SyncService(
stateStore: push
? PersistedSyncStateStore(
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
)
: null,
);
final e2e = await openEncryptedStore(
store: _remote(push: push),
oldPrefix: plainService.notesDir,
readPassphrase: _readPassphrase,
// Argon2id once per install, not on every CLI/MCP call.
keyCache: E2eKeyCache(read: _readCachedKey, write: _writeCachedKey),
);
if (!push) {
// Read-only during the migration: old builds still write the plaintext
// prefix, so merge it, then the encrypted one when this host has a key.
final plain = await const SyncService().sync(
repository,
_remote(push: false),
);
if (e2e is! E2eReady) return plain;
final layout = E2eLayout.of(plainService.notesDir);
return await SyncService(
notesDir: layout.prefix,
revsPath: layout.revsPath,
).sync(repository, e2e.store);
}
if (e2e is! E2eReady) {
throw StateError(
'sync is locked: put the crdt-sync passphrase in '
'$e2ePassphraseEnv or ${passphraseFile?.path ?? e2ePassphraseFileName}',
);
}
final layout = E2eLayout.of(plainService.notesDir);
return await SyncService(
notesDir: layout.prefix,
revsPath: layout.revsPath,
stateStore: plainService.stateStore,
).sync(repository, e2e.store);
}
RemoteStore _remote({required bool push}) =>
push ? _firebase : PullOnlyStore(_firebase);
/// Owner-only file in the data dir caching the derived E2E key.
static const e2eKeyFileName = 'e2e_key';
File get _keyFile => File(p.join(dataDir, e2eKeyFileName));
Future<List<int>?> _readCachedKey() async {
final file = _keyFile;
if (!file.existsSync()) return null;
try {
return base64.decode((await file.readAsString()).trim());
} on FormatException {
return null;
}
}
Future<void> _writeCachedKey(List<int> bytes) async {
final file = _keyFile;
// Restrict before the key is written, never after.
await file.writeAsString('');
await Process.run('chmod', ['600', file.path]);
await file.writeAsString(base64.encode(bytes), flush: true);
}
/// Environment variable holding the shared crdt-sync passphrase.
static const e2ePassphraseEnv = 'TODO_E2E_PASSPHRASE';
/// File name of the passphrase, beside the seeded Firebase session.
static const e2ePassphraseFileName = 'e2e_passphrase';
Future<String?> _readPassphrase() async {
final fromEnv = Platform.environment[e2ePassphraseEnv];
if (fromEnv != null && fromEnv.isNotEmpty) return fromEnv;
for (final file in [passphraseFile, sharedPasswordFile]) {
if (file != null && file.existsSync()) {
final text = (await file.readAsString()).trim();
if (text.isNotEmpty) return text;
}
}
return null;
}
/// Releases the log and the HTTP client.
Future<void> close() async {
_firebase.close();
await repository.close();
}
/// Reads this install's node id, minting and persisting a uuid on first run.
///
/// Never a fixed name: two installs sharing an id would overwrite each
/// other's file under `todo-sync/notes/` and lose writes.
static Future<String> _nodeId(String dataDir) async {
final file = File(p.join(dataDir, nodeIdFileName));
if (file.existsSync()) {
final stored = (await file.readAsString()).trim();
if (stored.isNotEmpty) return stored;
}
final minted = const Uuid().v4();
await file.writeAsString('$minted\n');
return minted;
}
}

39
lib/cli/cli_usage.dart Normal file
View File

@ -0,0 +1,39 @@
/// Usage text printed by `--help` and after a usage error.
const kUsage = r'''
Usage: dart run bin/todo_note.dart [options]
Adds a note to the todo app headlessly: pulls from Firebase RTDB, writes an
ordinary CRDT change as this install's own node, pushes, and prints the id.
A note with --repo is a repo task; one without is a plain idea.
--text <markdown> note text (first line = title); default: read stdin
--priority <p> low|medium|high (default medium)
--status <s> todo|in_progress|done|abandoned (default todo);
with --list/--search: show only that status
--repo <owner/name> repo task's repository, e.g. kuhyx/todo;
with --list/--search: show only that repo's tasks
--done-check <cmd> shell command, run from the repo root, exit 0 = done
--new-note with --repo: own note, not the shared one (an exact
title in another separate note merges into it)
--by <who> claude|kuhy
--list pull, then print live notes, one per line:
8-char id, status, priority, repo (- for none), title
--search <q> as --list, only notes whose text or repo contains q
--get <id> pull, then print one note in full (exit 1 if absent)
--delete <id> pull, tombstone the note, push
--set-status <id> <s> pull, change the note's status (as --status), push
--set-text <id> pull, replace the note's whole text with --text (or
stdin; first line = title), keep its other fields, push
--close <id> --evidence <s>
pull, set status done + evidence (commit sha + done
check exit code), push; refused without --evidence
--backfill-created-by [--dry-run]
pull, set created_by (claude|kuhy) on every note that
has none, push; --dry-run prints the plan only
--data-dir <dir> local log + node id (default
$XDG_DATA_HOME/todo-cli or ~/.local/share/todo-cli)
-h, --help this text
<id> is a full id or a unique prefix of at least 8 characters.
--list, --search and --get never push.
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.''';

View File

@ -0,0 +1,52 @@
/// The headless CLI's Firebase session, kept in a file of its own.
library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
/// A file-backed [FirebaseCredentialStore], seeded once from [seedFile].
///
/// [seedFile] is todo's desktop session (`~/.config/todo/firebase_auth.json`,
/// written by `crdt-sync/tool/seed_session.py --app todo`) and is only ever
/// read. Every write goes to [file], a private copy in the CLI's data dir.
/// That split matters: [FirebaseTokenProvider] clears its store when a refresh
/// token is revoked, and a shared file would let one bad CLI run delete the
/// seed the desktop wrapper provisions itself from.
class FileCredentialStore implements FirebaseCredentialStore {
/// Creates a store that persists to [file], falling back to [seedFile].
FileCredentialStore({required this.file, required this.seedFile});
/// The CLI's own copy, written on every token refresh.
final File file;
/// The read-only seed used until [file] exists.
final File seedFile;
@override
Future<FirebaseCredentials?> load() async {
final source = file.existsSync() ? file : seedFile;
if (!source.existsSync()) return null;
final decoded = jsonDecode(await source.readAsString());
if (decoded is! Map<String, dynamic>) return null;
return FirebaseCredentials.fromJson(decoded);
}
@override
Future<void> save(FirebaseCredentials credentials) async {
await file.parent.create(recursive: true);
final tmp = File('${file.path}.$pid.tmp');
// Owner-only before the token is written, not after: dart:io has no
// chmod, and a umask-default file would briefly expose a DB credential.
await tmp.writeAsString('');
await Process.run('chmod', ['600', tmp.path]);
await tmp.writeAsString(jsonEncode(credentials.toJson()));
await tmp.rename(file.path);
}
@override
Future<void> clear() async {
if (file.existsSync()) await file.delete();
}
}

View File

@ -0,0 +1,78 @@
/// `bin/merge_repo_notes.dart`: collapse each repo's open notes into one.
/// Dry run unless `--apply`; stdout is the `old_id<TAB>kept_id<TAB>repo` map.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:path/path.dart' as p;
import 'package:todo/cli/cli_runner.dart';
import 'package:todo/cli/cli_session.dart';
import 'package:todo/data/repo_note_merge.dart';
const _usage = 'usage: merge_repo_notes [--dry-run|--apply] [--data-dir D]';
/// Runs the merge for [argv]; returns the exit code.
Future<int> runMergeRepoNotes(
List<String> argv, {
required Map<String, String> env,
required StringSink out,
required StringSink err,
SessionOpener open = CliSession.open,
}) async {
var apply = false;
String? dataDir;
for (var i = 0; i < argv.length; i++) {
switch (argv[i]) {
case '--apply':
apply = true;
case '--dry-run':
apply = false;
case '--data-dir' when i + 1 < argv.length:
dataDir = argv[++i];
default:
err.writeln(_usage);
return 2;
}
}
CliSession? session;
try {
session = await open(
dataDir ?? defaultDataDir(env),
seedCredentials: p.join(
env['HOME'] ?? '',
'.config',
'todo',
'firebase_auth.json',
),
);
await session.sync(push: apply);
final plan = planRepoMerges(await session.repository.listNotes());
for (final (:kept, :removed) in plan) {
if (apply) {
await session.repository.upsert(
kept.copyWith(updatedAt: DateTime.now()),
);
for (final n in removed) {
await session.repository.delete(n.id);
}
}
for (final n in removed) {
out.writeln('${n.id}\t${kept.id}\t${kept.repo}');
}
}
final deleted = plan.fold(0, (sum, m) => sum + m.removed.length);
err.writeln(
'${apply ? 'applied' : 'dry run'}: ${plan.length} repos, '
'$deleted notes deleted',
);
if (apply && plan.isNotEmpty && !(await session.sync(push: true)).pushed) {
err.writeln('error: saved locally but nothing was pushed');
return 1;
}
return 0;
} on RemoteSyncError catch (error) {
err.writeln('error: $error');
return 1;
} finally {
await session?.close();
}
}

64
lib/cli/note_lookup.dart Normal file
View File

@ -0,0 +1,64 @@
import 'package:todo/cli/cli_args.dart';
import 'package:todo/data/note.dart';
const _minPrefix = 8;
/// No note, or more than one, matches an id argument; [message] says which.
class NoteLookupError extends FormatException {
NoteLookupError._(super.message);
@override
String toString() => message;
}
/// The note with id [ref], else the only one whose id starts with [ref].
Note findNote(Iterable<Note> notes, String ref) {
final exact = notes.where((n) => n.id == ref).firstOrNull;
if (exact != null) return exact;
if (ref.length < _minPrefix) {
throw NoteLookupError._(
'no live note with id $ref (an id prefix needs at least '
'$_minPrefix characters)',
);
}
final matches = notes.where((n) => n.id.startsWith(ref)).toList();
if (matches.isEmpty) throw NoteLookupError._('no live note with id $ref');
if (matches.length > 1) {
throw NoteLookupError._(
'id prefix $ref matches ${matches.length} notes; give more of the id:\n'
'${matches.map((n) => ' ${n.id} ${_title(n)}').join('\n')}',
);
}
return matches.single;
}
/// `<8-char id>\t<status>\t<priority>\t<repo or ->\t<title>\t<created_by>`.
String listLine(Note note) => [
if (note.id.length <= _minPrefix)
note.id
else
note.id.substring(0, _minPrefix),
CliArgs.statusName(note.status),
note.priority.name,
note.repo ?? '-',
_title(note),
note.createdBy ?? 'kuhy',
].join('\t');
String _title(Note note) => note.text.split('\n').first;
/// The note's metadata lines, `---`, then its text.
String noteDetail(Note note) => [
'id: ${note.id}',
'priority: ${note.priority.name}',
'status: ${CliArgs.statusName(note.status)}',
'created: ${note.createdAt.toIso8601String()}',
'updated: ${note.updatedAt.toIso8601String()}',
if (note.repo case final v?) 'repo: $v',
if (note.doneCheck case final v?) 'done_check: $v',
if (note.by case final v?) 'by: $v',
if (note.evidence case final v?) 'evidence: $v',
'created_by: ${note.createdBy ?? 'kuhy'}',
'---',
note.text,
].join('\n');

View File

@ -0,0 +1,44 @@
/// A read-only view of a [RemoteStore], for the CLI's verification modes.
library;
import 'package:crdt_sync/crdt_sync.dart';
/// Delegates every read to [inner] and silently drops every write.
///
/// Lets `--list` / `--get` run the app's own [SyncService] merge path without
/// publishing anything. Without it, each throwaway data dir (a fresh node id)
/// would leave a permanent full-log peer file in RTDB that every device then
/// downloads on every sync.
class PullOnlyStore implements RemoteStore, BulkMapReader {
/// Wraps [inner], which must also be able to read revision maps.
PullOnlyStore(this.inner);
/// The real backend reads go to.
final FirebaseRestClient inner;
@override
Future<List<String>> listDirectory(String path) => inner.listDirectory(path);
@override
Future<String?> getFileText(String path) => inner.getFileText(path);
@override
Future<Map<String, String>> getStringMap(String path) =>
inner.getStringMap(path);
@override
Future<void> putFileText(
String path,
String text, {
required String message,
}) async {}
@override
Future<void> deleteFile(String path, {String message = ''}) async {}
@override
Future<bool> canAccessRemote() => inner.canAccessRemote();
@override
void close() => inner.close();
}

View File

@ -0,0 +1,58 @@
import 'dart:async';
import 'package:http/http.dart' as http;
/// An HTTP client whose every request is bounded.
///
/// `package:http` has no timeout of its own, and neither do the Firebase and
/// token clients built on it: one dead connection (after boot, a network
/// blip) made a sync wait forever and wedged the MCP server's serial queue.
/// [timeout] bounds the wait for the response headers and then each gap
/// between body chunks, so a large body that keeps moving is never cut off.
class TimeoutClient extends http.BaseClient {
/// Wraps [_inner]; each wait fails with a [TimeoutException] after [timeout].
TimeoutClient(this._inner, {this.timeout = const Duration(seconds: 30)});
final http.Client _inner;
/// Longest wait for the headers, and for the next body chunk.
final Duration timeout;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final response = await _inner
.send(request)
.timeout(
timeout,
onTimeout: () => throw TimeoutException(
'${request.method} ${request.url.host} got no response',
timeout,
),
);
return http.StreamedResponse(
response.stream.timeout(
timeout,
onTimeout: (sink) {
sink
..addError(
TimeoutException(
'${request.method} ${request.url.host} body stalled',
timeout,
),
)
..close();
},
),
response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
);
}
@override
void close() => _inner.close();
}

161
lib/data/app_settings.dart Normal file
View File

@ -0,0 +1,161 @@
/// App-wide, non-sync preferences (currently just `advancedMode`).
///
/// Mirrors [SyncSettings]'s shape: `SharedPreferences` is the source of
/// truth for instant, offline reads; a Firebase mirror lets the same choice
/// follow the user to their other devices without blocking the UI on a
/// network round trip.
///
/// Unlike [SyncSettings], the remote calls here take an already-open
/// [FirebaseRestClient] rather than opening their own: `runSync()` in
/// `run_sync.dart` is the one place that owns a Firebase session per sync
/// pass, and reconciling this flag rides along on that same client instead
/// of paying for a second sign-in/token-refresh round trip.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Where the mirrored value lives in the shared `kuhy-syncs` RTDB project,
/// sibling to `changesets/<nodeId>.json`.
const String kAdvancedModeRemotePath = 'settings/advancedMode';
/// App-wide, non-sync preferences (`advancedMode`, `showClaudeNotes`).
class AppSettings {
/// Creates an [AppSettings] from its stored fields.
const AppSettings({
required this.advancedMode,
this.advancedModeUpdatedAt,
this.showClaudeNotes = false,
});
/// Whether the priority/status/template/mode chrome and the routine
/// save/sync status text are shown. Off by default: casual capture needs
/// none of it. A sync *failure* is always surfaced regardless of this
/// flag — that is the one state the user might need to act on.
final bool advancedMode;
/// When [advancedMode] was last changed, used to reconcile a value written
/// on another device with the local one (most recent write wins). Null for
/// a value that has never round-tripped through Firebase.
final DateTime? advancedModeUpdatedAt;
/// Whether the notes list shows notes Claude filed. Per device: it lives
/// only in this device's preferences and is never mirrored to Firebase.
final bool showClaudeNotes;
static const _kShowClaude = 'app.showClaudeNotes';
static const _kAdvancedMode = 'app.advancedMode';
static const _kAdvancedModeUpdatedAt = 'app.advancedMode.updatedAt';
/// Loads settings, defaulting `advancedMode` to false.
static Future<AppSettings> load() async {
final prefs = await SharedPreferences.getInstance();
final updatedAtMillis = prefs.getInt(_kAdvancedModeUpdatedAt);
return AppSettings(
advancedMode: prefs.getBool(_kAdvancedMode) ?? false,
showClaudeNotes: prefs.getBool(_kShowClaude) ?? false,
advancedModeUpdatedAt: updatedAtMillis == null
? null
: DateTime.fromMillisecondsSinceEpoch(updatedAtMillis),
);
}
/// Persists [value] locally (stamping [advancedModeUpdatedAt] to now so a
/// later reconciliation can tell which write is newer) and, when [client]
/// is a live Firebase session, best-effort mirrors it remotely. A push
/// failure — network (`FirebaseSyncError`) or an expired/wrong-account
/// session (`FirebaseAuthError`), both `RemoteSyncError` — is swallowed:
/// the local write already succeeded, and the next successful sync will
/// retry via [reconcileWithRemote].
Future<AppSettings> withAdvancedMode({
required bool value,
FirebaseRestClient? client,
}) async {
final updatedAt = DateTime.now();
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kAdvancedMode, value);
await prefs.setInt(
_kAdvancedModeUpdatedAt,
updatedAt.millisecondsSinceEpoch,
);
final updated = AppSettings(
advancedMode: value,
advancedModeUpdatedAt: updatedAt,
showClaudeNotes: showClaudeNotes,
);
if (client != null) {
try {
// getStringMap() only keeps entries whose JSON value is a string,
// so both fields are written as strings rather than a bool/int.
await client.patchValues(kAdvancedModeRemotePath, {
'value': value.toString(),
'updatedAtMillis': updatedAt.millisecondsSinceEpoch.toString(),
});
} on RemoteSyncError {
// Offline, a transient failure, or an expired/wrong-account session:
// the local write stands, and the next runSync() reconciliation will
// push it again.
}
}
return updated;
}
/// Persists the per-device Claude-notes choice; nothing leaves the device.
Future<AppSettings> withShowClaudeNotes({required bool value}) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kShowClaude, value);
return AppSettings(
advancedMode: advancedMode,
advancedModeUpdatedAt: advancedModeUpdatedAt,
showClaudeNotes: value,
);
}
/// Pulls the remote value from [client] and, if it is newer than the
/// local one, applies it locally and returns the reconciled settings.
/// Returns this instance unchanged when [client] is null, there is
/// nothing remote, the remote value is not newer, or the fetch fails with
/// a [RemoteSyncError] — network, or an expired/wrong-account session
/// (offline sync is a normal state, not an error).
Future<AppSettings> reconcileWithRemote(FirebaseRestClient? client) async {
if (client == null) return this;
try {
final remote = await client.getStringMap(kAdvancedModeRemotePath);
if (!remote.containsKey('value')) return this;
final remoteUpdatedMillis = int.tryParse(remote['updatedAtMillis'] ?? '');
if (remoteUpdatedMillis == null) return this;
final remoteUpdatedAt = DateTime.fromMillisecondsSinceEpoch(
remoteUpdatedMillis,
);
final candidate = AppSettings(
advancedMode: remote['value'] == 'true',
advancedModeUpdatedAt: remoteUpdatedAt,
showClaudeNotes: showClaudeNotes,
);
final adopted = adopt(candidate);
if (identical(adopted, this)) return this;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kAdvancedMode, adopted.advancedMode);
await prefs.setInt(_kAdvancedModeUpdatedAt, remoteUpdatedMillis);
return adopted;
} on RemoteSyncError {
return this;
}
}
/// Returns [candidate] if it carries a strictly newer
/// [advancedModeUpdatedAt] than this instance, otherwise returns this
/// instance unchanged. Shared by every call site that reconciles a
/// remote-or-otherwise-external value against the current in-memory
/// settings (`reconcileWithRemote` above, and the capture/settings
/// screens after a sync completes), so the "newer write wins" rule is
/// defined once instead of copied at each call site.
AppSettings adopt(AppSettings? candidate) {
if (candidate == null) return this;
final candidateAt = candidate.advancedModeUpdatedAt;
if (candidateAt == null) return this;
final currentAt = advancedModeUpdatedAt;
if (currentAt != null && !candidateAt.isAfter(currentAt)) return this;
return candidate;
}
}

View File

@ -0,0 +1,44 @@
/// Who filed a note, for notes written before `created_by` existed.
///
/// The `created_at` field's clock names the node that last wrote it. The MCP
/// and the CLI are the only nodes Claude writes through, so a note created
/// there carries one of their node ids; anything else came from kuhy's own
/// devices.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:todo/data/note_record.dart';
const _createdAt = 'created_at';
/// `claude` when [record]'s `created_at` was written by one of [claudeNodes],
/// else `kuhy`.
String classifyCreatedBy(Record record, Set<String> claudeNodes) {
final node = record.fields[_createdAt]?.$2.nodeId;
return node != null && claudeNodes.contains(node) ? 'claude' : 'kuhy';
}
/// Live records of [log] with no `created_by` yet, mapped to their value.
Map<String, String> planCreatedByBackfill(Log log, Set<String> claudeNodes) => {
for (final record in log.values)
if (!record.deleted &&
((record.fields[kCreatedByField]?.$1 as String?) ?? '').isEmpty)
record.id: classifyCreatedBy(record, claudeNodes),
};
/// [incoming], carrying [existing]'s `created_by` when [incoming] has none.
///
/// A store replaces a record wholesale, so an edit that does not know the
/// field (an import of an old backup) would otherwise drop it locally.
Record keepCreatedBy(Record incoming, Record? existing) {
final kept = existing?.fields[kCreatedByField];
if (kept == null || incoming.fields.containsKey(kCreatedByField)) {
return incoming;
}
return Record(
id: incoming.id,
fields: {...incoming.fields, kCreatedByField: kept},
deleted: incoming.deleted,
deletedHlc: incoming.deletedHlc,
);
}

View File

@ -5,7 +5,7 @@ import 'package:http/http.dart' as http;
/// The wrapper exists because a browser cannot write to the filesystem, and two /// The wrapper exists because a browser cannot write to the filesystem, and two
/// things depend on it: /// things depend on it:
/// ///
/// * `~/todo/BACKLOG.md` — read by the user's tooling and the `todo` MCP /// * `~/src/todo/BACKLOG.md` — read by the user's tooling and the `todo` MCP
/// server. Without this it would silently go stale after the move to a web /// server. Without this it would silently go stale after the move to a web
/// build. /// build.
/// * an on-disk copy of the note log, so a wiped Chrome profile is not a /// * an on-disk copy of the note log, so a wiped Chrome profile is not a

View File

@ -73,11 +73,7 @@ class LegacySqliteMigration {
} }
// coverage:ignore-end // coverage:ignore-end
static Future<void> _onUpgrade( static Future<void> _onUpgrade(CrdtTableExecutor db, int from, int to) async {
CrdtTableExecutor db,
int from,
int to,
) async {
if (from < 2) { if (from < 2) {
await db.execute( await db.execute(
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0', 'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',

38
lib/data/log_watch.dart Normal file
View File

@ -0,0 +1,38 @@
/// A seeded, coalesced stream over the note log's change events.
library;
import 'dart:async';
/// A stream that emits `compute()` when first listened to (the seed), then
/// again after [changes] fires. Seeding in `onListen` -- rather than lazily in
/// an `async*` body -- avoids a race where a write between `listen` and the
/// first generator tick would swallow the initial snapshot.
///
/// Re-emits are coalesced: the first change of a burst arms one
/// zero-duration timer and every further change before it fires is absorbed,
/// so N back-to-back changes cost ONE `compute()` carrying the latest state
/// instead of N full re-queries (each of which repaints the whole list).
/// The timer fires on the next event-loop turn, so tests stay deterministic
/// under `pumpEventQueue` and the widget tester's `pump`.
Stream<T> watchLog<T>(Stream<void> changes, T Function() compute) {
StreamSubscription<void>? sub;
Timer? pending;
late final StreamController<T> controller;
controller = StreamController<T>(
onListen: () {
controller.add(compute());
sub = changes.listen((_) {
pending ??= Timer(Duration.zero, () {
pending = null;
controller.add(compute());
});
});
},
onCancel: () {
pending?.cancel();
pending = null;
return sub?.cancel();
},
);
return controller.stream;
}

View File

@ -1,9 +1,8 @@
/// Domain model for a single idea/note. /// Domain model for a single idea/note.
/// ///
/// Notes are stored locally in a CRDT-backed SQLite table (see /// Notes are stored as crdt_sync records (see [NoteRepository] and
/// [NoteRepository]). The CRDT layer manages its own metadata columns /// `note_record.dart`); the clocks and tombstones live there, the fields
/// (`hlc`, `node_id`, `modified`, `is_deleted`); the fields here are the /// here are the user-facing data only.
/// user-facing data only.
library; library;
/// Priority tier for a note, used for sorting and visual grouping. /// Priority tier for a note, used for sorting and visual grouping.
@ -77,7 +76,16 @@ enum Status {
} }
} }
/// The values the optional `by` and `created_by` fields may hold.
const Set<String> kNoteAuthors = {'claude', 'kuhy'};
/// An immutable idea/note record. /// An immutable idea/note record.
///
/// A note with a [repo] is a *repo task* (an outstanding piece of work in
/// that repository, closable with [evidence]); one without is a plain idea.
/// The four task fields are optional and set-once in practice: they are
/// written only when a user or the CLI sets them, never by ordinary edits of
/// an idea, which keeps such edits wire-identical to the v3 build.
class Note { class Note {
/// Creates a [Note] from its stored fields. /// Creates a [Note] from its stored fields.
const Note({ const Note({
@ -87,6 +95,11 @@ class Note {
required this.status, required this.status,
required this.createdAt, required this.createdAt,
required this.updatedAt, required this.updatedAt,
this.repo,
this.doneCheck,
this.by,
this.evidence,
this.createdBy,
}); });
/// Builds a [Note] from a raw CRDT query row. /// Builds a [Note] from a raw CRDT query row.
@ -122,12 +135,41 @@ class Note {
/// When the note's content was last modified locally. /// When the note's content was last modified locally.
final DateTime updatedAt; final DateTime updatedAt;
/// Repository a task belongs to (`kuhyx/<name>`); null for a plain idea.
final String? repo;
/// Shell command, run from the repo root, whose exit 0 proves the task done.
final String? doneCheck;
/// Who does the task: one of [kNoteAuthors].
final String? by;
/// Proof the task was closed (commit sha + the done check's exit code).
final String? evidence;
/// Who filed the note: one of [kNoteAuthors]; null (older notes) means kuhy.
final String? createdBy;
/// Whether Claude filed this note (hidden by default, sorted last).
bool get isClaudeMade => createdBy == 'claude';
/// Whether this note is a repo task rather than a plain idea.
bool get isRepoTask => repo != null;
/// The repo without its owner ("kartka" for "kuhyx/kartka"), or null.
String? get repoName => repo?.split('/').last;
/// Returns a copy with selected fields replaced. /// Returns a copy with selected fields replaced.
Note copyWith({ Note copyWith({
String? text, String? text,
Priority? priority, Priority? priority,
Status? status, Status? status,
DateTime? updatedAt, DateTime? updatedAt,
String? repo,
String? doneCheck,
String? by,
String? evidence,
String? createdBy,
}) { }) {
return Note( return Note(
id: id, id: id,
@ -136,6 +178,11 @@ class Note {
status: status ?? this.status, status: status ?? this.status,
createdAt: createdAt, createdAt: createdAt,
updatedAt: updatedAt ?? this.updatedAt, updatedAt: updatedAt ?? this.updatedAt,
repo: repo ?? this.repo,
doneCheck: doneCheck ?? this.doneCheck,
by: by ?? this.by,
evidence: evidence ?? this.evidence,
createdBy: createdBy ?? this.createdBy,
); );
} }
} }

63
lib/data/note_bulk.dart Normal file
View File

@ -0,0 +1,63 @@
/// Partial logs for the multi-note writes: merged in one store write.
///
/// Each write re-serialises the whole log (over a megabyte on a real
/// device), so a bulk action must be one partial log merged once, never one
/// upsert per note. Merging is per field, so a field left out keeps its value
/// and its clock (`created_by` included).
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:todo/data/note.dart';
import 'package:todo/data/note_record.dart';
/// Partial records setting [priority] and/or [status] on the live notes of
/// [log] among [ids], all at [hlc].
///
/// Only fields whose value changes are written, plus `updated_at` = [now]
/// (so "last updated" sorting and newer-wins import see the edit). A note
/// with nothing to change, an unknown id and a deleted note are left out.
Log planBulkUpdate(
Log log,
Set<String> ids, {
required Hlc hlc,
required DateTime now,
Priority? priority,
Status? status,
}) {
final plan = <String, Record>{};
for (final id in ids) {
final current = log[id];
if (current == null || current.deleted) continue;
final note = noteFromRecord(current);
final next = note.copyWith(priority: priority, status: status);
if (next.priority == note.priority && next.status == note.status) continue;
// Generated against generated, never against the stored text: a peer's
// `...00Z` (or a web build's millisecond date) would otherwise read as
// a change and get a fresh clock, erasing the `created_at` node signal.
final before = noteFields(note, hlc);
plan[id] = Record(
id: id,
fields: {
for (final MapEntry(:key, :value) in noteFields(
next.copyWith(updatedAt: now),
hlc,
).entries)
if (before[key]?.$1 != value.$1) key: value,
},
);
}
return plan;
}
/// [note] at [hlc] plus a tombstone for each live note of [log] in
/// [removed] (other than [note] itself).
///
/// A merge, not a replace: a field [note] leaves unset keeps its stored
/// value, so this suits notes that only gain content (the repo note an
/// assign appends to), not edits that clear a field.
Log planReplace(Log log, Note note, Iterable<String> removed, Hlc hlc) => {
for (final id in removed)
if (log[id] case final r? when !r.deleted && id != note.id)
id: Record(id: id, fields: const {}, deleted: true, deletedHlc: hlc),
note.id: Record(id: note.id, fields: noteFields(note, hlc)),
};

38
lib/data/note_import.dart Normal file
View File

@ -0,0 +1,38 @@
/// Two small companions of [NoteRepository]: the result of an import, and
/// the in-memory store its test constructor uses.
///
/// Split out of `note_repository.dart` for file size; that file re-exports
/// this one.
library;
import 'package:crdt_sync/crdt_sync.dart';
/// Summary of an [NoteRepository.importNotes] run, for user feedback.
class ImportOutcome {
/// Creates an [ImportOutcome] from its per-category counts.
const ImportOutcome({
required this.added,
required this.updated,
required this.skipped,
});
/// Notes that did not exist locally and were created.
final int added;
/// Existing notes overwritten because the import was newer.
final int updated;
/// Notes skipped because the local copy was the same age or newer.
final int skipped;
}
/// In-memory [LogPersistence] for [NoteRepository.openInMemory] (tests).
class MemoryPersistence implements LogPersistence {
String? _text;
@override
Future<String?> read() async => _text;
@override
Future<void> write(String text) async => _text = text;
}

205
lib/data/note_query.dart Normal file
View File

@ -0,0 +1,205 @@
/// How notes are selected and ordered: the sort modes, the filter, and the
/// pure predicates behind them.
///
/// Split out of `note_repository.dart` for file size; that file re-exports
/// this one, so callers import it as before. Everything here is pure -- it
/// takes notes and a filter and returns a decision -- which is what made it
/// the natural seam.
library;
import 'package:todo/data/note.dart';
/// How the history list should be ordered.
enum NoteSort {
/// Newest created first.
createdDesc,
/// Most recently modified first.
modifiedDesc,
/// A-Z by note text.
alphabetical,
/// Highest [Priority] first.
priorityDesc,
}
/// An immutable set of constraints for querying notes.
///
/// All fields combine with logical AND. Empty/null fields impose no
/// constraint. Lives in the data layer so the filtering it drives never leaks
/// into the UI. Construct copies with [copyWith] when toggling one facet.
class NoteFilter {
/// Creates a [NoteFilter] from its constraint fields.
const NoteFilter({
this.query = '',
this.priorities = const {},
this.statuses = const {},
this.repo,
this.repoTasksOnly = false,
this.hideClaude = false,
this.createdFrom,
this.createdTo,
this.updatedFrom,
this.updatedTo,
});
/// Case-insensitive substring matched against the note body.
final String query;
/// Notes must have one of these priorities. Empty means "any priority".
final Set<Priority> priorities;
/// Notes must have one of these statuses. Empty means "any status".
final Set<Status> statuses;
/// Only notes whose repo equals this. Null means any repo (or none).
final String? repo;
/// Only notes that have a repo (repo tasks). Ideas are excluded.
final bool repoTasksOnly;
/// Leave out notes Claude filed. A view preference rather than a user
/// facet, so it never counts toward [isEmpty] or [activeCount].
final bool hideClaude;
/// Inclusive lower bound (by calendar day) on the creation date.
final DateTime? createdFrom;
/// Inclusive upper bound (by calendar day) on the creation date.
final DateTime? createdTo;
/// Inclusive lower bound (by calendar day) on the last-updated date.
final DateTime? updatedFrom;
/// Inclusive upper bound (by calendar day) on the last-updated date.
final DateTime? updatedTo;
/// True when no constraint is active (the unfiltered, full list).
bool get isEmpty =>
query.trim().isEmpty &&
priorities.isEmpty &&
statuses.isEmpty &&
repo == null &&
!repoTasksOnly &&
createdFrom == null &&
createdTo == null &&
updatedFrom == null &&
updatedTo == null;
/// Number of distinct active facets, for an "N filters" badge in the UI.
int get activeCount {
var n = 0;
if (query.trim().isNotEmpty) n++;
if (priorities.isNotEmpty) n++;
if (statuses.isNotEmpty) n++;
if (repo != null) n++;
if (repoTasksOnly) n++;
if (createdFrom != null || createdTo != null) n++;
if (updatedFrom != null || updatedTo != null) n++;
return n;
}
/// Returns a copy with selected facets replaced. A `null` argument keeps
/// the current value; clearing a date is done via the dedicated clear
/// flags so `null` can mean "unchanged".
NoteFilter copyWith({
String? query,
Set<Priority>? priorities,
Set<Status>? statuses,
String? repo,
bool? repoTasksOnly,
bool? hideClaude,
DateTime? createdFrom,
DateTime? createdTo,
DateTime? updatedFrom,
DateTime? updatedTo,
bool clearCreated = false,
bool clearUpdated = false,
}) {
return NoteFilter(
query: query ?? this.query,
priorities: priorities ?? this.priorities,
statuses: statuses ?? this.statuses,
repo: repo ?? this.repo,
repoTasksOnly: repoTasksOnly ?? this.repoTasksOnly,
hideClaude: hideClaude ?? this.hideClaude,
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
updatedTo: clearUpdated ? null : (updatedTo ?? this.updatedTo),
);
}
}
/// Whether [note] passes every clause of [filter].
///
/// Clauses are AND-combined, and an empty clause matches everything -- an
/// empty priority set means "any priority", not "no priorities".
bool matchesFilter(Note note, NoteFilter filter) {
final query = filter.query.trim().toLowerCase();
if (query.isNotEmpty &&
!note.text.toLowerCase().contains(query) &&
!(note.repo?.toLowerCase().contains(query) ?? false)) {
return false;
}
if (filter.repo != null && note.repo != filter.repo) return false;
if (filter.repoTasksOnly && note.repo == null) return false;
if (filter.hideClaude && note.isClaudeMade) return false;
if (filter.priorities.isNotEmpty &&
!filter.priorities.contains(note.priority)) {
return false;
}
if (filter.statuses.isNotEmpty && !filter.statuses.contains(note.status)) {
return false;
}
if (!_withinDays(note.createdAt, filter.createdFrom, filter.createdTo)) {
return false;
}
if (!_withinDays(note.updatedAt, filter.updatedFrom, filter.updatedTo)) {
return false;
}
return true;
}
/// Inclusive day-granularity range check, matching the old SQL bounds:
/// `from` includes its whole day; `to` includes its whole day.
bool _withinDays(DateTime value, DateTime? from, DateTime? to) {
if (from != null && value.isBefore(_startOfDay(from))) return false;
if (to != null &&
!value.isBefore(_startOfDay(to).add(const Duration(days: 1)))) {
return false;
}
return true;
}
/// The comparator implementing [sort]: human-made notes first, Claude-made
/// ones after, and [sort] orders each group.
Comparator<Note> comparatorFor(NoteSort sort) {
final within = _within(sort);
return (a, b) {
if (a.isClaudeMade != b.isClaudeMade) return a.isClaudeMade ? 1 : -1;
return within(a, b);
};
}
Comparator<Note> _within(NoteSort sort) {
switch (sort) {
case NoteSort.createdDesc:
return (a, b) => b.createdAt.compareTo(a.createdAt);
case NoteSort.modifiedDesc:
return (a, b) => b.updatedAt.compareTo(a.updatedAt);
case NoteSort.alphabetical:
return (a, b) => a.text.toLowerCase().compareTo(b.text.toLowerCase());
case NoteSort.priorityDesc:
return (a, b) {
final byPriority = b.priority.value.compareTo(a.priority.value);
return byPriority != 0
? byPriority
: b.updatedAt.compareTo(a.updatedAt);
};
}
}
/// Midnight (local) of [t]'s calendar day.
DateTime _startOfDay(DateTime t) => DateTime(t.year, t.month, t.day);

60
lib/data/note_record.dart Normal file
View File

@ -0,0 +1,60 @@
/// Note <-> crdt_sync [Record] mapping; re-exported by `note_repository.dart`.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:todo/data/note.dart';
const _text = 'text';
const _priority = 'priority';
const _status = 'status';
const _createdAt = 'created_at';
const _updatedAt = 'updated_at';
const _repo = 'repo';
const _doneCheck = 'done_check';
const _by = 'by';
const _evidence = 'evidence';
/// Record field naming who filed the note (`kuhy` or `claude`).
const kCreatedByField = 'created_by';
/// Record fields for [note], all at [hlc]. Unset task fields are omitted, so
/// an idea's record is exactly the v3 field set (and cannot clear a peer's).
Map<String, Field> noteFields(Note note, Hlc hlc) => {
_text: (note.text, hlc),
_priority: (note.priority.value, hlc),
_status: (note.status.value, hlc),
_createdAt: (note.createdAt.toIso8601String(), hlc),
_updatedAt: (note.updatedAt.toIso8601String(), hlc),
if (note.repo case final v?) _repo: (v, hlc),
if (note.doneCheck case final v?) _doneCheck: (v, hlc),
if (note.by case final v?) _by: (v, hlc),
if (note.evidence case final v?) _evidence: (v, hlc),
if (note.createdBy case final v?) kCreatedByField: (v, hlc),
};
/// Reads [record] as a [Note], ignoring unknown fields.
Note noteFromRecord(Record record) {
final fields = record.fields;
String? str(String name) => fields[name]?.$1 as String?;
// '' is how a peer clears a task field: omitting it never clears.
String? task(String name) => switch (str(name)) {
'' => null,
final v => v,
};
return Note(
id: record.id,
text: str(_text) ?? '',
priority: Priority.fromValue(fields[_priority]?.$1 as int?),
status: Status.fromValue(fields[_status]?.$1 as int?),
createdAt: _parseDate(str(_createdAt)),
updatedAt: _parseDate(str(_updatedAt)),
repo: task(_repo),
doneCheck: task(_doneCheck),
by: task(_by),
evidence: task(_evidence),
createdBy: task(kCreatedByField),
);
}
DateTime _parseDate(String? iso) =>
iso == null ? DateTime.fromMillisecondsSinceEpoch(0) : DateTime.parse(iso);

Some files were not shown because too many files have changed in this diff Show More