diff --git a/CLAUDE.md b/CLAUDE.md index 37c424e..3a34521 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,7 +25,7 @@ open Package.swift # opens the package in Xcode for GUI editing / previ the unsigned app opens without Gatekeeper's block. It verifies `Tic.zip.sha256` and quits only the app process (the `pgrep -f` pattern is anchored, so `Tic --mcp` helpers and their wrappers survive). Test it with `TIC_DEST=` and a stub `open` first on `PATH`. -- **Verification** is a clean `swift build`, `swift test` (Swift Testing — `AppDatabaseTests`, +- **Verification** is a clean `swift build`, `swift test` (Swift Testing — `AppDatabaseTests`, `SyncTests`, `TaskOutlineTests`, `NoteColorTests`, `TaskImageTests`, …), plus running the app. The outline logic lives in pure, testable functions (`TaskOutline`) precisely so it can be covered without a DB or the main actor. - `swift run` produces a bare executable (no bundle): fine for dev, but it has no Dock identity @@ -108,9 +108,50 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw (`WindowActions`), reusing `TaskOutline` for every structural rule so tools and UI can't diverge. Clients speak **stdio** to `Tic --mcp` (`MCPProxy`), which pipes to the socket — one config works for every client, and the server lives in the app next to the observers. Off by default - (`AppModel.mcpEnabled`). **Live updates are free:** tools write the DB, the existing + (`AppModel.mcpEnabled`); switched on, with per-client setup snippets, in Settings › AI Agents. **Live updates are free:** tools write the DB, the existing `ValueObservation` streams push into open panels; the one addition is `observeNote(id:)` so the controller streams its own note row too (an agent's title/colour/flag write shows live). +- **Sync between Macs (`Sync/`)** — one person's Macs share lists through a folder something else + syncs (iCloud Drive by default, or any Dropbox / Google Drive / OneDrive / Syncthing folder). **No + CloudKit:** every iCloud API needs an entitlement an ad-hoc app can't carry; plain files need none. + Each Mac writes only `devices/.json` (a `SyncSnapshot`) and reads the others, so a sync service + never sees a conflict. `SyncMerge` (pure, like `TaskOutline`) is a state-based CRDT: every synced + field is a `Register` (newest stamp wins), a note's whole outline (order + nesting) is one + register, **delete always wins**, and stamps are `max(now, clock + 1)` so an edit made after seeing a + change beats it on a slow clock. `record` diffs the DB against `resolve(snapshot)` (not the raw + registers), so values this Mac adjusted on apply never look like local edits. + `AppDatabase.syncCycle` does record → merge → apply in **one write transaction**, touching only + synced columns: frame, `isOpen`, collapsed, float, all-Spaces and the note's own `sortIndex` stay + per Mac, and lists from another Mac arrive **closed**. + **Per list, opt-in** (`note.isSynced`, off for new lists): the switch is itself a register + (`sharing`), so off on one Mac is off on all, each keeping its copy. Every Mac still *records* every + list (`sync-state.json` holds them all), but the folder file is `published()` — synced lists only — + so a list switched back on merges with real stamps. Deletes are scoped: a list deleted while synced + is tombstoned everywhere; one deleted while not synced only leaves this Mac (the `syncLocalDelete` + table, filled by an `AFTER DELETE` trigger, notes the switch **at the moment of deletion** — a + switch-off followed at once by a delete wasn't recorded yet and used to delete everywhere; the fuzz + run caught it). Task tombstones are made only for lists that ever synced. + **Images** travel as `images/.png` (immutable, named by `taskImage.hash`, filled on write or + lazily by the first sync); a task's `image` register holds the hash and crop. A picture whose file + hasn't arrived keeps this Mac's own register for that cycle (`waitingImages`), so it never reads as a + removal; files are loaded only when their hash checks out, and unreferenced ones are deleted after a + week. `observeTaskImageCrops` carries the hash so a replacement with the same crop reloads its thumbnail. + **UI:** ⋯ › Sync (shown only once sync is on in Settings) and Sync Now (for a list that syncs); the header's sync mark shows only while a cycle touches the + list (`FolderSync.activity`) and stays, orange, while there's a `problem`. `NoteWindowManager.sync` is + injected into note views as an optional environment object (nil in tests). `FolderSync` (`@MainActor`) runs a cycle at + start, 2 s after a synced edit (`observeSyncedChanges`, a column-limited region observation, so frame + drags don't trigger it), every 30 s, on wake, and at once on sleep; file IO is off the main actor + (an iCloud file may download as it's read). It keeps its own snapshot in `sync-state.json` beside the + DB and its device id in the `syncDeviceID` default (issued once, so a lost state file never leaves a + ghost Mac in the folder), refuses to recreate a folder whose parent vanished (an unmounted Dropbox reads as "can't + reach"), and skips files with a newer `schema` — bump it when the format changes **or `NoteColor` / + `NoteMaterial` gains a case**. Off by default (`syncEnabled` default). +- **Settings window (`SettingsView`)** — a SwiftUI `Settings` scene (⌘, and Tic › Settings… come + free) with three `Form(.grouped)` tabs: General (Launch at Login, version, update frequency + Check + Now), Sync (switch, folder, other Macs, and a switch per list), AI Agents (the MCP switch and + per-client snippets). The selected tab is remembered in the `settingsTab` default. The menu-bar item calls + `openSettings` after `NSApp.activate()`: a window opened from a menu-bar menu otherwise appears behind + the frontmost app. - **App shell** — `TicApp` provides a `MenuBarExtra`; `main.swift` (not `@main`) routes `--mcp` to the proxy, else `TicApp.main()`; `AppDelegate` (`NSApplicationDelegateAdaptor`) builds the shared `AppDatabase` + `NoteWindowManager` and calls @@ -214,8 +255,9 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw (title/task/secondary/completed/checkbox) for a `Surface` (`.solid` uses per-theme tuned inks; `.glass` uses adaptive `.primary`/`.secondary`). Views read a resolved `NoteTheme`, never branch on material themselves. -- **Updates install in place, after a confirmation (`UpdateChecker` + `UpdateInstaller`).** Daily - GET of the GitHub releases list (one request brings every release's git-cliff notes, parsed by +- **Updates install in place, after a confirmation (`UpdateChecker` + `UpdateInstaller`).** A GET of + the GitHub releases list at launch and then daily or weekly (`Frequency`, Settings › General; Never + turns it off; `lastChecked` is remembered and re-evaluated hourly) (one request brings every release's git-cliff notes, parsed by `ReleaseNotes`), compared numerically against `CFBundleShortVersionString` (nil under `swift run` → checker off). The menu item and the banner open the update window (`UpdateView`, a floating panel from `AppModel.openUpdate`): the notes for every version since the installed one, then Update Later / @@ -242,8 +284,8 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw banner, copy the build to `/Applications/Tic Dev.app`, give it a unique `CFBundleIdentifier` (PlistBuddy), re-sign ad-hoc, then `open` it. Re-arm with `defaults delete updateNotifiedVersion updateSeenVersion`, and delete the copy after. -- **Models are sync-friendly.** `Note`/`TaskItem` use `UUID` PKs + `updatedAt`; relationships and - defaults are chosen so CloudKit/iCloud sync stays feasible later (currently local-only). +- **Models are sync-friendly.** `Note`/`TaskItem` use `UUID` PKs, which is what lets `SyncMerge` key + every register by id across Macs. ### Swift 6 strict concurrency diff --git a/PLAN.md b/PLAN.md index 6755ace..18bffec 100644 --- a/PLAN.md +++ b/PLAN.md @@ -336,10 +336,84 @@ Tests/TicTests/ open panel. Toggle MCP off → the agent's next call fails with the stderr hint. Connect a second client and confirm "2 connected" and that both see each other's writes via `get_note`. +## Sync between Macs (planned) + +The request: one person, two Macs (work laptop + home desktop), used **one at a time**. Same lists +on both, changes carried between sessions, but **each Mac chooses which lists are open**. + +### Decision: files in a synced folder, not CloudKit + +CloudKit (and every other iCloud API) needs the iCloud entitlement, which an ad-hoc signed app can't +carry — it takes a paid Developer Program account, Developer ID signing, a provisioning profile and +notarisation. A synced *folder* needs none of that: Tic only reads and writes plain files, and +whatever syncs the folder does the networking. Default `iCloud Drive/Tic`; a "Choose Folder…" +picker covers a work Mac without personal iCloud (Dropbox, Google Drive, OneDrive, Syncthing). +Rejected: the SQLite file itself in iCloud Drive (WAL files sync separately → corruption), a server +of our own (accounts, hosting, breaks local-only), LAN peer-to-peer (the Macs are rarely on together). + +### Shape: one file per Mac, a last-writer-wins CRDT + +``` +/devices/.json ← each Mac writes only its own file +/images/.png ← immutable, named by content +``` + +- **Single writer per file**, so a sync service never sees a write conflict (no "conflicted copy"). +- **Export** (a second or two after a DB change, via a GRDB observation on `note`/`task`): diff the + DB against this Mac's last snapshot, stamp the changed fields, write the file atomically. Offline + is fine — the write is local and uploads later. +- **Import** (launch, wake, ~30 s poll): read the other Macs' files, merge with the pure + `SyncMerge`, apply in one transaction, and copy the winners into this Mac's snapshot so it doesn't + re-claim them. SQLite stays the only source of truth; the schema is unchanged; open panels update + through the existing `ValueObservation`s. +- The merge is a state-based CRDT (commutative, idempotent), so file read order and repeats don't + matter. Tests assert exactly those properties plus the rules below. + +| What | Rule | +|---|---| +| Task text, `isDone` (+ `completedAt`) | One register per field; newest stamp wins | +| Note title, colour, material, list options | One register per field; newest stamp wins | +| A note's task order + nesting | **One register for the whole outline** (`[(taskId, level)]`); newest wins; a task missing from the winner goes after its previous neighbour; written back via `applyStructuralUpdate` + `normalizedLevels` | +| Deletes | **Delete always wins**, even over a newer edit; a deleted note takes its tasks | +| Frame, `isOpen`, collapsed, float, all-Spaces, the note's own `sortIndex` | Never in the file — per Mac | +| Stamp | `max(now, highest stamp seen + 1)`; a same-millisecond tie goes to the larger encoded value, so every Mac picks the same winner | + +Per-field registers mean a tick on one Mac and a text edit on the other both survive; the outline as +one register means two reorders never interleave into a jumble. Files carry a `schema` number — a +Mac that sees a newer one skips it and asks to update Tic. + +- **Sync is per list and opt-in.** New lists stay on their Mac until switched on (⋯ › Sync, or the + list of lists in Settings › Sync). The switch is itself a register: off on one Mac is off on all, + every Mac keeps its copy, and only synced lists are written to the folder. Every Mac keeps recording + all its lists locally, so switching a list back on merges the copies field by field. A list deleted + while synced is deleted everywhere; one deleted while not synced only on that Mac (noted by a trigger + at deletion time). The note's sync mark shows only while a sync touches it (orange while the folder + can't be reached), and ⋯ has Sync Now. +- A list **created on the other Mac arrives closed** and shows up in the menu-bar Lists; opening it + makes it open on that Mac from then on. +- Settings › Sync lists each other Mac with **"Latest changes