From 5173b2a165809a0a56b33f26708b25e2c79092ca Mon Sep 17 00:00:00 2001 From: ehitimum Date: Thu, 12 Nov 2026 22:56:43 +0600 Subject: [PATCH 1/3] docs: define MnemoSync architecture and gated delivery strategy --- docs/ARCHITECTURE.md | 8 + docs/DEVLOG.md | 9 + docs/IMPROVEMENT_PLAN.md | 6 + docs/MNEMOSYNC_ARCHITECTURE.md | 86 +++ docs/MNEMOSYNC_MIGRATIONS.md | 41 ++ docs/MNEMOSYNC_TEST_MATRIX.md | 37 ++ docs/MNEMOSYNC_THREAT_MODEL.md | 66 ++ docs/mnemosync/MEMORY.md | 100 +++ .../MnemoSync_Full_Development_Plan.md | 619 ++++++++++++++++++ 9 files changed, 972 insertions(+) create mode 100644 docs/MNEMOSYNC_ARCHITECTURE.md create mode 100644 docs/MNEMOSYNC_MIGRATIONS.md create mode 100644 docs/MNEMOSYNC_TEST_MATRIX.md create mode 100644 docs/MNEMOSYNC_THREAT_MODEL.md create mode 100644 docs/mnemosync/MEMORY.md create mode 100644 docs/mnemosync/MnemoSync_Full_Development_Plan.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e0f7bd8..5c2c795 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -3,6 +3,14 @@ A quick map of how the app is put together, so changes don't require re-reading everything. For the chronological change history see [DEVLOG.md](./DEVLOG.md). +## MnemoSync development + +The serverless sync strategy and dependency gates live in +[MNEMOSYNC_ARCHITECTURE.md](./MNEMOSYNC_ARCHITECTURE.md), with a separate +[threat model](./MNEMOSYNC_THREAT_MODEL.md), [migration contract](./MNEMOSYNC_MIGRATIONS.md) +and [test matrix](./MNEMOSYNC_TEST_MATRIX.md). Start from current AI feature HEAD, not stale main. +Phase 0 introduces recovery archives; LAN/Drive and Smart Merge remain later gated phases. + ## Stack - **Shell:** Tauri 2 (Rust backend + system WebView). - **Frontend:** React 19 + TypeScript + Vite 8, Tailwind CSS v4. diff --git a/docs/DEVLOG.md b/docs/DEVLOG.md index 92d3960..763548c 100644 --- a/docs/DEVLOG.md +++ b/docs/DEVLOG.md @@ -30,6 +30,15 @@ Items 1–3 were in the released 2.1.0; each fix has a regression test. byte-identical, from `node_modules`, no network). - Version 2.1.1 in `package.json`, `Cargo.toml`, `tauri.conf.json` (not tagged). +## 2026-11-12 — MnemoSync strategy and initial recovery slice + +- Extracted the supplied development plan and MEMORY.md under `docs/mnemosync/`; treated as + reference documents. Verified PR #1 is open and feature HEAD is still `0f15939e2f30`. +- Recorded architecture decisions, threat model, schema/migration contract, phased PR strategy + and an honest automated/device/visual acceptance matrix. Preserve current AI work and UI shells. +- Phase 0 implementation begins with checked native ZIP recovery; transports and Smart Merge + remain gated follow-on work. Baseline `npm run check`: 116 tests, lint/types/build pass. + ## 2026-11-12 — Isolate AI revisions from nearby typing in undo history - After fixing the CI runtime, Linux exposed a real timing bug: a fast accepted AI rewrite diff --git a/docs/IMPROVEMENT_PLAN.md b/docs/IMPROVEMENT_PLAN.md index a913d0c..ab0fef1 100644 --- a/docs/IMPROVEMENT_PLAN.md +++ b/docs/IMPROVEMENT_PLAN.md @@ -5,6 +5,12 @@ _Assessed 2026-09-11 on branch `v1_stable_UI` (HEAD `1a4535f`); shipped as v2.0. ## 1. Where the codebase stands +**MnemoSync (2026-11-12):** development starts from the integrated AI feature HEAD. Strategy, +ADRs and security/test gates: [MNEMOSYNC_ARCHITECTURE.md](./MNEMOSYNC_ARCHITECTURE.md). +First deliverable is native checked backup/restore with existing desktop/phone settings styling; +then SQLite/IndexedDB and portable assets, Smart Merge, shared replay engine, LAN, Drive, hybrid +and recovery UX. The Android/installed-app gate remains pending until actual device evidence. + **Stack:** Tauri 2 (Rust) · React 19 + TypeScript 6 · Vite 8 · Tailwind v4 · TipTap 3 · React Flow 12 · Konva 10. Three targets share one codebase: Windows desktop (WebView2), Android (Tauri mobile), and the web build (browser fallback backend in `lib/api.ts` → localStorage). diff --git a/docs/MNEMOSYNC_ARCHITECTURE.md b/docs/MNEMOSYNC_ARCHITECTURE.md new file mode 100644 index 0000000..4677141 --- /dev/null +++ b/docs/MNEMOSYNC_ARCHITECTURE.md @@ -0,0 +1,86 @@ +# MnemoSync implementation strategy + +Baseline verified 2026-11-12: local `feature/ai-assistant` and open PR #1 both point to +`0f15939e2f309d0021575e69ebe9075843b1a9f6`. Main is still `6a54d255724a`. +New work branches from that feature HEAD, without merging or altering PR #1. + +The supplied [development plan](mnemosync/MnemoSync_Full_Development_Plan.md) and +[handoff memory](mnemosync/MEMORY.md) are reference inputs. They are not authorization to +merge existing PRs, provision accounts, expose manuscripts, or claim unperformed testing. +The requested work authorizes implementation, testing and new PRs. + +## Delivery order + +| Slice | Deliverable | Gate before proceeding | +|---|---|---| +| 0a | This strategy, ADRs, threat model, test matrix, supplied plan | Verify branch baseline and preserve existing AI work | +| 0b | Native checksummed recovery ZIPs and settings controls | Round-trip chapters, hierarchy, maps, assets, sessions and exports without changing originals; desktop/Android acceptance remains explicit | +| 1 | Native SQLite sync state, web IndexedDB migration, portable hashed assets | Crash-safe local saves/outbox; old projects and browser data preserved | +| 2 | Smart Merge preview, alias mapping and journaled staging | Volume 1 vs root fixture; keep divergent Chapter 3 and import Chapter 4 once | +| 3 | Revision DAG, tombstones, durable replay, transport interface | Reordered/duplicated/lost-message simulations and concurrent edits | +| 4 | Separate native LAN trust and per-project grants | Real Windows/Android Wi-Fi tests, revocation and AI-pairing isolation | +| 5 | Same-account Google OAuth and immutable Drive transport | Real cross-client appData access, secure native tokens, web expiry recovery | +| 6–8 | Hybrid receipts, conflict/recovery UX, fault/security/performance tests | No false Synced state, account isolation, real hardware soak and rollback | + +Each slice gets its own reviewable PR. Where prerequisites are still open, use stacked PRs; +retarget dependent PRs after their bases merge. Do not represent Phase 0 as working synchronization. + +## ADR 001 — Keep the local source of truth + +Native `project.json`, `documents/*.json`, `assets/` remain authoritative. Add SQLite WAL state +for intents, revisions, outbox, inbox, aliases and per-transport receipts; do not convert project +files into an opaque database. Web moves from localStorage to IndexedDB with a transactional +copy/read-back migration that retains the legacy source until verified. AI sessions migrate +locally but remain excluded from sync by default. + +Write intent before file mutation; atomically save file; commit queue and revision state; close +intent. Startup recovery compares hashes and completes or rolls back unresolved intents. A failed +transport never reverses a successful local save. Remote changes must be staged rather than +resetting an actively edited TipTap/canvas document. + +## ADR 002 — Causal immutable revisions + +Schema v1 uses UUID operation IDs, canonical project/entity IDs, origin device sequences, parent +revision hashes, payload hash and action. Client timestamps are display information. Multiple +unrelated heads remain a conflict; deletes remain tombstones. Duplicate operation IDs dedupe +across LAN and Drive; mismatched bytes for an existing operation ID are rejected. Receipts are +per destination, so LAN delivery alone cannot clear a Drive queue. + +## ADR 003 — Separate trust domains + +Existing AI pairing grants inference access only. Sync will have a separate protocol identity, +purpose-separated cryptography and explicit project read/write grants; discovered devices get no +project information until authorized. No sync network listener or OAuth flow is added in Phase 0. + +## ADR 004 — Drive is an optional transport + +Use the same user's appDataFolder with `drive.appdata`, distinct platform OAuth clients under one +application, and a real cross-client proof before transport implementation. Publish immutable +verified blobs before their batch manifests, retain cursors per account, and reconcile invalid +cursors without propagating cloud deletion. Keep browser access tokens in memory, native tokens +in secure stores. Google provisioning and live authorization require the user's account context. +Recheck official OAuth/Drive documentation at implementation time. + +## ADR 005 — Merge preserves alternatives + +Choose a canonical UUID and hierarchy once, never a permanent winning device. Name matching only +suggests candidates. Folder placement and content comparison are independent. A confirmed phone +root chapter may move under desktop Volume 1 without being considered a text conflict. Snapshot +both originals, stage a new project, retain aliases and journal decisions. Unknown-base divergent +chapters and graph snapshots require review; never concatenate or select by timestamp. + +## ADR 006 — Recovery archives are separate from sync + +Native Phase 0 recovery uses a versioned ZIP with exact bytes and SHA-256 digests for allowlisted +project data. This is corruption detection, not encryption or proof of a trusted sender. AI +conversations and generated exports belong in a manual recovery archive but do not enter sync by +default. Credentials, registry, pairing grants and app-level settings are outside the allowlist. + +Restore activates a fresh local project identity in a new directory, leaving originals and their +registry entries intact. Only image attributes and known JSON asset fields are relocated; prose, +IDs and graph labels are not subject to global replacement. Restored AI provider configuration +is disconnected, while session files remain recoverable. The original archive retains metadata. + +See [migration contract](MNEMOSYNC_MIGRATIONS.md), [threat model](MNEMOSYNC_THREAT_MODEL.md) and +[test matrix](MNEMOSYNC_TEST_MATRIX.md). The Phase 0 gate includes actual Android file-picker, +storage and recovery checks; passing Windows unit tests cannot satisfy it. diff --git a/docs/MNEMOSYNC_MIGRATIONS.md b/docs/MNEMOSYNC_MIGRATIONS.md new file mode 100644 index 0000000..246c657 --- /dev/null +++ b/docs/MNEMOSYNC_MIGRATIONS.md @@ -0,0 +1,41 @@ +# MnemoSync schema and migration contract + +## Recovery ZIP v1 + +File `mnemoscript-backup.json` has `format: "mnemoscript-project-backup"`, `schemaVersion: 1`, +`projectId`, `sourceRoot`, and a `files` map keyed by relative `/` paths. Each value is +`{size, sha256}` for the exact archived bytes. The manifest does not checksum itself. It is +bounded and version checked; digests do not authenticate the archive author. Future versions +must add an explicit reader/migration path; unknown versions fail without activation. + +The archive preserves allowlisted source bytes including unknown JSON metadata. Restore changes +only project UUID/path and a visible `(restored)` name suffix, disconnects project AI configuration, remaps image references, and +serializes the affected JSON. Document/folder IDs, manuscript formatting/content, graph node +IDs, sessions and asset bytes remain. Original metadata remains in the unmodified ZIP. Restored +project JSON has a content-free document index; per-document files remain authoritative. + +Restore is a separate local copy, not adoption of the original sync identity. A later Smart Merge +must explicitly link these identities. No SQLite, IndexedDB, asset-URI or sync-schema migration +runs in Phase 0. There is no change to existing project save/open APIs or AI pairing permissions. + +Native command boundary: `backup_project({projectId}) -> ApiResponse` creates a unique +archive in the app's sibling `backups/` directory; `restore_project_backup` accepts a raw ZIP body +and returns the registered Project. Compression/extraction run on a worker. Frontend `lib/api.ts` +unwraps envelopes and uses plugin filesystem/dialog APIs for an optional user-selected archive +copy. The restore picker reads a user-selected ZIP as binary, with an early size check. + +Backend tooling now requires Rust 1.88 or newer for ZIP 9.5; CI already installs stable. Lockfile +records exact dependency resolutions. ZIP only enables pure-Rust deflate, without unrelated +compression/encryption backends. + +## Next schemas (design only) + +Native SQLite migrations will version durable write intents, revision hashes/heads, operation +IDs and origin sequences, outbox/inbox, per-destination receipts, account namespaces, tombstones, +merge aliases/journals. Retain native JSON, support interrupted migration/recovery, and refuse +unsupported mandatory protocol versions. + +Web IndexedDB migration must transactionally copy and verify localStorage projects and +`mnemoscript:ai-sessions:*`, retain legacy source until verification, and support interruption, +quota failure, tab races, old projects and no-login/offline use. Asset hashes/URIs require a +separate compatibility migration with readable-byte validation and missing-asset reporting. diff --git a/docs/MNEMOSYNC_TEST_MATRIX.md b/docs/MNEMOSYNC_TEST_MATRIX.md new file mode 100644 index 0000000..de4ee68 --- /dev/null +++ b/docs/MNEMOSYNC_TEST_MATRIX.md @@ -0,0 +1,37 @@ +# MnemoSync verification matrix + +Baseline on 2026-11-12: `npm run check` passed lint, types, 116 existing tests and production build. +Large-bundle warnings predate this change. Run required checks again after the implementation. + +| Layer | Required evidence | Scope | +|---|---|---| +| Native archive unit | Exact bytes, hierarchy, Unicode/HTML marks, graph IDs, paths, sessions/exports, repeated restore | `cargo test backup::` | +| Native rejection | Corruption, truncation, missing/extra files, unsafe paths, symlinks, size/version mismatch, folder cycles | No activated or staged partial result on ordinary failure | +| Mounted UI/UX | Desktop/phone variants, no-project restore, busy states, accessible errors, cancel/retry, oversize before read, duplicate requests | `regression/backup.regression.test.tsx` | +| App regression | Dirty chapter saved before snapshot; local save failure prevents backup | `regression/backup-app.regression.test.tsx` | +| Existing behavior | All previous editor, maps, AI, pairing, project storage tests | `npm run check`, `npm run test:regression`, `cargo check`, `cargo test`, `cargo clippy -- -D warnings` | +| Visual layout | Desktop and phone settings, theme contrast, long paths, keyboard and touch | Pending: local browser preview access was denied by the permission gate; do not claim screenshots reviewed | +| Installed Windows | Custom-path project, image and map render after restore, library includes original and copy, external ZIP copy | Pending real app acceptance | +| Real Android | App-private backup, ZIP chooser, Save a copy provider access, restore, reopen, image/map render | Pending real device acceptance | + +## Synthetic corpus for every storage/merge phase + +Use synthetic writing only, never the user's manuscripts in committed fixtures. + +- Desktop Novel / Volume 1 / Chapters 1–3 / Mind Map; mobile Novel / root Chapters 1–4 / Mind Map. +- Distinct project/doc/folder UUIDs. Chapter 1 identical, Chapter 2 folder-only difference, + Chapter 3 divergent, Chapter 4 phone-only. Both map snapshots diverge. +- Rich HTML marks, lists, Unicode, embedded images; imported fantasy-map item, background image + and baked terrain; custom Windows path and Android app-private paths; per-project AI sessions. +- Missing/corrupt document file, missing asset, invalid folder reference, cycle, unsafe archive, + stale timestamp, interrupted write, full disk, app killed, stale cloud cursor and account change. + +## Later release gates (not implemented/tested) + +Smart Merge must back up both originals, preview matching/placement separately from content, +preserve divergent Chapter 3, import Chapter 4 once and survive interruption. Randomized +multi-replica replay must converge without timestamp wins or stale resurrection. LAN requires +real Wi-Fi/device grants/revocation; Drive requires same-account cross-platform OAuth proof, +expiry/quota/cursor recovery and no account mixing. Hybrid tests must apply identical IDs once +and keep each transport pending until its own receipt. Test Android suspension and live-editor +composition, plus diagnostic content redaction and staged rollback, before release. diff --git a/docs/MNEMOSYNC_THREAT_MODEL.md b/docs/MNEMOSYNC_THREAT_MODEL.md new file mode 100644 index 0000000..c14ed92 --- /dev/null +++ b/docs/MNEMOSYNC_THREAT_MODEL.md @@ -0,0 +1,66 @@ +# MnemoSync threat model and release gates + +Reviewed scope: 2026-11-12. Threats are requirements, not claims that future transports exist. + +## Assets and boundaries + +Protect manuscript text, revisions, graph/map data, binary assets, private AI conversations, +project identity mappings, device keys, Google tokens and local paths. Boundaries are untrusted +archives, peer networks, Drive/account namespaces, the browser origin and local persistence. +An attacker with arbitrary write access to the operating-system account is outside the initial +archive threat model; a checksum is not a digital signature. + +| Capability | Default | Explicit grant required | +|---|---|---| +| Local writing and manual backup | Local only | No network identity needed | +| Restore ZIP | New local project only | User chooses an archive | +| AI inference pairing | Existing AI-only grant | Does not grant sync access | +| Sync discovery | Opaque device/service identity | No project catalogue before auth | +| Sync project read/write | Denied | Separate device trust and project grant | +| Drive | Disabled | Authorize intended account and choose projects | +| AI conversations in sync | Excluded | Future separate opt-in | + +## Archive controls + +- Accept only schema 1 and the declared file inventory; verify length and SHA-256 for every file + before activation. Require project identity match and valid document/folder relationships. +- Allow `project.json`, `documents/*.json`, `assets/**`, `ai/sessions/*.json`, `exports/**`. + Exclude app-level secrets, registry, sync state, device grants and arbitrary root files. +- Reject absolute paths, dot segments, backslashes, NTFS alternate streams, control characters, + Windows reserved names, case collisions, duplicate ZIP entries, links and special files. +- Bound archive input to 600 MiB, uncompressed data to 512 MiB, each file to 128 MiB, inventory to + 10,000 files, manifest to 4 MiB. Read/decompress with a limit, not trusting ZIP header sizes. +- Refuse linked source entries including Windows reparse points. Reject missing/external local + image references rather than announce a recoverable backup with missing image bytes. +- Never overwrite an existing backup. Delete only incomplete files/stages owned by that operation. + Interrupted private `.restore-*` folders are never listed or activated; retain for manual + inspection rather than broadly deleting them at startup. No automatic backup expiry/pruning. +- Hash inventory before and after creation; if a concurrent save changes it, fail with retry. + This detects changes but is not a filesystem-wide transactional snapshot; pause editing during + backup. The future journal layer must coordinate every local writer for stronger guarantees. +- Restore writes and verifies a new staging directory, then renames and registers the new project. + An interruption after activation but before registration leaves recoverable files, not deletion. +- Archives are unencrypted and include private AI sessions. Explain this in settings and encourage + a separate off-device copy. A backup in app-private storage is not device-loss protection. + +## Future transport controls + +LAN: authenticated encryption, fresh nonces, purpose/direction binding, replay rejection, bounded +frames/concurrency, project grants on every request, revocation that closes live sessions, no path +arguments from peers. Test untrusted Wi-Fi, hostile discovery, replay and denial of service. + +Drive: narrow scope; tokens never in project snapshots, localStorage or diagnostic logs. Account +namespaces and pending queues stay isolated. Publish blobs before batches; validate hashes before +reference application; back off on errors; never turn missing cloud data into mass local deletion. +Drive transport is not automatically end-to-end encryption or independent backup. + +Merge/replay: preserve all concurrent heads, reject mismatched operation identities, retain +tombstones and source snapshots; journal interrupted merges; never overwrite active editor +content during composition. Test malicious HTML and graph payloads at rendering boundaries. + +## Pending validation + +Actual Windows and Android round trips, Android save-picker access and off-device archive copy, +crash/power-loss fault injection, real LAN peers, Google OAuth client configuration/account +switches, API quota handling, browser compatibility, large-project memory/performance and soak. +No public sync release until these gates have explicit evidence in the test matrix. diff --git a/docs/mnemosync/MEMORY.md b/docs/mnemosync/MEMORY.md new file mode 100644 index 0000000..f527c67 --- /dev/null +++ b/docs/mnemosync/MEMORY.md @@ -0,0 +1,100 @@ +# MnemoSync Project Memory (Development Handoff) + +> **Scope:** This is a project-specific handoff note for MnemoScript developers and coding assistants. It is **not** a dump of ChatGPT's private memory, hidden reasoning, credentials, or user profile. Update it alongside implementation. + +## Goal + +Implement optional, secure, low-cost **local-first project synchronization** for Windows (Tauri 2), Android (Tauri mobile), and web (React/Vite) without a MnemoScript-operated server: + +- **MnemoLink:** native devices discover each other on LAN; one-time explicit pairing and project grant, then automatic trusted reconnection and encrypted peer sync. +- **MnemoDrive:** user authorizes their own Google Drive `appDataFolder`; multiple devices signed into the same Google account share project revisions through Drive. The web app uses Drive first. +- **Smart Project Merge:** safely link independent copies of a novel, including the real example of **desktop `Volume 1` with chapters under it vs Android root-level chapters**. Preserve divergences and extra chapters, choose a canonical hierarchy and UUID, not a permanent master device. + +## Baseline inspected 2026-11-12 + +- Repo: `ehitimum/MnemoScript`; **`main` is old** (`6a54d255724a...`). +- PR #1 `feature/ai-assistant` -> `main` is **open**. Latest inspected feature commit: `0f15939e2f309d0021575e69ebe9075843b1a9f6`. +- Feature branch has v2, v2.1 AI, phone AI pairing and **new Codex CLI support** (after v2.1 tag). Start sync development from the integrated feature-branch HEAD / post-merge main, not from stale main. +- Native files: `app/src-tauri/src/project.rs`: `/project.json` with metadata/folders/content-free document index, `documents/.json` with authoritative content, assets under `assets/`, AI sessions under `ai/sessions/`. +- Web fallback: `app/src/lib/api.ts` uses `localStorage` for projects and AI sessions; must migrate to IndexedDB for real sync. +- Project data: `app/src/types.ts`; document types are text, mindmap, fantasymap. Folder references use `folderId`, folders use `parentId`, `order`. +- Assets: `app/src/lib/assets.ts`, `mapAssets.ts`; current serialized content can contain **absolute local paths**. Migrate to stable asset URIs/hashes. +- Existing AI pairing: `app/src-tauri/src/ai/pair_server.rs`, `pair_client.rs`, `pair_crypto.rs`; PC listening TCP/UDP 47815, broadcast discovery, short pairing code, SPAKE2 and XChaCha20-Poly1305. This grants **AI access only**. Do **not** silently extend it to manuscript access or share secrets without explicit authorization. +- `App.tsx` flushes pending document changes; sync must enqueue durable changes after successful local writes and preserve live editor state. +- Run `npm run check`, `cargo test`, `cargo clippy -- -D warnings` before PRs; add regressions for every data-loss bug. + +## Locked decisions for implementation + +1. Save local first. Serverless Drive is **transport/storage, not a transactional database**. Never use mutable single-project ZIP as the simultaneous multiwriter source of truth. +2. Use **stable UUIDs, immutable operations, parent revision IDs/hash DAG, per-device sequence and unique operation IDs**, idempotent replay, tombstones, explicit conflict heads. **Never last-write-wins solely by timestamp**. +3. Use a single common `SyncTransport`, implemented for LAN and Drive; identical `operationId`s deduplicate cross-transport delivery. Track receipts separately for each enabled transport. +4. Native JSON persists; add separate **SQLite sync state** (outbox, revisions, IDs, intent recovery); use **IndexedDB** for web. Crash recovery must reconcile JSON writes with durable queue. +5. Smart Merge is first-class. The writer selects preferred folder tree (`Volume 1` on desktop) and canonical project identity. Mobile root chapters can map into Volume 1 without changing their text. Identical items deduplicate, mobile-only Chapter 4 imports, divergent Chapter 3 asks for manual review. Snapshot both originals and stage safely before commit. +6. Devices auto-**discover** on Wi-Fi, but first-time trust and project access need confirmation. After that, auto-reconnect. Keep separate sync grants and crypto purpose from AI pairing. +7. Browser LAN is **not required for MVP**: no arbitrary UDP browser discovery, browser local-network permissions differ. First launch uses Drive; optional user-initiated LAN via desktop endpoint after browser compatibility proof. +8. Google OAuth: `drive.appdata` non-sensitive scope, correct desktop/Android/web clients within same Google application; validate cross-client appData access early. Native tokens stored securely; web browser token model may require user reauthorization; never store refresh token in localStorage. +9. Drive's hidden appData is **flat** and user-owned; use opaque object names/metadata and immutable change batches/blobs. A successful blob upload does not mean batch published; publish manifest last. Use changes feed cursors, handle duplicates/401/429/reset. Exports/backups are distinct from sync. +10. AI sessions, exports, CLI credentials, API keys and local registry paths do **not** sync by default. Add optional AI session sync later. Privacy/security are mandatory. + +## Concrete next work, in order + +- [ ] Verify current branch/PR #1 again, merge or branch from its integrated HEAD. +- [ ] Add architecture ADR, threat model and a lossless ZIP backup/restore command. +- [ ] Implement SQLite sync state + web IndexedDB storage and migrations. +- [ ] Build asset path-to-hash migration, portable resolver and test corpus. +- [ ] Implement Smart Merge candidate matching, desktop Volume 1 vs mobile root mapping, side-by-side chapter conflicts, alias IDs and non-destructive commit. +- [ ] Implement revision DAG, durable outbox/inbox, tombstones, generic SyncTransport and randomized replay tests. +- [ ] Add separate LAN sync handshake/crypto/authorization and test Windows + Android on real Wi-Fi. +- [ ] Implement Google OAuth on three platforms; validate same user's `appDataFolder` access from all clients. +- [ ] Implement Drive change feed, immutable batches, blobs, resumable uploads, quota backoff and account switch handling. +- [ ] Implement hybrid fan-out/dedupe, sync status UI, recovery, conflict review and full reliability/security tests. + +## Implementation update — 2026-11-12 + +- Reverified PR #1 through the GitHub connector: open, feature HEAD remains `0f15939e2f30`; + development branches from that HEAD. No merge of PR #1 was performed. +- Extracted this package under `docs/mnemosync/`. Added strategy/ADRs, threat model, + schema/migration contract and a test matrix as `docs/MNEMOSYNC_*.md`. +- Initial Phase 0 code: `src-tauri/src/backup.rs` + tests, `backup_project` and raw-binary + `restore_project_backup` commands; version-1 recovery ZIP manifest with per-file SHA-256. + Archives include chapters/maps/assets/sessions/exports, exclude app secrets/registry/grants. +- Restores stage and verify a new local project with a fresh UUID and `(restored)` name suffix; + originals stay intact. Remap only image attributes/known map image fields, including Windows + paths, HTML entities and all three fantasy-map asset fields; keep prose and graph IDs. +- BackupSettings reuses desktop cards and phone rows, has progress/errors/retry, local archive + creation, optional Save a copy and a file picker for restore. Browser labels native-only + availability honestly. App saves dirty content first and aborts backup if that save fails. +- Tooling: ZIP 9.5 requires Rust 1.88; added SHA-256, HTML rewriting/entity parsing and tempfile + tests. No SQLite/IndexedDB/portable asset migration or transport enabled yet. +- Automated evidence and pending manual gates are recorded in `MNEMOSYNC_TEST_MATRIX.md`. + Browser visual verification was blocked by denied local-preview permission; do not retry + via alternate browser tooling. Installed Windows/real Android acceptance remains pending. +- Next: finish Phase 0 device acceptance, then Phase 1 durable SQLite/IndexedDB intents and + portable assets. Google client setup and real LAN/Drive tests are still future work. + +## Critical scenario / regression test + +**Desktop:** `Novel` -> `Volume 1` -> `Chapter 1`, `Chapter 2`, `Chapter 3`, `Mind Map`. +**Mobile:** `Novel` -> root `Chapter 1`, `Chapter 2`, `Chapter 3`, `Chapter 4`, `Mind Map`; some content differs; UUIDs may be unrelated. + +**Expected:** show candidate pairing, require merge approval; choose desktop folder structure and canonical project UUID; mobile root chapters matched to corresponding Volume 1 docs (metadata-only folder mismatch is not content conflict); Chapter 4 imported under Volume 1; divergent Chapter 3 shown in a conflict preview; mind map conflict handled separately; all original source data backed up and unchanged until explicit cleanup. Both replicas end on the same logical project identity; neither becomes a permanent master. Sync via LAN and Drive without duplicate Chapter 4. + +## Security and cost constraints + +- No required MnemoScript-hosted sync server, no project-wide shared service account, no full-drive OAuth scope. +- Never claim `Drive sync` == end-to-end encryption or backup. Drive app data can be deleted independently and is invisible in Drive UI. +- Standard Drive API usage has quotas measured in request units and Google has announced potential billing for quota overages later in 2026. Batch operations, monitor API usage and back off on errors. +- LAN encrypt every project operation and blob; enforce per-project grants, device revocation, limits and path sanitization. +- Browser local network access must be initiated by explicit user gesture on HTTPS and observed permission/CORS policy; avoid assuming every browser supports it. + +## Documentation / references + +- Full plan: [`MnemoSync_Full_Development_Plan.md`](./MnemoSync_Full_Development_Plan.md) +- GitHub PR: https://github.com/ehitimum/MnemoScript/pull/1 +- Current feature branch: https://github.com/ehitimum/MnemoScript/tree/feature/ai-assistant +- Google Drive app data: https://developers.google.com/workspace/drive/api/guides/appdata +- Drive change feed: https://developers.google.com/workspace/drive/api/guides/manage-changes +- Drive usage limits: https://developers.google.com/workspace/drive/api/guides/limits +- Browser Local Network Access: https://developer.chrome.com/docs/modern-web-guidance/guides/security/local-network-access + +**Maintenance rule:** update this file after each implemented phase with schema migrations, tests, changed APIs, unresolved risks, and new PR/commit baselines. Never add real Google tokens, device pairing keys, author manuscripts, or sensitive logs to a repository memory file. diff --git a/docs/mnemosync/MnemoSync_Full_Development_Plan.md b/docs/mnemosync/MnemoSync_Full_Development_Plan.md new file mode 100644 index 0000000..39cfd10 --- /dev/null +++ b/docs/mnemosync/MnemoSync_Full_Development_Plan.md @@ -0,0 +1,619 @@ +# MnemoSync — Full Development Plan + +**Project:** [MnemoScript](https://github.com/ehitimum/MnemoScript) +**Feature:** Local-first, serverless multi-device project synchronization +**Targets:** Windows desktop (Tauri 2), Android (Tauri mobile), web (React/Vite) +**Planning baseline:** `feature/ai-assistant` at `0f15939e2f309d0021575e69ebe9075843b1a9f6` (2026-11-12) +**Repository integration:** [PR #1](https://github.com/ehitimum/MnemoScript/pull/1) is **open**; `main` remains older. Start new work from the feature-branch HEAD after confirming it is current, or merge PR #1 first. Do not develop against old `main` in isolation. +**Status:** Architectural plan; no code modifications or verified runtime integrations performed. +**Companion handoff:** [`MEMORY.md`](./MEMORY.md) + +--- + +## 0. Executive decision + +Build **one local-first sync engine** with two *optional*, interoperable transports: + +1. **MnemoLink (LAN)** — mutually authenticated, encrypted peer-to-peer sync between installed native apps on reachable local networks; automatically reconnect **after explicit first-time pairing** and project-level permission. No ongoing internet or hosted server. Existing AI pairing crypto/discovery concepts are reusable, but AI authorizations must **not** become project-sync authorizations by accident. +2. **MnemoDrive (Google Drive)** — each user grants MnemoScript a narrowly scoped Google Drive permission. Independent devices for that **same signed-in Google account** exchange immutable document revisions/change batches and content-addressed assets using the user's Drive quota. No MnemoScript sync server. The website uses this path first. +3. **Smart Project Merge** — a **prerequisite** for users who already have two independent copies of one novel. It chooses a canonical *project identity*, preferred *folder hierarchy*, and a safe mapping of items, **without choosing one whole device as the permanent winner**. Preserve every conflicting manuscript version. + +All three work over the same transport-neutral immutable change model. A LAN-delivered change and a Drive-delivered copy must have the **same operation ID**, and applying it twice must be a no-op. The local store remains primary for ongoing editing; no cloud login is required to create or use local projects. + +**Deliberate non-goals for initial release:** automatic live multi-user character-by-character collaboration, a central MnemoScript user account or backend, background Android sync guaranteed when the app is killed, universal zero-click browser discovery, automatic semantic manuscript merge, sharing projects between distinct Google accounts, and automatic syncing of OS credential stores. + +### Product contract + +- Save locally first. Users can write when offline. A failed sync never undoes a successful local save. +- Pairing automatically discovers and reconnects *trusted* devices, but a stranger on public Wi-Fi cannot read projects merely by being nearby. +- Each project controls LAN and Drive sync independently; local-only remains supported. +- Google Drive is an optional sync/backup provider, **not** a reliable transactional database. Use immutable events and verified blobs; do not update one shared ZIP or one mutable `project.json` from every device. +- `Sync complete` means all locally pending changes are durably published to each *enabled* destination, the client has applied known incoming changes, and no unresolved conflicts remain. LAN complete alone is **not** Google Drive complete. +- Sync cannot delete an original unmerged project during first-time project linking; merging must create backups and offer rollback. + +--- + +## 1. Verified codebase baseline and impact + +### 1.1 Repository audit (November 12, 2026) + +- PR #1: **“MnemoScript v2 + AI assistant (2.0.0, 2.1.0, Codex)”**, open, branch `feature/ai-assistant` -> `main`. +- The active feature branch includes v2.0.0 persistence/shell improvements, v2.1.0 AI assistant, encrypted phone-to-PC AI pairing, and a **post-v2.1.0 Codex CLI integration** in `app/src-tauri/src/ai/codex.rs` (commit `0f15939e2f30`). +- [`app/src-tauri/src/project.rs`](https://github.com/ehitimum/MnemoScript/blob/0f15939e2f309d0021575e69ebe9075843b1a9f6/app/src-tauri/src/project.rs): local filesystem projects, `project.json` with metadata/folders/content-free document index, `documents/.json` as authoritative document bodies; UUIDs and atomic writes; a registry maps UUID to local path. Native path can be user-selected. `Document` includes `id`, `title`, `content`, `updated_at`, `doc_type`, `order`, and `folder_id`. +- [`app/src/lib/api.ts`](https://github.com/ehitimum/MnemoScript/blob/0f15939e2f309d0021575e69ebe9075843b1a9f6/app/src/lib/api.ts): all Tauri IPC, plus a **web mock/fallback storing projects and AI sessions in browser `localStorage`**. This is not adequate as a production large-asset/offline sync store. +- [`app/src/lib/assets.ts`](https://github.com/ehitimum/MnemoScript/blob/0f15939e2f309d0021575e69ebe9075843b1a9f6/app/src/lib/assets.ts), `mapAssets.ts`: HTML image `src` and fantasy-map `assetPath` can hold **absolute OS paths**. Those are not cross-device portable and must be migrated. +- [`app/src-tauri/src/ai/pair_server.rs`](https://github.com/ehitimum/MnemoScript/blob/0f15939e2f309d0021575e69ebe9075843b1a9f6/app/src-tauri/src/ai/pair_server.rs), `pair_client.rs`, `pair_crypto.rs`: existing **AI-only** PC-side listener on TCP/UDP 47815, LAN broadcast discovery, 8-digit pairing code, SPAKE2, XChaCha20-Poly1305 envelopes, timestamp/replay checking, device revocation. Phone currently acts as a client of a PC, not as a symmetric full-project sync host. Pairing secrets are stored in local app files. +- [`app/src-tauri/src/ai/sessions.rs`](https://github.com/ehitimum/MnemoScript/blob/0f15939e2f309d0021575e69ebe9075843b1a9f6/app/src-tauri/src/ai/sessions.rs): AI conversations are `ai/sessions/.json`. **Default: exclude from MVP sync**; design a later opt-in with session merging and privacy prompts. +- `app/src/App.tsx`: owns local document/project state, flushes editor/canvas pending changes on switch/background/close. A new sync adapter must not re-render/reset an actively edited TipTap/Konva/React Flow document, and must register changes only after durable local save. +- `app/src-tauri/src/lib.rs`: Tauri command surface plus asset raw-byte IPC. Add new sync commands without changing public behavior of existing project/AI commands. +- `docs/ARCHITECTURE.md`, `docs/DEVLOG.md`, `docs/IMPROVEMENT_PLAN.md`, `AGENTS.md`: update with new modules and test expectations. + +### 1.2 Data and behavior inventory + +| Data | Local source | Sync v1 | Special handling | +|---|---|---|---| +| Project metadata | `project.json` | Yes | Strip local `path`, avoid syncing device-specific AI default/credentials | +| Folder tree | `project.json` | Yes | Stable folder IDs, parent mapping, move/reorder/rename conflicts | +| Rich-text chapter | `documents/.json` | Yes | TipTap HTML, preserve formatting, divergent versions | +| Mind map | document JSON | Yes | Preserve IDs and graph refs; conflicting graph snapshots reviewed | +| Fantasy map | document JSON | Yes | Images/heightmap/background asset dependencies | +| Assets | `assets/*` | Yes | Content-addressed, portable references, hash validation | +| AI chat sessions | `ai/sessions/*` | Later/opt-in | Personal writing context may be sensitive; append/same-session conflicts | +| Generated exports | `exports/*` | No by default | Regenerable and potentially large | +| Global registry | `registry.json` | Never | Local UUID -> filesystem path only | +| CLI/OAuth/API credentials | OS store/app-private | Never | Tokens never in project data or Drive files | +| Appearance and device UI prefs | device preferences | Not by default | Opt-in selective settings later | + +--- + +## 2. The key case: desktop `Volume 1` vs mobile root chapters + +### 2.1 Example + +**Desktop** (proper structure): `My Novel / Volume 1 / Chapter 1, Chapter 2, Chapter 3, Mind Map`. +**Android** (separately created): `My Novel / Chapter 1, Chapter 2, Chapter 3, Chapter 4, Mind Map` at root, with some chapters modified independently. + +These may have different **project UUIDs, folder UUIDs, and document UUIDs**, even when they represent the same story. Matching by UUID alone will not work. Treat naming/content matches as **suggestions**, not proof. + +### 2.2 First-time Smart Merge user flow + +1. **Discover candidate duplicates:** while enabling sync, compare local vs peer/Drive project catalogues. Show potential same-novel groups based on normalized project name, document title/type overlap, hashes and optionally first-/last-paragraph similarity. Never auto-merge only because a project name matches. +2. **Select intentions:** `Keep separate projects` **or** `Link these copies as one project`. +3. **Choose canonical identity:** use desktop's project UUID **or** generate a new UUID. Both are fine, but choose once. This does **not** establish desktop as a permanent master. Store source-project alias mappings and ensure all subsequent replicas use the one canonical UUID. +4. **Choose preferred organization:** offer `Desktop layout`, `Mobile layout`, or `Custom`. Default this scenario to `Desktop layout` because the writer wants the `Volume 1` hierarchy. +5. **Match folders independently of documents:** map `Desktop Volume 1` to a canonical folder ID. A root-level Android chapter that matches a chapter in `Volume 1` maps to the **canonical chapter ID** *and* **canonical `folderId`**; its missing Android folder is not a content conflict. +6. **Match documents:** exact logical UUID (same lineage) -> exact hash -> normalized title+type+substantial content similarity -> manual confirmation. Show confidence; never silently treat two different stories called `Chapter 1` as identical. +7. **Classify each document:** identical, only on one side, metadata-only difference (e.g., root vs folder), one-sided edit with a proven common base, or concurrent/unknown-base content conflict. +8. **Preview:** a tree preview shows where all imported chapters, maps, assets and folders will live. Separate *placement* decisions from *content* decisions. Mobile-only `Chapter 4` is suggested under `Volume 1`, but confirmation is required for unrelated root items. +9. **Review conflicts:** for unknown ancestry or divergent TipTap HTML, show side-by-side rendered previews and word/paragraph diffs; choose `Keep desktop`, `Keep mobile`, `Keep both`, or user-prepared manual merge. Always retain the rejected alternative in recoverable history/snapshot. Never concatenate whole chapters automatically after manual copy/paste. +10. **Backup both projects:** create immutable snapshots/exports with checksums before mutation (e.g. desktop `~/.mnemoscript/backups//...`, Android app-private backup; Drive staged backups if working remotely). +11. **Dry-run & commit:** validate IDs, folder links, asset dependencies, document types, unique orders and storage capacity. Apply to a **new staging copy**, then atomically update local registry / activate it. Journal each step so interruption resumes or rolls back safely. +12. **Publish mapping and canonical snapshot:** send a signed/authenticated `project.link` record with mapping tables, then the merged snapshot. Other replicas import canonical IDs without destructive overwrite. Existing source folders remain available until the writer explicitly removes them after confirming a successful sync on every target. + +### 2.3 Example match table + +| Android item | Desktop item | Suggested action | +|---|---|---| +| Root/Chapter 1, same text | Volume 1/Chapter 1 | Deduplicate; map Android doc ID to canonical ID | +| Root/Chapter 2, different folder only | Volume 1/Chapter 2 | Preserve text; use `Volume 1` placement | +| Root/Chapter 3, edited text | Volume 1/Chapter 3 | Conflict preview; do **not** silently select the newer file | +| Root/Chapter 4 (mobile-only) | No match | Import under Volume 1 after confirmation | +| Root/Mind Map, modified graph | Volume 1/Mind Map | Preserve both versions; graph-aware/manual choice | + +**Crucial principle:** “Choose the primary” means choosing **initial identity and folder layout**, *not* setting a perpetual authoritative device. After linking, either device may originate edits; conflicts resolve per entity. + +### 2.4 ID aliases and migration journal + +Persist `sourceProjectId -> canonicalProjectId`, `(sourceProjectId, sourceDocumentId) -> canonicalDocumentId`, and analogous folder IDs, with a `mergeId`, source fingerprints, backup locations and commit state. All ID remapping must rewrite safe internal references (e.g. `folderId`, references between linked nodes/docs) where supported. Never rewrite arbitrary prose/HTML strings by global find-and-replace. Preserve old source ID/history for import idempotency. + +Conflicts in *folder layout* can be resolved separately: if one device moves Chapter 2 into Volume 1 while the other edits Chapter 2's text, both changes may be applied because they address different fields. For concurrent differing moves, ask the user to select the destination. + +--- + +## 3. Shared sync data model: no server-side authority + +A central server is unavailable, so there cannot be a guaranteed single integer `revision` assigned by a server. Use **revision ancestry** with content-addressed versions, globally unique operations, per-device ordered batches, and deterministic/idempotent replay. Client wall-clock time is for display only, never a sole conflict tiebreaker. + +### 3.1 Stable entities + +- `projectId`: canonical UUID once linked. +- `deviceId`: random per installed device/browser profile; regenerated if local identity wiped. +- `folderId`: UUID stable across devices; parentFolderId nullable. +- `documentId`: UUID stable across devices; type `text | mindmap | fantasymap`. +- `assetId`: SHA-256 hash + MIME/extension metadata, or random ID bound to hash, with immutable bytes. +- `sessionId`: unique AI session ID if later synced. +- `operationId`: UUIDv7 or random UUID plus device sequence; never reuse. +- `revisionId`: hash of canonicalized entity snapshot and causal parent revision IDs (avoid serialization-dependent mismatches). + +### 3.2 Proposed typed records + +```ts +type EntityKind = 'project' | 'folder' | 'document' | 'asset' | 'ai-session'; +type MutationKind = 'create' | 'update' | 'move' | 'reorder' | 'delete' | 'link'; + +interface SyncOperation { + schemaVersion: 1; + operationId: string; + canonicalProjectId: string; + originDeviceId: string; + originSequence: number; + entity: { kind: EntityKind; id: string }; + action: MutationKind; + parentRevisionIds: string[]; // causal base(s), NOT timestamps + newRevisionId: string; + payloadHash?: string; // content-addressed immutable blob + metadataPatch?: Record; + createdAtClient: string; // display/debug only +} + +interface SyncBatch { + schemaVersion: 1; + batchId: string; + projectId: string; + deviceId: string; + fromSequence: number; + toSequence: number; + operations: SyncOperation[]; + checksum: string; +} + +interface LocalSyncState { + projectId: string; + enabledTransports: ('lan' | 'drive')[]; + outbox: SyncBatch[]; // DURABLE, not React-only state + appliedOperationIds: string[]; // store compactly in DB + knownRevisionHeads: Record; + perPeerCursors: Record; + pendingConflicts: string[]; +} +``` + +For the local backend, store index/outbox/heads in **SQLite with WAL and transactions** (Rust `rusqlite`/`sqlx` evaluation) while **retaining existing document JSON files** for compatibility. Browser: IndexedDB (Dexie or native wrapper) with transactional queue/state. Where file save and SQLite transaction cannot be atomic together, use a **write-ahead intent** plus startup reconciliation/content-hash scan: save file safely; queue retry; confirm both are consistent. Never mark a change as published before the corresponding payload has been verified at the destination. + +### 3.3 Ordering and causal merge + +- Same `operationId` and same payload: ignore duplicates regardless of transport. +- Same entity, new revision whose parents include current head: fast-forward. +- Different entities, independent edits: apply both. +- Same entity, parallel revisions with no known ancestry: leave multiple heads and present conflict. +- Metadata field-level merging only for explicitly commutative edits; `folderId` and `order` need deterministic behavior and conflict detection. +- Deletes use tombstones; a returning offline device must **not** resurrect deleted documents automatically. Concurrent edit vs delete becomes recoverable conflict. +- Keep snapshots/revisions for a defined retention period, separate from user-visible “Trash.” Avoid automatic garbage collection until all registered devices' state/retention rules permit it; offline devices could return months later. +- Use per-device unique operations and batch sequence continuity to detect gaps/partial transfer. Do not assume Google Drive listing order or LAN delivery is causal order. + +### 3.4 Portable asset references + +Replace absolute paths in persisted content with a stable asset URI, e.g.: + +```html +Map illustration +``` + +and map JSON: + +```json +{"assetId":"sha256-...","libId":null} +``` + +Provide one resolver per storage backend: native Tauri asset-protocol URL; web `Blob`/object URL with lifecycle cleanup. Migrate old absolute paths only when bytes are readable; missing assets produce a report + placeholder, not a permanently broken rewritten path. Asset first, referencing revision second; check size/MIME/hash on download and enforce size limits. Same hash => upload once. Do not sync binary data as base64 in document JSON. + +--- + +## 4. MnemoLink: encrypted local pairing and LAN transport + +### 4.1 Reuse versus isolate + +Reuse the conceptual infrastructure (`pair_crypto.rs` SPAKE2, XChaCha20-Poly1305, replay protection; broadcast discovery or optionally mDNS). **Do not extend `ai/pair_server.rs` with project-file permissions or reuse `ai/` trust grants without user consent**. Prefer `sync/lan/{discovery,pairing,protocol,server,client}.rs`, separate protocol name, derived or independent keys, separate port/service identity, protocol version, key rotation/revocation. AI device trust and Sync project trust are distinct capabilities. + +### 4.2 Device roles + +- Desktop: accepts inbound sessions while MnemoScript open; also dials peers. +- Android: can dial desktop reliably while foregrounded; optional foreground-only inbound listener. Background execution depends on Android lifecycle, network permissions, OS restrictions and user expectations. +- Multiple devices: no single permanent master. A peer advertises project IDs only after authentication/authorization; no manuscript metadata in pre-auth discovery beacons. +- Browser: **not v1 auto-discovery**; browsers cannot use arbitrary UDP discovery. Later use a user-initiated known-address/QR local WebSocket/HTTP channel if browser security policy permits; Drive is v1 web path. + +### 4.3 Discovery, authentication and authorization + +1. Device advertises random/opaque ID and service/protocol version on LAN, not chapter titles or project names. +2. Known devices reconnect automatically and mutually authenticate their saved identity. +3. New device: explicit user-initiated pairing, 8-digit code/QR and SPAKE2 (or equivalent vetted PAKE), limited attempts, short validity, short confirmation of device fingerprint. +4. After device trust: show **project access grants** (`read/write` per project, optionally read-only); default *no access*. Confirm both sides for each project link. Revocation takes effect on next request; actively terminate live sessions. +5. Secure session encryption/integrity, purpose- and direction-separated AAD, fresh nonces, replay protection, per-request IDs; limit peer payload sizes/rates and bound concurrent sessions. +6. Exchange protocol/schema capabilities; reject unknown mandatory schema, downgrade to safe read-only with upgrade message. +7. Exchange project catalogs/heads, missing operation IDs/hashes and assets; transfer in bounded chunks; hash-verify and acknowledge; checkpoint cursors. Resume interrupted sessions. +8. When offline or peer gone, retain durable outbox; retry when peer reappears/app resumes. Do not block editor saves. + +### 4.4 LAN wire protocol (illustrative) + +`POST /sync/v1/hello`, `/pair`, `/auth`, `/projects`, `/summary`, `/batches/pull`, `/batches/push`, `/blobs/get`, `/blobs/put`, `/ack`, `/revoke`. All project-affecting methods require cryptographic authentication + scoped authorization. Prefer a well-tested framed binary protocol or HTTP with robust bounds rather than expanding minimal hand-rolled HTTP parser for uploads. + +Propose manifest exchange and diff by hashes: send small summaries first, transfer missing blobs only, fetch incremental batches. TLS is optional **only if** application-layer encryption thoroughly protects confidentiality and integrity for **every** message and binary chunk; explicit domain separation is mandatory. Avoid raw plaintext project content over LAN. + +### 4.5 Failure/corner cases + +- Wi-Fi client isolation, firewalls, VPNs, subnet discovery differences, IPv6, Windows network profile, Android multicast/broadcast restrictions, local IP changes, lost UDP replies, two peers simultaneously initiating, duplicate delivery, partial blob uploads, wrong device clock and revocation during transfer. +- Browser bridge requires HTTPS hosting, permission/CORS, and origin allowlist, with no arbitrary websites allowed to call desktop. Cross-browser universal support is **not guaranteed**. +- Existing AI pairing uses UDP discovery and TCP port 47815; avoid port collision and segregate state. After product validation, a shared discovery registry can advertise **distinct service capabilities**, not shared authorization. + +--- + +## 5. MnemoDrive: user's own Google Drive as rendezvous + storage + +### 5.1 Storage choice and identity + +**Primary option:** hidden `appDataFolder`, OAuth scope `https://www.googleapis.com/auth/drive.appdata`. This is a per-user, per-application hidden area and *does not appear in the regular Drive UI*. Files in this area are not shareable and cannot be moved/trash-managed like regular files; user account storage limits apply. The actual file namespace is flat: represent logical paths in filenames/properties and client manifests, not with real directories. + +**Secondary option, later:** visible `MnemoScript Backups` folder under My Drive, with `drive.file` and user-created/app-created files. Offer manual ZIP/JSON export; do not silently move live appData into a Drive folder (different spaces). Clearly distinguish **Sync** vs **Backup/Export**. Never request broad full-Drive scope for convenience. + +An installed app, Android app and website must use properly configured OAuth client identities within the same MnemoScript Google Cloud application/consent configuration; **test cross-platform access to the same `appDataFolder` account in a real environment before investing in sync logic**. A Google account connected on one device does not automatically authenticate another device; each must explicitly authorize, and must match the intended Google account. + +### 5.2 OAuth implementation + +- **Windows:** installed-app OAuth authorization-code + PKCE/system browser with localhost loopback redirect; store refresh material securely in Windows Credential Manager, scoped to MnemoScript, never in the project folder. +- **Android:** platform-supported native Google authorization via Android integration (Google Identity Services / current recommended authorization API) with correct package name/signing fingerprint and Tauri plugin boundary; secure refresh/token material using Android Keystore-backed encryption where supported. Do not put refresh tokens in regular JSON or JS localStorage. +- **Web:** Google Identity Services browser token flow with user gesture, in-memory access token and clear expiry/reconnect UI. A browser-only app **cannot promise indefinite unattended auth refresh without a backend**. Never embed an OAuth client secret or persist a refresh token in accessible localStorage. +- **Security:** identify account by Google stable subject ID (`sub`) if requested appropriately (e.g. OpenID Connect); compare account identity when linking devices. App data remains scoped to the signed-in account; no server-side user database. + +### 5.3 Drive storage layout: immutable, retryable + +With no transaction/CAS on a shared project file, never let two devices overwrite a mutable `project.json` or `novel.zip`. Instead: + +```text +appDataFolder (flat; conceptual names) + mnemo-v1/catalog/ # optional acceleration + mnemo-v1/p//ops//-.json + mnemo-v1/p//blobs/ + mnemo-v1/p//snapshots/.json + mnemo-v1/p//merge/.json +``` + +These are **file naming conventions**, not actual nested Drive folders. Each immutable batch references only already uploaded and hash-verified payloads. Batch publication is the commit marker. Identical retries can create duplicate Drive file entries, so content IDs/operation IDs are part of metadata and the client must reconcile duplicates idempotently. Query efficiently via `files.list(spaces=appDataFolder, ...)` initially, then persist `changes.getStartPageToken`/`changes.list(spaces=appDataFolder)` cursors. `changes.list` describes *file* updates, not application-level revision ordering; the sync engine still reads operation manifests and resolves ancestry. On an invalid/unusable cursor, perform full reconciliation, not blind overwrite. + +**Traffic optimization:** debounce editor saves to a bounded local queue, coalesce untransmitted revisions of the same entity *only if causal history and conflict detection remain valid*, write compact batches at reasonable time/size thresholds, gzip when appropriate, hash dedupe assets, and checkpoint/snapshot to avoid unbounded replay. Do not create one Drive file per keystroke. Preserve conflict-producing revisions and current heads. + +### 5.4 Drive lifecycle + +1. User turns on Drive sync, signs into Google, and selects projects to sync. +2. First device uploads immutable blobs and a first project snapshot/batch; verify publication. +3. Next device discovers remote projects; offers `Download new project`, `Link to existing local project`, or `Keep separate`. If it already contains the same novel, invoke Smart Merge **before adopting a canonical ID**. +4. On local save: persist locally -> queue operation -> upload dependencies -> publish immutable batch -> mark Drive delivered. +5. Pull: read change feed -> discover manifests -> fetch missing payloads -> validate checksums/schema -> apply safely -> checkpoint. +6. After LAN delivery, still upload to Drive if enabled; Drive receives the identical operation IDs. +7. On 401/expiry: pause Drive only, keep local/LAN saves, request reconnection without discarding outbox. +8. On 403/429/quota: exponential backoff + jitter, show `Waiting for Drive`; do not busy-loop or erase changes. +9. On 404/removed app data: freeze deletion handling, offer restore from local copies/backup; do not propagate a potentially destructive cloud reset into every device. +10. On account switch: show explicit warning; keep separate namespaces/cursors per Google account; never upload account A's projects to B without explicit consent. + +### 5.5 Google API cost/quotas + +Standard Drive API usage is currently described by Google as free within standard quotas; billing for above-threshold use is **planned later in 2026**. Drive API quotas use **quota units** (for example, list methods are relatively expensive); the app creator's Cloud project may be affected even though data belongs to users. Monitor Google Cloud metrics, set safety limits/alerts and conservative poll intervals, and avoid frequently calling list endpoints for each chapter. A minimal hosting bill does **not** imply unlimited free API traffic. See official [Drive usage limits](https://developers.google.com/workspace/drive/api/guides/limits). + +--- + +## 6. One sync engine, two transports + +### 6.1 Interface and transport-independent semantics + +```ts +interface SyncTransport { + id: 'lan' | 'drive'; + connect(context: SyncAuthContext): Promise; + discoverProjects(): Promise; + exchangeHeads(projectId: string, known: KnownHeads): Promise; + pullBatches(projectId: string, cursor?: string): Promise; + pushBatch(projectId: string, batch: SyncBatch): Promise; + hasBlob(projectId: string, hash: string): Promise; + downloadBlob(projectId: string, hash: string): Promise; + uploadBlob(projectId: string, hash: string, bytes: Uint8Array): Promise; + disconnect(): Promise; +} +``` + +`PushReceipt` means **that destination acknowledged verified publication**; per-transport receipts are tracked separately. The merge/reconciliation engine must not contain transport-specific `if (drive)...` decisions. Drive availability and LAN presence can vary independently. A shared local operation outbox fans out to both enabled destinations. Incoming operations are deduplicated by `operationId` and verified payload hash. + +### 6.2 State machine + +`local-only`, `not-configured`, `needs-auth`, `discovering`, `syncing`, `up-to-date`, `offline-queued`, `conflict`, `error/backoff`, `needs-upgrade`. Show LAN and Drive status separately when both are enabled. Show pending operations and last successful exchange; never show `Synced` while content remains unsent to a selected destination. For no-op offline sessions, the local app remains usable. + +### 6.3 Concurrency/lifecycle integration + +- A document being edited may be updated remotely. Do not replace the TipTap live model mid-composition without user permission; stage incoming state, show `Remote update available` or apply safely when idle with preserved selection/undo. +- AI Auto mode modifies manuscripts through frontend tools; it must generate the same durable sync events and respect conflict/approval states. AI tools must not receive Google OAuth credentials or LAN device keys. +- Persist a per-document local dirty flag, document revision head(s), and per-transport delivery; use checksums to reconcile project JSON after abnormal shutdown. +- `project.json` metadata and `documents/*` snapshots are not a cross-file transaction. Staging/journal/replay guarantees are required around operations affecting multiple entities (e.g., moving folder+docs, initial merge, restoring backup). +- Clear revision histories and merge mappings never means silently deleting content: snapshot/recoverability first. + +--- + +## 7. Conflict resolution policy + +| Conflict | Initial policy | Future improvement | +|---|---|---| +| Same chapter edited on two devices | Preserve 2 heads; side-by-side TipTap preview/diff; writer chooses or manually merges | Proven-ancestor 3-way merge, eventually Yjs/CRDT | +| Same title but different `documentId` | Suggest duplicate match only; ask writer | Improved semantic suggestions, never auto-destructive | +| Desktop Volume 1 vs mobile root | Desktop canonical hierarchy; map matching mobile docs to `Volume 1` | Flexible folder mapping rules | +| Folder renamed differently | Preserve candidate names + prompt | Conflict-aware field merge | +| Chapter moved while text changed elsewhere | Merge move and text when independent fields/causal ancestry | Fine-grained operations | +| Different moves/reorders | Choose order/location, preserve other metadata | Fractional order keys/sequence CRDT later | +| Deleted on A, edited on B | Recoverable delete-vs-edit conflict | Version history view | +| Fantasy map/mind map concurrent edits | Keep alternative snapshots, ask; do not naïvely merge graph JSON | Domain-aware graph operations | +| Image missing locally | Download by hash; placeholder until verified | Smart prefetch | +| AI chat on two devices | Keep local by default | Opt-in session model with record-level merge | + +TipTap HTML diffing is tricky: canonical normalization must preserve marks, nodes, image refs, task lists and formatting. Use a parser-aware comparison where practical; a pure raw HTML diff is insufficient for reliable auto-merge. Without a common base, do not silently join user-edited paragraphs that may have been copy-pasted between devices. + +--- + +## 8. Full phased development plan + +Each phase has tangible code artifacts and an exit gate. Durations are **not** commitments; prioritize completion of reliability gates over dates. Release labels are proposals. + +### Phase 0 — Branch, requirements, threat model, backups + +**Build:** +- Confirm feature branch HEAD / PR #1 status; optionally merge PR #1 into `main`, then branch `feature/mnemosync` from integrated HEAD. Do not copy modules from old main. +- Add `docs/MNEMOSYNC_ARCHITECTURE.md`, `docs/MNEMOSYNC_THREAT_MODEL.md`, ADRs: storage, revision ancestry, Google scope, LAN auth, merge policy. +- Record test corpus: desktop Volume 1 + mobile root, divergent chapters, images, fantasy maps, AI sessions, cross-platform custom project paths. +- Define schema version, permissions matrix, retention, max sizes, recovery UX, and E2EE stance (Drive traffic is TLS-protected, not automatically end-to-end encrypted). +- Implement full project ZIP export/checksum/restore independent of sync. + +**Exit gate:** two existing v2.1.0 projects can be exported/restored losslessly on desktop and Android; current tests still pass; baseline documented. + +### Phase 1 — Local persistence foundation and asset portability + +**Build:** +- Native `sync/` SQLite index/queue/revision tables with WAL and recovery journal; retain JSON project files and their public APIs. +- IndexedDB web production storage (`ProjectStore` abstraction), migration from `mnemoscript:projects` localStorage and `mnemoscript:ai-sessions:*`, no accidental wipe on interruption. +- Add asset IDs/content hashes; migrate TipTap `` and map `assetPath` to portable references via import mapping; keep legacy reads compatible. +- Implement `save => durable queue` intent and crash recovery; serializable project snapshots, hash validation, schema tests; protect against path traversal/symlink escapes. +- Separate local UI settings and AI secret fields from syncable project metadata. + +**Exit gate:** old projects open unchanged; images display in all three platforms with imported test assets; huge web project avoids localStorage limits; forced-crash tests find no unrecorded committed edits. + +### Phase 2 — Smart Project Merge (required before linking old copies) + +**Build:** +- `MergeCandidateScanner`, `DocumentMatcher`, `FolderMapper`, `MergePreview`, `MergeJournal`, `MergeExecutor`. +- Source/canonical ID aliases, optional canonical project ID selection, dry-run detection, non-destructive staging copy, snapshots of both originals. +- Root-vs-Volume-1 placement mapping, exact duplicate detection, title-only suggestions, content hash/similarity candidates, safe manual review. +- Keep both conflicting chapters as explicit choices; rich text comparison and diff preview; map/mind map snapshot previews. +- Import canonical result into each target without deleting source; cancellation/rollback/resume; store merge decisions for subsequent imports. + +**Exit gate:** desktop `Volume 1` + mobile root yields canonical `Volume 1` with imported mobile-only Chapter 4; all text revisions and image/map refs recoverable; interruption during merge cannot destroy either source. + +### Phase 3 — Shared core sync engine + +**Build:** +- Model/codec (`SyncOperation`, `SyncBatch`, `KnownHeads`), immutable revision DAG per entity, outbox, apply engine, field-level metadata merge, tombstones and bounded history. +- Transactional/durable enqueue, idempotent replay, causal version verification, safe checkout of new revisions, multi-transport receipts. +- `SyncTransport` interface + in-memory deterministic transport for tests. +- Service hooks after save, project/folder change, image import, AI write tools, app launch/resume and network regain. +- Conflict work queue/UI model; separate per-project and per-device cursors. + +**Exit gate:** deterministic two- and three-replica simulation across arbitrarily reordered/duplicated/dropped messages converges for nonconflicting changes, never silently loses concurrent edits, and preserves tombstones after offline reconnect. + +### Phase 4 — LAN pairing and native sync (MnemoLink) + +**Build:** +- New sync-specific discovery, listener, authenticated session, project grant and revoked-device table. Consider mDNS plus existing UDP discovery fallback. +- Extract **only safe crypto helpers** from `ai/pair_crypto.rs`; use new purpose-specific keys/capabilities. Strict separation of AI inference and sync permissions. +- Desktop PC as responsive listener + Android foreground client; optionally Android foreground listener once stable. +- Wire endpoints for summaries, missing ops/blobs, chunked encrypted transfer, acknowledgments, cancellation, retries. +- Trust management UI: nearby discovery, pair QR/short code, project sharing grants, revoke/rename. +- Network firewall/platform capability tests; no inbound connectivity requirement for Android v1. + +**Exit gate:** two real devices pair once, reconnect on the same Wi-Fi, sync a new/moved/edited/deleted document and an imported image; untrusted LAN devices cannot list projects; offline interrupted transfer resumes; AI pairing still works. + +### Phase 5 — Google OAuth + Drive transport (MnemoDrive) + +**Build:** +- Google Cloud project, consent, scope `drive.appdata`, desktop/Android/web OAuth clients, app domain verification and privacy policy as required by Google; external public-app verification testing. +- Secure native token persistence (Windows credential store, Android secure storage), ephemeral web access token/reauthorization UI. +- Cross-platform proof: all three clients read/write the **same** appData account namespace; explicitly test separate OAuth client IDs. +- `DriveTransport` with flat logical naming, appProperties/manifest indexes, immutable batches, blobs, initial list and changes cursor, resumable upload for larger assets, retry/backoff and dedupe. +- Account mismatch and Drive removal handling. Drive usage telemetry with local/privacy-safe counters, upload batching and user-controllable network policy. + +**Exit gate:** independently launched desktop, Android and web load the same remote project (after the same Google account grants permission), offline edits safely catch up; duplicate retries do not duplicate chapters; expired web auth gives an explicit prompt rather than losing queued changes. + +### Phase 6 — Hybrid fan-out and reconciliation + +**Build:** +- A transport coordinator: publish once per enabled transport, track independent delivery receipts, pull from both, dedupe global ops, merge revision heads consistently. +- Auto-prefer LAN for available peer transfers while Drive remains asynchronously updated when enabled; force Drive-only if LAN not reachable; respect per-project `local | LAN | Drive | hybrid` setting. +- Device catalog/account mapping, source-project alias handling, history compaction safety, multi-device conflicts. +- Reconcile when switching modes (LAN-only -> hybrid, Drive-only -> hybrid, project linked with pre-existing Drive data). + +**Exit gate:** desktop <-> Android LAN sync then web through Drive sees precisely one copy of each document; 3-device concurrent operations converge without duplicates; account switch does not mix data. + +### Phase 7 — UX, recovery, and browser LAN feasibility + +**Build:** +- Welcome/project list `Local / Pending / Synced / Conflict`, Sync Settings and per-project destinations, pending-count and last-sync timestamps. +- Smart Merge Wizard screenshots/previews and confirmations; `Recover previous version`, `Keep both`, `Fix broken asset` and `Restore backup` actions. +- On web, optional Chromium-oriented local desktop connection proof of concept: known host/QR + user gesture + HTTPS origin + CORS + Local Network Access permissions; test mixed-content/WebSocket behavior on supported browser versions. Ship browser LAN only if threat model and compatibility tests pass; otherwise explicitly label experimental and keep Drive default. +- User-facing explanations for same-account, no internet, auth expiry, quota, local network isolation and Android background constraints. + +**Exit gate:** a writer can link two existing projects safely without developer tools, can recover any conflict, and can tell what remains pending on each transport. + +### Phase 8 — Security, fault testing, performance and rollout + +**Build:** +- Threat tests: unauthorized peer, revoked device, replay, malformed payload, path traversal, oversized assets/ZIP bombs, malicious HTML/XSS, tokens in logs, account switch, LAN network-origin abuse. +- Fault injection: crash after file write/before queue, crash after blob upload/before batch, 409-style concurrent heads, Drive 401/403/429/5xx, power/network loss, disk full, Android killed, stale Drive cursor, deleted cloud app data. +- Multi-replica randomized property tests (event reorder/duplication, arbitrary offline durations), real hardware soak tests, upgrade/downgrade migration tests; keep existing Claude/Codex/AI tests passing. +- Incremental quota dashboard and diagnostic logs with content redaction; private beta, canary release, backup-required first sync, explicit rollback instructions. + +**Exit gate:** no known data-loss path in test corpus, safe disable/re-enable and restore, no cross-project data disclosure, reliability metrics acceptable in beta. + +### Phase 9 — Post-MVP optional evolution + +- Opt-in AI session synchronization (without syncing API secrets, login sessions or other tokens). +- Better metadata/graph conflict operations, then safe three-way text merge when bases are known; evaluate Yjs/TipTap collaboration for actual simultaneous editing only after baseline sync is stable. +- Efficient snapshot pruning/garbage collection with durable per-device acknowledgments and conservative offline retention. +- Visible Google Drive backup/export provider, recovery codes/export archive; potential user-controlled end-to-end encrypted Drive sync as an explicitly separate project. +- Better cross-browser LAN, optional Apple/iOS client, peer-to-peer relay through user-owned infrastructure if demand exists. + +### Proposed release grouping + +| Proposed version | Scope | +|---|---| +| `2.2.0` beta | Phases 0–4: safe local persistence, Smart Merge, native LAN sync | +| `2.2.x` | Phase 5: Google Drive provider and web sync, only after OAuth validation | +| `2.3.0` | Phase 6 hybrid experience + Phase 7 UX + Phase 8 hardened public release | +| Later | Phase 9 (collaboration, session sync, optional E2EE) | + +**Alternative:** ship all Phases 0–8 as a single `2.2.0` if one-version delivery is a product constraint. Do not bypass security/data-loss gates to meet a release number. + +--- + +## 9. Suggested concrete code layout + +```text +app/src/lib/sync/ + types.ts # cross-platform protocol/schema + engine.ts # causal reconciliation, apply decisions + merge/ + candidates.ts + matcher.ts + folderMapping.ts + preview.ts + decisions.ts + transports/ + SyncTransport.ts + DriveTransport.ts + LanClient.ts + storage/ + WebProjectStore.ts # IndexedDB + NativeProjectStore.ts + assets.ts # portable URI resolver + useSyncStatus.ts + +app/src/components/sync/ + SyncSettings.tsx + SyncStatus.tsx + PairDeviceWizard.tsx + MergeProjectsWizard.tsx + ConflictReview.tsx + RecoveryPanel.tsx + +app/src-tauri/src/sync/ + mod.rs + commands.rs + database.rs # SQLite queue/revisions/index + journal.rs + manifest.rs + lan/ + discovery.rs + pairing.rs + server.rs + client.rs + crypto.rs + drive/ + auth.rs + transport.rs + +docs/ + MNEMOSYNC_ARCHITECTURE.md + MNEMOSYNC_THREAT_MODEL.md + MNEMOSYNC_TEST_MATRIX.md + MNEMOSYNC_MIGRATIONS.md +``` + +Use `src/lib/api.ts` as the public frontend command boundary and register new commands in `src-tauri/src/lib.rs`. Avoid replacing native project files wholesale with SQLite; SQLite is for **sync state and transactions**, while existing project JSON stays readable and backup-friendly. + +--- + +## 10. Test plan / acceptance matrix + +| Test scenario | Expected outcome | +|---|---| +| Desktop Volume 1 + Android root; both created independently | Wizard discovers potential duplicate; canonical Volume 1; no lost docs | +| Chapter 3 edited both sides with no shared base | Two versions preserved; manual conflict choice | +| Chapter 4 exists on phone only | Imported into selected Volume 1 folder | +| Identical chapter with different IDs | One logical document after confirmed mapping; alias retained | +| Same title, unrelated content | Not auto-deduplicated | +| Different folder trees | Preferred hierarchy adopted, content independent | +| Same chapter moved on desktop, edited on phone | Merge placement and text without losing either | +| Delete while remote device offline | Tombstone survives; offline stale replica cannot resurrect by default | +| Device paired on public LAN | Unauthorized device sees no project metadata | +| Same op arrives via LAN and Drive | Applied once | +| Drive enabled, PC off, Android changes | Web downloads once signed into same Drive account | +| Drive auth expires on web | Re-auth UI; queued changes remain local | +| Google account A vs B | Separate namespaces; explicit warning, no cross-upload | +| App killed during save/queue | Recovery journal reconstructs missing outbox entry | +| App killed during merge | Staging resumes or rolls back; originals intact | +| Partial image transfer | Hash mismatch prevents reference from being published | +| AI Auto edit, undo, and remote conflict | Both edits captured as local changes; remote state preserved | +| Mind/fantasy map with images | Graph remains valid; all assets load on each platform | +| Android background suspension | Pending local changes preserved until next successful foreground sync | +| Browser unsupported local network API | Drive works; LAN feature gracefully unavailable | +| Drive app data deleted | Local copies stay; app asks before reinitializing remote namespace | +| Existing imported custom-path desktop project | Local registry path retained; remote snapshots path-free | + +Testing commands consistent with branch `AGENTS.md`: + +```bash +cd app +npm install --legacy-peer-deps +npm run check +cd src-tauri +cargo check +cargo test +cargo clippy -- -D warnings +``` + +Add targeted Vitest property/regression tests for merge and sync; Rust tests for codec/crypto/peer protocol; actual Windows + Android Wi-Fi tests; browser compatibility matrix and Google OAuth test accounts. Never claim real hardware behavior is verified based only on loopback tests. + +--- + +## 11. Cost controls and policy + +- No persistent MnemoScript-managed compute required. Static web hosting may use a free tier but is not a guarantee of zero cost. +- Drive files occupy **the user's Drive quota**. All ordinary app-owned data stays in their account; do not introduce a service account as the universal file owner. +- API traffic uses the MnemoScript Google Cloud project quota. Request units for list calls are costly; prefer a single change feed cursor per account/space and sparse polling. Follow Google quota/backoff guidance; provide a local setting such as `Sync on Wi-Fi only` and explicit `Sync now`. +- Batch small edits rather than one remote file per keystroke; uploads only verified changed blobs; compress payloads when beneficial; set client file-count, bandwidth, and retention budgets; do not silently prune unacknowledged history. +- Google OAuth verification (privacy policy, verification domains, test users, screenshots, potential security assessment depending on scopes) can create administrative work even without server costs. +- Default project content cloud sync is **not end-to-end encrypted** merely because OAuth and HTTPS are used. Explain this plainly to writers. A future E2EE setting requires cross-device key recovery, conflict-aware encryption, and robust key-loss handling. + +--- + +## 12. Open decisions to record as ADRs (defaults selected for planning) + +| Question | Proposed decision | +|---|---| +| Must users sign in to write? | **No**, all projects start local-first | +| Which Drive area? | **appDataFolder** for sync; visible folder only for explicit backup/export | +| Is Drive always the master? | **No**, it is one storage/transport; revision ancestry drives merge | +| Can users pair automatically on Wi-Fi? | Auto-**discover**, one-time explicit **trust** and per-project access, then auto-reconnect | +| Does web need LAN at launch? | **No**, Drive first; optional browser LAN experimental later | +| Which device is primary forever? | **Neither**, canonical ID/layout chosen once; thereafter multi-writer | +| How to reconcile Volume 1 vs root? | Match chapters separately from folder placement; default desktop hierarchy | +| What if content conflicts? | Preserve both, show preview; never last-write-wins | +| Do AI sessions sync immediately? | **No**, opt-in follow-on; secrets never sync | +| Does sync automatically erase originals? | **No**, staging/backup first and explicit later cleanup | +| Do native project files switch to DB only? | **No**, keep JSON as data source; add separate transactional sync state | +| Is Drive also backup? | Sync redundancy **is not** sufficient backup; separate export/restore path | + +--- + +## 13. Source references + +**Repository:** +- [PR #1 — merged work pending](https://github.com/ehitimum/MnemoScript/pull/1) +- [Feature branch](https://github.com/ehitimum/MnemoScript/tree/feature/ai-assistant) +- [Project persistence](https://github.com/ehitimum/MnemoScript/blob/feature/ai-assistant/app/src-tauri/src/project.rs) +- [AI pairing server](https://github.com/ehitimum/MnemoScript/blob/feature/ai-assistant/app/src-tauri/src/ai/pair_server.rs) +- [AI pairing crypto](https://github.com/ehitimum/MnemoScript/blob/feature/ai-assistant/app/src-tauri/src/ai/pair_crypto.rs) +- [Web/local API](https://github.com/ehitimum/MnemoScript/blob/feature/ai-assistant/app/src/lib/api.ts) +- [Architecture](https://github.com/ehitimum/MnemoScript/blob/feature/ai-assistant/docs/ARCHITECTURE.md) + +**Official external guidance (consult before implementation, as rules and APIs evolve):** +- [Google Drive appDataFolder](https://developers.google.com/workspace/drive/api/guides/appdata) +- [Drive API scopes](https://developers.google.com/workspace/drive/api/guides/api-specific-auth) +- [Drive change feed](https://developers.google.com/workspace/drive/api/guides/manage-changes) +- [Drive API usage limits and pricing](https://developers.google.com/workspace/drive/api/guides/limits) +- [Drive resumable uploads](https://developers.google.com/workspace/drive/api/guides/manage-uploads) +- [Google Identity Services browser token model](https://developers.google.com/identity/oauth2/web/guides/use-token-model) +- [Chrome Local Network Access](https://developer.chrome.com/docs/modern-web-guidance/guides/security/local-network-access) + +**Note:** This is a proposal rooted in inspected source and official documentation, not a claim that sync is already implemented or that Google OAuth, network pairing, or platform flows were tested on real devices. Recheck branch, API behavior, security and quotas during implementation. From 6ab8a3ec33391bc57e96b11e0a52dde5df6a5716 Mon Sep 17 00:00:00 2001 From: ehitimum Date: Sun, 15 Nov 2026 16:16:50 +0600 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20PR=20#2=20review=20=E2=80=94=20Node?= =?UTF-8?q?=20engines=20range,=20runtime=20guard,=20notes=20header?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - engines.node widened to ^22.22.2 || ^24.15.0 || >=26 (what locked jsdom and undici accept; the suite passes on Node 22.23). CI keeps 24.15.0. - The runtime regression could never fail the way it described (Vitest dies before collecting on Node 20); it now asserts the running Node satisfies engines.node and that the range refuses Node 20. - docs/mnemosync/MEMORY.md says at the top that it is kept as working notes. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- app/package-lock.json | 2 +- app/package.json | 2 +- app/src/regression/runtime.regression.test.ts | 50 ++++++++++--------- docs/TESTING.md | 5 +- docs/mnemosync/MEMORY.md | 4 ++ 6 files changed, 37 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 3fa71d5..288e7f8 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Map studio: [docs/FANTASYMAP.md](docs/FANTASYMAP.md) · Android: [docs/ANDROID.m ## Getting started -Prerequisites: Node.js 24.15+ (24.x, pinned in `.node-version`), Rust (stable), and on Windows the MSVC build tools. +Prerequisites: Node.js 22.22+ or 24.15+ (CI uses the 24.15.0 pinned in `.node-version`), Rust (stable), and on Windows the MSVC build tools. ```bash cd app diff --git a/app/package-lock.json b/app/package-lock.json index 706742f..e76c44c 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -8,7 +8,7 @@ "name": "app", "version": "0.0.0", "engines": { - "node": "^24.15.0" + "node": "^22.22.2 || ^24.15.0 || >=26" }, "dependencies": { "@dagrejs/dagre": "^3.0.0", diff --git a/app/package.json b/app/package.json index ed3a7c9..9f79a70 100644 --- a/app/package.json +++ b/app/package.json @@ -4,7 +4,7 @@ "version": "2.1.1", "type": "module", "engines": { - "node": "^24.15.0" + "node": "^22.22.2 || ^24.15.0 || >=26" }, "scripts": { "dev": "vite", diff --git a/app/src/regression/runtime.regression.test.ts b/app/src/regression/runtime.regression.test.ts index 6b5abcd..b1f4f3b 100644 --- a/app/src/regression/runtime.regression.test.ts +++ b/app/src/regression/runtime.regression.test.ts @@ -1,26 +1,30 @@ -import { createRequire } from 'node:module'; -import { Worker } from 'node:worker_threads'; +import { readFileSync } from 'node:fs'; import { expect, it } from 'vitest'; -it('starts the pinned jsdom dependency in a fresh Node worker (CI runtime regression)', async () => { - // CI on Node 20 failed before collecting any tests: undici's CacheStorage needs newer - // runtime APIs. Exercise a clean process context rather than Vitest's already loaded DOM. - const jsdomPath = createRequire(import.meta.url).resolve('jsdom'); - const worker = new Worker(` - const { parentPort, workerData } = require('node:worker_threads'); - const { JSDOM } = require(workerData); - const dom = new JSDOM('

