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
34 changes: 34 additions & 0 deletions docs/cloud.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ and safe to re-run:
- `0006_projects_helpers_private.sql` — moves the `is_project_member` /
`has_project_role` RLS helpers into a non-API `private` schema so they are not
reachable as PostgREST RPCs (clears the database linter). Apply after `0005`.
- `0007_compaction.sql` — the `claim_compaction(project_id, expected_seq, state,
up_to_id)` RPC (SECURITY DEFINER, membership-checked): optimistically installs
a fresh compacted `ydoc_state` snapshot (guarded by the `seq` generation) and
prunes the subsumed `ydoc_updates` rows, so the append log stays bounded. Backs
Phase 4.3. Apply after `0006`. *(Numbering note: ROADMAP §4.3 sketched
`0005_compaction.sql`, but `0005`/`0006` were taken by the 4.1 project
migrations, so it ships as `0007`; and the RPC signature is widened from the
sketch's `(project_id, expected_seq)` to also carry the new snapshot + the
pruned-through id, so the whole compaction is one atomic, RLS-safe
transaction.)*

> Note: the linter's "Leaked Password Protection Disabled" warning is unrelated
> to these migrations — it's an optional **Authentication → Policies** toggle
Expand Down Expand Up @@ -224,3 +234,27 @@ LWW and tombstones. Apply `0004_personal_resources.sql` first.
**not** appear in `personal_tm`, and uninstalling on A doesn't touch B.
- [ ] **Local-only unaffected**: signed out, glossary/TM work exactly as before and
no `personal_glossary`/`personal_tm` request is made (no tombstones written).

## 10. Manual verification (Phase 4.3 — Postgres persistence loop)

The persistence loop (`src/storage/cloud/ydocPersistence.ts`) makes Postgres the
source of truth for a cloud project's Yjs doc: catch-up on open, debounced
appends of local edits to `ydoc_updates`, and optimistic compaction into
`ydoc_state` via `claim_compaction`. Realtime (§4.2) is only the low-latency
channel. Apply `0007_compaction.sql` first. Two signed-in members, each having
opened the same published cloud project:

