Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: saves stamp collab.sync, so a saved copy rejoins its live session as a fork (#594)
nyblnetd952ddc444b4
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex ea9b959e..00544b46 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7442,6 +7442,53 @@ rigs treat a drawn arrow as a deliberate difference: named in`test-maths-lite.ts`, counted with the identical ones in the coverage floor.Cost: +966 B of shell.+## 2026-10-04 — bento/spaces saves stamp `collab.sync`; which writes carry it++Slides has always stamped the session's CRDT state into `doc.collab.sync` on+save, so an offline-edited copy rejoins as a true fork (docs/collab-design.md).+Spaces had the restore side (it uses the kernel session, whose `attach()`+restores a `SYNC_V` stamp) but stamped only the invite copy. Measured, with the+stamp removed: a reopened copy is a fresh adopt — its offline edits are already+in the shadow, so no op is minted for them and peers never receive them (the+two copies stay different), and an offline edit to a block a peer also changed+is overwritten by the peer's replay.++One function decides it, `spaces/src/share.ts stampSync(store, session)`,+called at the moment the document is taken for a write. Per path:++- **⌘S, Save a copy, Update this file, Download updated copy, the invite** —+ stamp the CURRENT state. All four write this replica.+- **View-only copy** — no state (`readerCopy` clears `sync`), as slides: a+ viewer rejoining as a fork of itself is a fork nobody can merge back.+- **Page extract, Copy document JSON, Markdown** — no `collab` at all.+- **Duplicate as a new space** — `duplicateAsNew`: fresh `docId`, no `collab`,+ so no `sync`; it never meets its ancestor's channel or room.+- **Encrypted** — the stamp is part of the doc JSON, so it is inside the+ envelope like everything else (`serializeAuto`).+- **A store opened read-only never stamps** (frozen, reader copy, reading+ copy). A frozen file may carry a `sync` of a SYNC_V this build cannot read,+ and the format promises an unknown field survives a round trip untouched.++**Older builds.** A build without this change opens a stamped file, restores+from it (the restore side shipped with spaces' sync in #320), and writes it+back byte-identical on ⌘S — checked in Chrome against the pre-change shell. It+does not re-stamp, so an edit it saves is not in the stamp. Measured: on+rejoin, a new block still reaches peers, but a changed paragraph does not —+the two copies disagree on it (same mechanism as the 2026-09-17 lean-stamp+entry: a text generation the stamp does not carry). The same is true of an+edit written into `#bento-doc` from outside the app, which is why+docs/spaces-agents.md now says to edit a shared space through `window.bento`.+Shipped builds already produced such files (they stamped the invite copy).++**Cost.** The stamp is the full text history (lean stamping is refused,+2026-09-17). Measured: 400 word-sized edits to one paragraph, 1.8 KB of text,+stamp 57 KB. Slides accepts this; prose makes it grow faster. Dash caps its+stamp at 2 MB and drops it past that; spaces does not cap today.++**After the save queue (#580).** The stamp moves from `doSave` into the+queue's `prepare`, immediately before the detached snapshot is copied, so the+stamp describes exactly the revision that is written. The self-update in place+goes through the same queue there, so its `onBeforeWrite` stamp moves with it.## 2026-10-04 — Spaces: undo, redo and every whole-document restore keep the live identity (`FROM_LIVE`)`spaces/src/store.ts` exports `FROM_LIVE = ['docId', 'collab', 'readonly',diff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex 04e44a3a..6ebcdb0f 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -596,5 +596,9 @@ rather than vanishing quietly at save time.— the file round-trips byte-exact and edits are refused.- A remote image `src` shows a placeholder until the reader asks for it. Embedthe bytes as an `asset:` instead — see **Images** above.-- There is no collaboration yet. Two people editing two copies get two files- and no merge.+- A shared space (its `collab` names a room) syncs between open copies, and a+ saved copy carries its sync state in `collab.sync` so it can rejoin the+ session later as a fork. Leave `collab` alone. An edit written into+ `#bento-doc` from outside the app is not in that state, so it is not reliably+ carried to the other copies when the file next joins — edit a shared space+ through `window.bento` in the open file instead.diff --git a/scripts/test-sync-spaces-session.ts b/scripts/test-sync-spaces-session.tsindex d84519b6..20b0c4f5 100644--- a/scripts/test-sync-spaces-session.ts+++ b/scripts/test-sync-spaces-session.ts@@ -291,6 +291,238 @@ H('end to end: two tabs of one space converge')sa.close?.(); sb.close?.()}+// ---------------------------------------------------------------------------+// A SAVED FILE REJOINS AS A FORK.+//+// Slides stamps `doc.collab.sync` (the session's CRDT state) into every save of+// a shared deck; spaces did not, so an offline-edited copy of a shared space+// reopened as a FRESH ADOPT. Its offline edits were already in the document it+// adopted — the shadow — so no op was ever minted for them and no peer ever+// received them. Everything below drives the code ⌘S runs: share.ts stampSync+// at the moment the document is taken, then the file's JSON through parseDoc,+// a new Store and a new SyncSession, which is exactly what boot() does with a+// file. Each phase is a REAL tab on a REAL BroadcastChannel; "offline" closes+// that tab's transports while its session keeps diffing, which is what a lost+// connection looks like to the session.+const { stampSync, duplicateAsNew } = await import('../spaces/src/share.ts')+const { parseDoc } = await import('../spaces/src/model.ts')+type AnySession = InstanceType<typeof SyncSession>+const priv = (s: AnySession) => s as unknown as {+ transports: Array<{ close(): void }>+ heartbeat: ReturnType<typeof setInterval> | null+ state: { lamport: number; vv: Record<string, number> }+ forkPending: boolean+}+/** the connection drops; the session keeps diffing local edits */+function goOffline(s: AnySession): void {+ for (const tr of priv(s).transports) tr.close()+ priv(s).transports = []+}+/** the tab is closed */+function closeTab(s: AnySession): void {+ goOffline(s)+ if (priv(s).heartbeat) clearInterval(priv(s).heartbeat!)+}+/** ⌘S: stamp, then the bytes that reach the file (the doc JSON) */+function save(store: AnyStore, session: AnySession): string {+ stampSync(store, session)+ return JSON.stringify(store.doc)+}+/** open a saved file in a new tab, as boot() does */+function reopen(file: string): { store: AnyStore; session: AnySession } {+ const r = parseDoc(file)+ if (!r.ok) throw new Error('saved file did not parse')+ const store = new Store(r.doc)+ return { store, session: new SyncSession(store) }+}+const html = (s: AnyStore, id: string) => s.block(id)?.html+const pagesKey = (s: AnyStore) => JSON.stringify(s.doc.pages)++H('a saved file rejoins as a fork: A edits offline, B edits meanwhile, both survive')+{+ const a = space('fork'), b = space('fork')+ const sa = new SyncSession(a), sb = new SyncSession(b)+ await settle()+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'shared', type: 'p', html: 'written live' }) }, { structure: true })+ await settle()+ ok(html(b, 'shared') === 'written live', 'live: A’s block reached B before anyone went offline')++ // A saves while live — the stamp is the CURRENT state, and only shared+ // documents carry it+ const first = save(a, sa)+ const stamped = JSON.parse(first).collab?.sync+ ok(!!stamped && stamped.v === 2 && stamped.lamport > 0,+ `⌘S stamps collab.sync (v=${stamped?.v}, lamport=${stamped?.lamport})`)++ // A drops offline, edits, saves, closes+ goOffline(sa)+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'off-a', type: 'p', html: 'written offline in A' }) }, { structure: true })+ a.commit(() => { a.doc.pages[1].title = 'Renamed offline in A' })+ await settle()+ const file = save(a, sa)+ closeTab(sa)+ ok((JSON.parse(file).collab?.sync?.lamport ?? 0) > (stamped?.lamport ?? 0),+ 'the offline save stamps the NEWER state — the one that knows about the offline edits')++ // meanwhile B keeps working+ b.commit(() => { b.doc.pages[0].blocks.push({ id: 'on-b', type: 'p', html: 'written by B meanwhile' }) }, { structure: true })+ b.commit(() => { b.doc.pages[2].title = 'Renamed by B meanwhile' })+ await settle()+ ok(!b.block('off-a'), 'while A is away B has not seen its edit (the partition is real)')++ // A reopens the saved file and rejoins+ const { store: a2, session: sa2 } = reopen(file)+ ok(priv(sa2).forkPending === true && priv(sa2).state.lamport > 0,+ 'the reopened file restored its CRDT state (a fork, not a fresh adopt)')+ await settle(600)++ ok(html(b, 'off-a') === 'written offline in A', 'B received A’s offline block')+ ok(b.doc.pages[1].title === 'Renamed offline in A', 'B received A’s offline rename')+ ok(html(a2, 'on-b') === 'written by B meanwhile', 'A received B’s block from the time it was away')+ ok(a2.doc.pages[2].title === 'Renamed by B meanwhile', 'A received B’s rename')+ ok(html(a2, 'off-a') === 'written offline in A' && a2.doc.pages[1].title === 'Renamed offline in A',+ 'replay did NOT overwrite A’s offline edits on A')+ ok(pagesKey(a2) === pagesKey(b), 'A and B converged on the same pages')+ closeTab(sa2); closeTab(sb)+}++H('a saved file rejoins as a fork: concurrent edits to the SAME block')+{+ const a = space('same'), b = space('same')+ const sa = new SyncSession(a), sb = new SyncSession(b)+ await settle()+ goOffline(sa)+ // both rewrite b1 ("hello") while partitioned — A on its side, B on its own+ a.commit(() => { a.doc.pages[0].blocks[0].html = 'hello from A offline' })+ b.commit(() => { b.doc.pages[0].blocks[0].html = 'B says hello' })+ // and both edit the same page's title, a plain LWW register+ a.commit(() => { a.doc.pages[0].title = 'Home (A)' })+ await settle()+ b.commit(() => { b.doc.pages[0].title = 'Home (B)' })+ await settle()+ const file = save(a, sa)+ closeTab(sa)+ const { store: a2, session: sa2 } = reopen(file)+ await settle(600)+ const merged = html(a2, 'b1') ?? ''+ ok(merged === html(b, 'b1'), `the block's text converged on both sides ("${merged}")`)+ ok(merged.includes('from A offline') && merged.includes('B says'),+ 'the text merge kept BOTH sides’ words — neither edit was thrown away')+ ok(a2.doc.pages[0].title === b.doc.pages[0].title,+ `the title (a register) converged on one winner ("${a2.doc.pages[0].title}")`)+ ok(pagesKey(a2) === pagesKey(b), 'A and B converged on the same pages')+ closeTab(sa2); closeTab(sb)+}++H('a stamped file reopened with no peers keeps its edits and its state')+{+ const a = space('alone')+ const sa = new SyncSession(a)+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'solo', type: 'p', html: 'mine' }) }, { structure: true })+ await settle()+ const file = save(a, sa)+ closeTab(sa)+ const before = JSON.parse(file)+ const { store: a2, session: sa2 } = reopen(file)+ await settle()+ ok(pagesKey(a2) === JSON.stringify(before.pages), 'nothing in the document moved on reopen with nobody there')+ ok(priv(sa2).forkPending && priv(sa2).state.vv[Object.keys(before.collab?.sync?.vv ?? {})[0]] > 0,+ 'the restored version vector still knows the earlier tab’s ops')+ a2.commit(() => { a2.doc.pages[0].blocks.push({ id: 'solo-2', type: 'p', html: 'more' }) }, { structure: true })+ await settle()+ const again = JSON.parse(save(a2, sa2))+ ok((again.collab?.sync?.lamport ?? 0) > (before.collab?.sync?.lamport ?? 0), 'and saving again stamps a state that has moved on')+ closeTab(sa2)++ // The next time the file is opened with somebody there, they get+ // everything the lone tab wrote. The colleague's tab is open FIRST: a fork+ // announces itself with one `snap` at its own hello, so over the+ // same-machine channel a peer that opens AFTER the fork never hears it (the+ // relay covers that case by persisting the fork's snapshot — onRelayReady).+ // That gap is the kernel session's, shared with slides, and not this rig's.+ const colleague = space('alone')+ const sl = new SyncSession(colleague)+ await settle()+ const { store: a3, session: sa3 } = reopen(JSON.stringify(again))+ await settle(600)+ ok(html(colleague, 'solo') === 'mine' && html(colleague, 'solo-2') === 'more',+ 'reopened later with a colleague there, the edits made with nobody there reach them')+ ok(pagesKey(colleague) === pagesKey(a3), 'and the two converge')+ closeTab(sa3); closeTab(sl)++ // pre-v2 state (bare-id keys) is DISCARDED, as in slides: the file joins as+ // a never-synced adopt rather than restoring registers it cannot read+ const legacy = JSON.parse(file)+ legacy.collab.sync = { v: 1, lamport: 99, regs: { x: [99, 'z'] } }+ const { session: sv1 } = reopen(JSON.stringify(legacy))+ ok(priv(sv1).state.lamport === 0 && priv(sv1).forkPending === false,+ 'a pre-v2 stamp is discarded — fresh adopt, not a restore')+ closeTab(sv1)+}++H('what each write carries: the rules per path')+{+ const a = space('rules')+ const sa = new SyncSession(a)+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'r1', type: 'p', html: 'x' }) }, { structure: true })+ await settle()++ // a never-shared space stays clean+ const solo = space('rules-solo')+ delete (solo.doc as { collab?: unknown }).collab+ const ss = new SyncSession(solo)+ stampSync(solo, ss)+ ok(!(solo.doc as { collab?: { sync?: unknown } }).collab?.sync, 'a space with no session gets no stamp')+ closeTab(ss)++ // a read-only store never rewrites what the file carries+ const ro = space('rules-ro')+ const foreign = { v: 3, lamport: 7, future: true }+ ;(ro.doc.collab as { sync?: unknown }).sync = foreign+ ro.readOnly = true+ const sro = new SyncSession(ro)+ stampSync(ro, sro)+ ok(JSON.stringify((ro.doc.collab as { sync?: unknown }).sync) === JSON.stringify(foreign),+ 'a read-only (frozen / reader / reading-copy) store leaves an unknown-version stamp untouched')+ closeTab(sro)++ // an older build round-trips the stamp byte-for-byte: parseDoc keeps unknown+ // and known collab fields exactly as written+ const file = save(a, sa)+ const r = parseDoc(file)+ ok(r.ok && JSON.stringify(r.doc.collab?.sync) === JSON.stringify(JSON.parse(file).collab?.sync) && !!r.doc.collab?.sync,+ 'parseDoc carries collab.sync through untouched')++ // Duplicate as a new space: new identity, no credentials, no state+ const dup = duplicateAsNew(a.doc, 'doc-dup', '2026-10-04T00:00:00.000Z')+ ok(dup.docId === 'doc-dup' && !('collab' in dup), 'Duplicate drops collab — and with it the stamped sync')+ ok(!!(a.doc.collab as { sync?: unknown }).sync, '…without touching the original, which keeps its own')+ closeTab(sa)+}++H('Duplicate as a new space never syncs with its ancestor')+{+ const a = space('ancestor'), b = space('ancestor')+ const sa = new SyncSession(a), sb = new SyncSession(b)+ await settle()+ stampSync(a, sa)+ const dupStore = new Store(parseDoc(JSON.stringify(duplicateAsNew(a.doc, 'doc-dup-2'))).doc)+ const sd = new SyncSession(dupStore)+ await settle()+ ok(priv(sd).forkPending === false && priv(sd).state.lamport === 0,+ 'the duplicate starts from no state — it is not a fork of anything')+ dupStore.commit(() => { dupStore.doc.pages[0].blocks.push({ id: 'in-dup', type: 'p', html: 'only in the duplicate' }) }, { structure: true })+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'in-anc', type: 'p', html: 'only in the ancestor' }) }, { structure: true })+ await settle(600)+ ok(!a.block('in-dup') && !b.block('in-dup'), 'an edit in the duplicate never reaches the ancestor’s tabs')+ ok(!dupStore.block('in-anc'), 'and an edit in the ancestor never reaches the duplicate')+ ok(html(b, 'in-anc') === 'only in the ancestor', '(while the ancestor’s own tabs still sync — the channel is live)')+ const room = (dupStore.doc.collab as { room?: string } | undefined)?.room+ ok(!room || room !== (a.doc.collab as { room?: string }).room,+ `the duplicate is in no room of the ancestor's (room ${room ?? 'none yet'})`)+ closeTab(sa); closeTab(sb); closeTab(sd)+}+// ---------------------------------------------------------------------------H('the people UI: who is on which page'){diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 7b76f375..fe81769a 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -477,6 +477,17 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.2026, from the same file. `bento.journal()` opens today's for an agent, and`bento.journal('2026-08-06')` any day's.+- **A saved copy of a shared space rejoins its live session with its offline+ edits.** ⌘S, Save a copy and both self-update writes now stamp the live+ session's sync state into the file (`collab.sync`), as bento/slides always+ has. Before, a copy edited away from the session reopened as if it had never+ synced: its edits stayed in that copy and never reached anyone else, and an+ edit to a paragraph somebody had also changed was overwritten by theirs.+ Measured in two Chrome tabs: edit in one, save, edit the saved file offline,+ edit in the other tab meanwhile, reopen — the old build ends with the two+ tabs disagreeing; this one shows both edits in both tabs. View-only copies,+ page extracts, Markdown and JSON exports, and "Duplicate as a new space…"+ carry no sync state, and a file opened read-only is never re-stamped.- **⌘Z no longer undoes who a space is.** Undo restores a snapshot of thewhole document, and it used to bring that snapshot's identity back with thecontent: edit something, then Stop sharing, and the next ⌘Z switched sharingdiff --git a/spaces/src/about.ts b/spaces/src/about.tsindex 69068bad..5d2fc007 100644--- a/spaces/src/about.ts+++ b/spaces/src/about.ts@@ -40,6 +40,7 @@ import { t, localeChoices, locale, setLocale } from './i18n'import { appearanceSection } from './appearance'import { esc, textOf } from './sanitize'import { docForExport } from './model'+import { duplicateAsNew } from './share.ts'import { htmlToMd } from './marks.ts'import { humanBytes } from './assets'import { SPEC, mdLayout, type MdCtx } from './blocks'@@ -75,6 +76,12 @@ export interface AboutHooks {onWriteCopy?: (doc: SpacesDoc) => Promise<boolean>/** the editor's status line, for the confirmations that outlive the dialog */onStatus?: (message: string) => void+ /**+ * Called immediately before a self-update writes THIS document into a new+ * shell — stamps the live session's CRDT state (share.ts stampSync), so the+ * updated file rejoins as a fork exactly as a ⌘S-saved one does.+ */+ onBeforeWrite?: () => void}/**@@ -99,7 +106,7 @@ export async function launchUpdateCheck(): Promise<void> {}export function openAbout(hooks: AboutHooks): void {- const { store, onRepaint, onSaveCopy, onImport, onExportSpace, onWriteCopy, onStatus } = hooks+ const { store, onRepaint, onSaveCopy, onImport, onExportSpace, onWriteCopy, onStatus, onBeforeWrite } = hooksconst doc = store.docconst returnFocus = document.activeElement as HTMLElement | null@@ -377,6 +384,7 @@ export function openAbout(hooks: AboutHooks): void {inPlace.disabled = trueinPlace.textContent = t('Verifying…')try {+ onBeforeWrite?.()const written = await applyUpdateInPlace(rel, store.doc)if (written) {box.replaceChildren(updatedCard(rel, written.backup))@@ -402,6 +410,7 @@ export function openAbout(hooks: AboutHooks): void {try {// the update writes a NEW file and leaves this one untouched, so a// bad update is undone by deleting the download+ onBeforeWrite?.()await applyUpdate(rel, store.doc)get.textContent = t('Downloaded ✓')box.append(note(t('This window keeps running v{v} until you open the downloaded file.', { v: APP_VERSION })))@@ -607,10 +616,8 @@ export function openAbout(hooks: AboutHooks): void {// A DUPLICATE, not a copy: a fresh docId and no collaboration// credentials, so it can never sync with the space it came from. You// keep editing this one — the writer holds no handle (portable.ts).- const clone = JSON.parse(JSON.stringify(store.doc)) as SpacesDoc- clone.docId = uid('doc')- delete clone.collab- clone.modified = new Date().toISOString()+ // share.ts duplicateAsNew: the stamped `sync` goes with `collab`.+ const clone = duplicateAsNew(store.doc, uid('doc'))close()void onWriteCopy(clone)})] : []),diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex e682b5b1..5bc1558d 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -5168,7 +5168,8 @@ export class Editor {this.store.endRun()// Copies rejoin as true FORKS: the stamped CRDT state is what lets an// offline edit on either side merge two-way rather than clobber.- this.session?.stampInto(this.store.doc)+ // (readerCopy clears it again — a viewer is not a fork.)+ shareModule.stampSync(this.store, this.session)const out = kind === 'invite'? await shareModule.inviteCopy(this.store.doc): shareModule.readerCopy(this.store.doc)@@ -5210,6 +5211,8 @@ export class Editor {// handle, which is what leaves you editing this space afterwards.onWriteCopy: (out) => this.onExportSpace?.(out) ?? Promise.resolve(false),onStatus: (msg) => this.status(msg),+ // both self-update writes carry this space's CRDT state, as ⌘S does+ onBeforeWrite: () => shareModule.stampSync(this.store, this.session),})}diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 331a7845..7b5f64d2 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -33,7 +33,7 @@ import { buildSpacePreview } from './preview'import { Store } from './store'import { Editor } from './editor'import { SyncSession } from './sync/session.ts'-import { isReaderCopy } from './share.ts'+import { isReaderCopy, stampSync } from './share.ts'import { downloadMarkdown, launchUpdateCheck } from './about'configureApp({@@ -263,6 +263,10 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')//// The status line was dead too: saveFile returns 'saved-as' down the// forcePicker path, never 'saved', so the confirmation never appeared.+ //+ // A copy of THIS space is this replica, so it carries the CRDT state like+ // ⌘S does: opened later, it rejoins as a fork rather than a fresh adopt.+ stampSync(store, session)void serializeAuto(store.doc).then((html) => writeUpdatedFileAs(html, store.doc, { suffix: suffix === 'copy' ? 'copy' : suffix })).then((ok) => { if (ok) editor.status(t('Copy saved — you are still editing the original')) })@@ -314,6 +318,11 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')async function doSave(): Promise<void> {store.endRun()editor.status(t('Saving…'))+ // Stamped at the moment the document is taken for the write, and nowhere+ // earlier: the state must describe exactly the bytes that reach the file,+ // or the registers restored on reopen defend the wrong values. When the+ // save queue lands this moves into its prepare step, beside the snapshot.+ stampSync(store, session)const res = await saveFile(store.doc)if (res === 'saved' || res === 'saved-as' || res === 'downloaded') {// the document is on disk now — the dot goes outdiff --git a/spaces/src/share.ts b/spaces/src/share.tsindex 77760478..8e0a0864 100644--- a/spaces/src/share.ts+++ b/spaces/src/share.ts@@ -153,6 +153,64 @@ export function readerCopy(doc: SpacesDoc): SpacesDoc | null {return out}+/**+ * Write this replica's CRDT state into `doc.collab.sync`, immediately before+ * the document is taken for a write of THIS space — ⌘S, Save a copy, the+ * invite, and both self-update writes.+ *+ * Why it matters: a saved file that carries the state rejoins its live session+ * as a true FORK. Its registers defend the edits made while it was offline,+ * relay replay is deduplicated by version vector instead of re-applied over+ * them, and the kernel session sends a `snap` frame on rejoin that merges the+ * fork into every peer, both ways. A file saved WITHOUT it reopens as a fresh+ * adopt: its offline edits are already in the shadow, so no op is ever minted+ * for them and no peer ever sees them (scripts/test-sync-spaces-session.ts,+ * "a saved file rejoins as a fork", measures exactly that under sabotage).+ *+ * The kernel's `stampInto` already refuses a document with no session+ * (`collab` absent or `on: false`). This adds the one rule a space needs on+ * top: a store opened READ-ONLY never stamps. All three ways to get there+ * mean the file's `sync` is not ours to rewrite —+ *+ * · frozen written by a newer build: whatever `sync` it carries may be+ * a SYNC_V this build cannot read, and the format promise is+ * that an unknown field survives a round trip untouched+ * · reader copy `readerCopy()` removed `sync` on purpose; a viewer that+ * rejoined as a fork of itself would be a fork nobody can merge+ * · `readonly` a sealed reading copy has no session to rejoin+ *+ * and a read-only store has made no edits of its own to defend.+ *+ * Copies that are NOT this replica never reach here and carry no state: the+ * page extract and "Copy document JSON" drop `collab` whole, "Duplicate as a+ * new space…" is a new identity (`duplicateAsNew`), and the view-only copy+ * clears `sync` in `readerCopy()`.+ */+export function stampSync(+ store: { readonly readOnly: boolean; readonly doc: SpacesDoc },+ session: { stampInto(doc: SpacesDoc): void } | null | undefined,+): void {+ if (!session || store.readOnly) return+ session.stampInto(store.doc)+}++/**+ * "Duplicate as a new space…": the same pages under a NEW identity.+ *+ * A fresh `docId` and no `collab` at all — not even the stamped `sync`. The+ * duplicate must never meet the space it came from: the docId keys the+ * same-machine channel, the room keys the relay, and the stamped state would+ * make it rejoin the ancestor's room as a fork of it. It mints credentials of+ * its own when it is first opened, exactly as a new space does.+ */+export function duplicateAsNew(doc: SpacesDoc, docId: string, now = new Date().toISOString()): SpacesDoc {+ const out = clone(doc)+ out.docId = docId+ delete out.collab+ out.modified = now+ return out+}+/*** Is this copy a live viewer — one that follows the session read-only?*