বাংলা manuscript

'); - parentPort.postMessage(dom.window.document.querySelector('[data-doc-id="chapter-1"]').textContent); - dom.window.close(); - `, { eval: true, workerData: jsdomPath }); - try { - const content = await new Promise((resolve, reject) => { - worker.once('message', resolve); - worker.once('error', reject); - worker.once('exit', (code) => { if (code !== 0) reject(new Error(`DOM worker exited: ${code}`)); }); - }); - expect(content).toBe('বাংলা manuscript'); - } finally { - await worker.terminate(); - } +/** + * Node runtime guard (PR #2 review). On Node 20, Vitest itself fails before collecting any test + * (locked jsdom/undici need newer APIs), so a test cannot report that case; `.node-version` and + * `engines` are the real guard. This states the intent: the Node running the suite satisfies the + * declared `engines.node` range (the same range locked jsdom accepts). + */ +function satisfies(version: string, range: string): boolean { + const [maj, min, pat] = version.replace(/^v/, '').split('.').map(Number); + const cmp = (a: number[], b: number[]) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; + return range.split('||').some((part) => { + const m = part.trim().match(/^(\^|>=)(\d+)(?:\.(\d+))?(?:\.(\d+))?$/); + if (!m) throw new Error(`Unsupported range part: ${part}`); + const want = [Number(m[2]), Number(m[3] ?? 0), Number(m[4] ?? 0)]; + const have = [maj, min, pat]; + if (cmp(have, want) < 0) return false; + return m[1] === '>=' || have[0] === want[0]; + }); +} + +it('runs on a Node version inside the declared engines range', () => { + const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { engines: { node: string } }; + expect(satisfies(process.versions.node, pkg.engines.node)).toBe(true); + // The range keeps Node 22.22+ working (jsdom accepts it) and still refuses Node 20. + expect(satisfies('22.23.0', pkg.engines.node)).toBe(true); + expect(satisfies('20.19.0', pkg.engines.node)).toBe(false); + expect(satisfies('24.14.0', pkg.engines.node)).toBe(false); }); diff --git a/docs/TESTING.md b/docs/TESTING.md index e1705eb..dc6a83b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,8 +1,9 @@ # Testing MnemoScript -Use Node 24.15.0 from the root `.node-version` (supported range: 24.15+ in 24.x). Both CI and +Use Node 24.15.0 from the root `.node-version` (supported: `^22.22.2 || ^24.15.0 || >=26`). Both CI and release workflows read this file. Locked jsdom 30/undici 8 cannot start under the former Node 20 -CI runtime. `regression/runtime.regression.test.ts` exercises jsdom in a fresh Node worker. +CI runtime. `regression/runtime.regression.test.ts` checks the running Node satisfies `engines.node` +(`^22.22.2 || ^24.15.0 || >=26`, the range locked jsdom accepts). `regression/ai-history.regression.test.ts` fixes the clock to verify fast AI responses cannot merge undo history with preceding or following typing (word rewrite, structural rewrite, continue). diff --git a/docs/mnemosync/MEMORY.md b/docs/mnemosync/MEMORY.md index f527c67..453fa3e 100644 --- a/docs/mnemosync/MEMORY.md +++ b/docs/mnemosync/MEMORY.md @@ -1,5 +1,9 @@ # MnemoSync Project Memory (Development Handoff) +> **Kept in the repository on purpose:** these are the MnemoSync working notes (decisions, gates, +> open questions) for whoever continues this work. They are not end-user documentation; the +> design itself lives in `docs/MNEMOSYNC_*.md`. + > **Scope:** This is a project-specific handoff note for MnemoScript developers and coding assistants. It is **not** a dump of ChatGPT's private memory, hidden reasoning, credentials, or user profile. Update it alongside implementation. ## Goal From 88a04deaee3ea29f86600fde87d14b95e1c81d2a Mon Sep 17 00:00:00 2001 From: ehitimum Date: Sun, 15 Nov 2026 16:37:44 +0600 Subject: [PATCH 3/3] test: read package.json by path in the engines check import.meta.url is not a file URL under jsdom. Co-Authored-By: Claude Opus 5.5 --- app/src/regression/runtime.regression.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/regression/runtime.regression.test.ts b/app/src/regression/runtime.regression.test.ts index b1f4f3b..7e397f8 100644 --- a/app/src/regression/runtime.regression.test.ts +++ b/app/src/regression/runtime.regression.test.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import { expect, it } from 'vitest'; /** @@ -21,7 +22,7 @@ function satisfies(version: string, range: string): boolean { } it('runs on a Node version inside the declared engines range', () => { - const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { engines: { node: string } }; + const pkg = JSON.parse(readFileSync(resolve(__dirname, '../../package.json'), 'utf8')) as { engines: { node: string } }; expect(satisfies(process.versions.node, pkg.engines.node)).toBe(true); // The range keeps Node 22.22+ working (jsdom accepts it) and still refuses Node 20. expect(satisfies('22.23.0', pkg.engines.node)).toBe(true);