Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
51 changes: 28 additions & 23 deletions app/src/regression/runtime.regression.test.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import { createRequire } from 'node:module';
import { Worker } from 'node:worker_threads';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
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('<p data-doc-id="chapter-1">বাংলা manuscript</p>');
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<string>((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(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);
expect(satisfies('20.19.0', pkg.engines.node)).toBe(false);
expect(satisfies('24.14.0', pkg.engines.node)).toBe(false);
});
8 changes: 8 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions docs/DEVLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/IMPROVEMENT_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
86 changes: 86 additions & 0 deletions docs/MNEMOSYNC_ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -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.
41 changes: 41 additions & 0 deletions docs/MNEMOSYNC_MIGRATIONS.md
Original file line number Diff line number Diff line change
@@ -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<string>` 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.
37 changes: 37 additions & 0 deletions docs/MNEMOSYNC_TEST_MATRIX.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading