feat(persistence): bidirectional local/cloud story sync (Supabase)

Connect the previously-skeleton cloudStore to the client with a full
bidirectional reconcile engine. Commercial build (AUTH_ENABLED) only; the
open-source build is byte-for-byte unchanged — all cloud paths short-circuit
when AUTH_ENABLED is false.

- cloudSync.ts: reconcile engine — decideAction (pure, LWW rev->updatedAt with
  tombstone priority) + syncOnLogin/pushOnSave/pushDeletion (best-effort,
  serialized, isAuthed-gated)
- cloudSyncClient.ts: browser fetch bridge (short-circuit + fault-tolerant)
- /api/stories/{manifest,pull,push,delete}: RLS-guarded sync endpoints
- upsert_story_if_newer RPC: optimistic concurrency (SECURITY INVOKER,
  auth.uid() injection, rev->updated_at guard, revoked from public)
- cloudStore: +manifest/pullBlobs, save->RPC {stored,won}, softDelete w/ rev
- localStore: +listAllRecordsForSync/putSyncedRecord/markRecordSynced
  (concurrency-guarded sync writes); types: +StorySyncMeta/StorySyncEnvelope
- facade + UserChip: inject pushOnSave/pushDeletion + login-triggered reconcile

Sync model: full reconcile on login + background push on save (no Realtime;
eventual consistency). Conflict resolution: last-write-wins.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Kai ki
2026-06-28 11:20:47 +08:00
parent da74e3e763
commit ff12b2759f
12 changed files with 824 additions and 66 deletions
+31
View File
@@ -98,3 +98,34 @@ export type StoryRecord = {
* structured-clones objects, so this is stored as-is (no JSON.stringify). */
session: Session;
};
// ── Cloud-sync wire types (story-cloud-sync) ────────────────────────────────
/** Manifest projection of one cloud story — the lightweight metadata the
* reconcile engine diffs against the local set. Unlike `StoryMeta` it CARRIES
* the tombstone (`deletedAt`) and `rev`, because reconcile needs both to pick
* a winner (rev → updatedAt last-write-wins) and to propagate soft-deletes.
* Never carries the session blob — the manifest is the cheap diff basis. */
export type StorySyncMeta = {
id: string;
rev: number;
/** epoch ms */
updatedAt: number;
/** Soft-delete tombstone (epoch ms) or null. */
deletedAt: number | null;
};
/** Full-payload carrier for pull/push between the local store and the cloud.
* Extends the shared `SlimStoryBlob` with the two sync-ordering fields:
* - `updatedAt` is the CLIENT-recorded modification time (NOT a server
* `now()`), so when two devices collide on the same `rev`, `updatedAt`
* stays a meaningful last-write-wins tiebreaker rather than always-now.
* - `deletedAt` lets a tombstone ride the same envelope (delete propagation).
* `rev` is already on `SlimStoryBlob`, so the envelope = blob + (updatedAt,
* deletedAt). This is the single shape crossing the API at pull/push. */
export type StorySyncEnvelope = SlimStoryBlob & {
/** epoch ms */
updatedAt: number;
/** Soft-delete tombstone (epoch ms) or null. */
deletedAt: number | null;
};