- [ ] **Catch-up on open**: member B opens the project → the doc arrives from
Postgres (`ydoc_state` + `ydoc_updates`) even with Realtime idle.
- [ ] **Append**: member A edits → within ~½s a new `ydoc_updates` row appears,
`author_id = A`. B (reopened, or after a reconnect) sees the edit.
- [ ] **Offline convergence**: take B offline, edit on both A (online) and B
(offline), bring B back and reopen → both docs converge, no edit lost
(Yjs replay is idempotent).
- [ ] **Compaction bounds the log**: drive `ydoc_updates` past ~200 rows → a
client folds them into a new `ydoc_state` snapshot (its `seq` increments)
and the log shrinks. With two clients compacting at once, only one wins
(the `seq` guard) and the other no-ops — no lost updates.
- [ ] **Local-only unaffected**: a project with no `cloud` link makes no
`ydoc_state`/`ydoc_updates` request; the BroadcastChannel/LAN path is
unchanged.
5 changes: 3 additions & 2 deletions docs/revamp/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ Rules for autonomous sessions:
| 3.3.1 | Sidebar layout sync (deferred from 3.3) | S | 3.3 | done (PR #53) |
| 3.4 | Personal term bank + TM sync | M | 3.3 | done (PR #52) |
| 4.1 | Cloud project schema + RLS + publish/join | M | 3.1 | done (PR #55) |
| 4.2 | SupabaseRealtimeTransport + chunking | M | 4.1 | in-review (PR #56) |
| 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | pending |
| 4.2 | SupabaseRealtimeTransport + chunking | M | 4.1 | done (PR #56) |
| 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | in-review (PR #57) |
| 4.4 | Live collab UX: cursors, leases, attribution | M | 4.3, 1.6 | pending |
| 5.1 | Members & roles management | M | 4.1 | pending |
| 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | pending |
Expand Down Expand Up @@ -71,3 +71,4 @@ Rules for autonomous sessions:
- 2026-07-20 — Phase 3.4 merged in PR #52 (**Milestone 3 complete**). Phase 3.3.1 built: sidebar layout sync (the layout deferred from 3.3). `useSidebarPanelStore` gains a persisted LWW `updatedAt` stamped on every layout/collapsed mutation (`setTab`/`setLayout`/`showPanel`/`togglePanel`/`toggleCollapsed`/`movePanel`/`resetLayout`; transient open/active-tab never bump it) + `partialize`/`merge` carry it; `defaultLayout` exported for rehydration backfill. New `features/editor/layoutSync.ts` syncs the layout through the same `user_settings` cloud table under the `sidebar.layout` key with the same client-supplied LWW: `syncLayout(client, userId)` (pull-newer applies to the live store via `setState` — rehydrating machine B without a reload, backfilling any stage a stale remote misses — else push local-newer), plus `startLayoutSync()`/`stopLayoutSync()` wiring (reconcile once per new sign-in; debounced push on store change, guarded by an `applyingRemote` flag so a pull's `setState` never echoes back as a push). `main.tsx` starts it via a guarded **dynamic** import only when `isCloudConfigured()`. Deviation (noted in ROADMAP §4): the 3.3 `settingsSync` engine is bound to Dexie `settingsRepo` keys (not a source-agnostic adapter engine as the 3.3.1 note optimistically implied), so the layout — a zustand/localStorage store — syncs as a small **sibling** reconciler reusing `user_settings` + LWW rather than a settingsSync "adapter". No 3.3 code refactored (keeps that phase's tests untouched). `settingsSync` never sees the `sidebar.layout` row (its `.in()` query is scoped to `SYNCED_SETTINGS_KEYS`). Verified: flag-OFF `dist` has **zero** `GoTrueClient`/`syncLayout`/`user_settings` (layoutSync tree-shaken; the only `sidebar.layout` substring is the store's `verbalis.sidebar.layout` localStorage key — local code); flag-ON keeps `GoTrueClient` out of the entry and puts `layoutSync` in its own lazy chunk. Built on the designated session branch, not `claude/revamp-phase-3-3-1`. `docs/cloud.md` §8.1 verification. Tests: `layoutSync` (LWW: apply-newer-remote rehydrates the store, push-local-newer, push-when-no-remote-row, equal-noop), `layoutSync.wiring` (sign-in applies the cloud layout live; debounced push on a local layout change). Green: 608 unit (+6) / 27 e2e / build (flag-off layout-sync-free, flag-on lazy).
- 2026-07-20 — Phase 3.3.1 merged in PR #53. Phase 4.1 built: cloud project schema + RLS + publish/open (start of **Milestone 4**, real-time collaboration). Migrations applied to the live project via the Supabase MCP (advisor clean bar the unrelated leaked-password Auth toggle): `0005_projects.sql` — `projects`, `project_members(role project_role enum: project_manager|translator|revisor)`, `ydoc_state(state bytea, seq)`, append-only `ydoc_updates(update bytea, author_id default auth.uid())` (tamper-evident attribution, D8), member-scoped RLS via `is_project_member`/`has_project_role` helpers, a private `project-files` storage bucket. `0006_projects_helpers_private.sql` — moves the two SECURITY DEFINER membership helpers into a non-API `private` schema (repoints every 0005 policy) so they stop being RPC-exposed while RLS keeps calling them, clearing the linter's 0029 lints. Numbering deviation: ROADMAP §4.1 sketched `0004_projects.sql`, but `0003`/`0004` were taken by the 3.3/3.4 migrations, so this shipped as `0005` + a `0006` hardening follow-up. `src/core/types`: `ProjectRole` + additive `Project.cloud?: {id, role}` (unindexed; local-only projects never carry it). `src/storage/cloud/bytea.ts`: pure hex-literal encode/decode for bytea-over-PostgREST (base64 decode fallback). `src/storage/cloud/projectCloud.ts`: pure client-injected data layer (`insertCloudProject` seeds the project row + owner `project_manager` membership + `ydoc_state` snapshot; `listCloudProjects`; `fetchCloudProject` → summary+role; `fetchYdocState` → decoded bytes) + orchestration (`publishProject` encodes the project's live Yjs doc via `acquireProjectDoc`+`Y.encodeStateAsUpdate`, inserts, stamps `project.cloud`; `openCloudProject` fetches metadata+snapshot, hydrates a fresh local Dexie project + its segments via `readAllSegments`, reusing an existing local copy rather than duplicating). Strictly additive — `getSupabase()` dynamic, gated on `isCloudConfigured()`. UI (self-gating, cloud logic dynamically imported so the projects route stays lean): `features/projects/cloud/CloudControls.tsx` (`CloudBadge`, owner `PublishCloudButton` on a card, `OpenFromCloudButton` header action — all render null unless configured + signed-in) + `OpenCloudProjectDialog.tsx` (lists member projects, opens → navigates to the local copy); wired into `ProjectCard` + projects `index.tsx`. Verified: flag-OFF `dist` has **zero** `GoTrueClient`; flag-ON keeps Supabase in a lazy chunk out of the entry. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-1`; the two-account publish→open→RLS-deny round-trip is the manual DoD (needs two real sessions; vitest uses an injected mock client). Tests: `cloud.bytea` (hex round-trip incl. all 256 byte values + empty + base64 fallback), `cloud.projectCloud` (insert creates all three rows with the owner as project_manager and a decodable snapshot; list camelCase mapping; fetch summary+role incl. translator default + null-when-absent; error propagation — all via an in-memory client mirroring the PostgREST chains). Green: 618 unit (+10) / 27 e2e twice / build (flag-off Supabase-free, flag-on lazy); no new e2e (ROADMAP §4 asks none for 4.1).
- 2026-07-20 — Phase 4.1 merged in PR #55. Phase 4.2 built: `SupabaseRealtimeTransport` + chunking (pure client, no schema change). `src/storage/sync/transport/chunking.ts` — the protocol core: base64 wire encoding (`bytesToBase64`/`base64ToBytes`), `encodeMessage(SyncMessage, limit=60000)` frames a message into `WireChunk`s (Realtime is JSON + ~250KB/msg, so binary payloads are base64 +33% and split), and an order-independent `ChunkReassembler` that yields a `SyncMessage` once all chunks of a message id arrive (single-chunk pass-through; payloadless kinds `hello`/`bye`/`state-request` carry `d:''`). `src/storage/sync/transport/supabaseRealtime.ts` — `SupabaseRealtimeTransport implements SyncTransport` over a private Realtime broadcast channel `project:{cloudId}` (`broadcast:{self:false}`, so no self-echo, matching BroadcastChannel); `getSupabase()` is dynamic so no eager supabase-js. Outbound `update`s are coalesced by `OutboundUpdateBatcher` (debounce 300ms → `Y.mergeUpdates` → one broadcast); other kinds send immediately; sends before `SUBSCRIBED` buffer in an outbox flushed on subscribe. The channel is injectable (`channelProvider`) as a test seam. `createTransport(projectId, {cloudId?})` gains a cloud branch (Supabase when `cloudId` set; **BroadcastChannel/Tauri paths byte-identical otherwise**); `syncManager.startProjectSync` computes `cloudId` from `project.cloud` when signed-in + `isCloudConfigured()`, else `undefined`. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-2`; the transport is complete + unit-covered now, but the end-to-end **two-browser live edit** DoD needs the Postgres initial-state loop (4.3) + the auto-start-on-open UI (4.4) — the transport is selectable but not yet auto-wired for cloud projects (that's 4.4), stated honestly. No migration (4.2 is transport-only). Tests: `sync.chunking` (base64 all-bytes/empty round-trip; single + multi-chunk encode/reassemble; out-of-order arrival; two interleaved messages stay separate; payloadless pass-through), `sync.realtimeTransport` (`OutboundUpdateBatcher` merges a burst into one flush that replays both edits via fake timers + no-fire-after-destroy; transport delivers a 50KB multi-chunk `state` to the *other* peer only via a linked in-memory channel pair — caught + fixed a real ordering bug where the outbox flushed before `this.channel` was assigned; pre-subscribe sends buffer then flush). Green: 629 unit (+11) / 27 e2e twice / build (flag-off has zero `GoTrueClient`; flag-on keeps Supabase a lazy chunk out of the entry).
- 2026-07-20 — Phase 4.2 merged in PR #56 (STATUS was stale — recorded here). Phase 4.3 built: the Postgres persistence loop (Realtime is latency, Postgres is truth). `supabase/migrations/0007_compaction.sql` — the `claim_compaction(project_id, expected_seq, state, up_to_id)` RPC (SECURITY DEFINER, membership-checked): atomically bumps the `ydoc_state.seq` generation **only while it still matches** `expected_seq`, installs the new compacted snapshot, and prunes `ydoc_updates` with `id <= up_to_id`. Numbering deviation: ROADMAP §4.3 sketched `0005_compaction.sql`, but `0005`/`0006` were taken by the 4.1 project migrations, so it ships as `0007`; and the RPC signature is **widened** from the sketch's `(project_id, expected_seq)` to also carry the new snapshot + pruned-through id, so the whole compaction is one atomic RLS-safe transaction (the append log has no DELETE policy by design — D8 tamper-evidence — so pruning goes through this controlled definer path, membership re-checked inside). `src/storage/cloud/ydocPersistence.ts` — pure client-injected data layer (`fetchSnapshot`/`fetchUpdates`/`appendUpdate`/`countUpdates`/`claimCompaction`, hex-bytea via 4.1's `bytea.ts`) + the `createYdocPersistence({cloudId, doc, client})` loop: **catch-up** fetches `ydoc_state` + the whole `ydoc_updates` log, merges (`Y.mergeUpdates`) and applies as `ORIGIN_REMOTE` (so neither the transport nor this loop re-broadcasts/re-appends it), then pushes anything the local doc holds that the cloud lacks (offline edits / pre-publish history) by diffing state vectors (`Y.encodeStateAsUpdate(doc, remoteSV)` when `localAheadOf`); **append** buffers local `doc.on('update')` deltas (ignoring `ORIGIN_REMOTE`), debounce-merges them (500ms) into one attributed `ydoc_updates` row, and re-buffers/retries on a failed (offline) append; **compaction** triggers once the log passes 200 rows — it re-reads the *authoritative* snapshot+updates from Postgres (never the possibly-lagging local doc) to build the new snapshot, so it subsumes exactly the rows it prunes, then optimistically `claim_compaction`s (loser gets `null` and no-ops — the log is already bounded). Catch-up is re-runnable (idempotent Yjs replay), which is what converges an offline member on reconnect. Wiring: `syncManager.startProjectSync` starts the loop (dynamic `startYdocPersistence`, only when `cloudId` set + signed-in + `isCloudConfigured()`) alongside the realtime transport, kicks off a non-blocking `catchUp()`, stores the handle on the ref-counted session, and destroys it in `stopProjectSync`; local-only projects never touch it. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-3`; the RPC signature widening above; live **reconnect re-sync** (re-`hello`/re-`catchUp` when Realtime drops-then-resubscribes) is left to 4.4, which owns the transport/auto-start UX — 4.3 converges on **reopen** (each open runs catch-up), the DoD proven at the persistence layer. `docs/cloud.md` (§3 migration list + §10 manual verification). Tests: `cloud.ydocPersistence` (catch-up converges a fresh doc from snapshot+log; append coalesces a burst into one row; applied-remote is never re-appended; **offline-A/online-B converge through Postgres with no edit lost** — the DoD, on a shared in-memory server; compaction folds+prunes past the threshold and bumps seq, and a stale optimistic claim returns `null`; `fetchSnapshot`/`fetchUpdates` bytea round-trips). Green: 636 unit (+7) / build (flag-off: **zero** `GoTrueClient`/`claim_compaction` — the loop tree-shakes out entirely when the cloud is unconfigured; flag-on: `GoTrueClient` and the persistence loop each in their own lazy chunk, out of the entry). No new e2e (ROADMAP §4 asks none for 4.3; the two-member live DoD needs a real backend, per the §10 manual matrix).
Loading
Loading