Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: restore paths onto the kernel's applyRestore, by direction; trail recover hook (#714)

nyblnetd6bcff73db67
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a414db5c..cd31d078 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -245,6 +245,23 @@ jobs:
--outfile="$RUNNER_TEMP/test-spaces-restore-gate.mjs"
node "$RUNNER_TEMP/test-spaces-restore-gate.mjs"
+ - name: Spaces restore directions rig (several timezones)
+ # Every whole-document restore resolves through the kernel's
+ # applyRestore over one rule set (spaces/src/store.ts RESTORE_RULES):
+ # undo/redo, version restore, Replace from JSON and loadDoc go 'back'
+ # (history kept live), the recovery banner goes 'recover' (revisions
+ # follow the snapshot, the trail unions by day without counting a day
+ # twice). Undo keeps the asset pool its checkpoints omit. The trail
+ # hook does day arithmetic on labels, hence the timezone loop.
+ # (Bundled: store.ts imports './model' extensionless.)
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-spaces-restore.ts --bundle --platform=node --format=esm \
+ --outfile="$RUNNER_TEMP/test-spaces-restore.mjs"
+ for tz in UTC Europe/Berlin Pacific/Kiritimati Pacific/Niue; do
+ echo "--- $tz"
+ TZ=$tz node "$RUNNER_TEMP/test-spaces-restore.mjs"
+ done
+
- name: Spaces in-file history rig
# doc.revisions (spaces/src/history.ts): every entry is the kernel's
# Revision envelope with the patch under body; what it covers is the
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index bb2d682e..bd08c33e 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10540,3 +10540,97 @@ real deck.
`docs/PLATFORM.md` is where cross-app invariants live, and it is the
maintainer's to edit. This contract belongs there once the maintainer agrees.
+
+## 2026-10-15 — bento/spaces restores by direction, and a recovery unions the trail by day
+
+Every whole-document restore in bento/spaces now resolves through the kernel's
+`applyRestore` (`kernel/src/docfields.ts`) over one rule set,
+`spaces/src/store.ts` `RESTORE_RULES` = the field-class map plus two recover
+hooks, on `trail` and `revisions`. The hand-rolled keep-live in `store.ts` and
+`restoregate.ts` is gone. Each entry point names its direction:
+
+- **'back'** — undo, redo, a version restore from either timeline, Replace
+ from JSON and `bento.loadDoc`. Content follows. Identity, modes, capability
+ and history keep the live value, so a paste or a version can neither delete
+ this space's history nor install one.
+- **'recover'** — the crash-recovery banner only. `revisions` goes through
+ `history.ts` `revisionsRecover`, which applies these rules in order:
+ 1. `[]` means the list was cleared. The hook returns `undefined`, so the
+ key is removed, just as Clear history deletes it rather than storing
+ `[]`.
+ 2. A recovered list that is not an array, or that has even one entry
+ failing `readable`, is refused whole, and the live list stands. That
+ entry check is the same one a file's list passes (`historyIsForeign`).
+ A recovery snapshot is foreign input, and before this rule one
+ unreadable entry replaced the live, readable log.
+ 3. A foreign live list is never written over (#671). This also keeps a
+ newer build's history intact.
+ 4. Otherwise the readable recovered list follows the snapshot. This is the
+ crash case: a revision the last save wrote must survive.
+
+ The hook never merges and never picks entries.
+
+ **Cleared stays cleared.** The recovery snapshot is the whole document, so
+ a snapshot with no `revisions` means the person ran Clear history. Without
+ the rule below, Restore on the banner brought the cleared drafts back, and
+ the next copy the person shared carried them. That is a confidentiality
+ bug: here confidentiality wins over integrity, behind a banner the person
+ chose to accept. Since kernel #726, a whole snapshot removes an absent
+ history key by default, so cleared revisions stay cleared in the kernel
+ itself. Before #726 the kernel kept that key live before any hook ran. For
+ that reason `restoregate.ts` `asWholeRecovery` states an absent `revisions`
+ as `[]` on the 'recover' path, and the hook reads `[]` as cleared. That
+ normalisation is now redundant but harmless, since it gives the same
+ result. It stays for now, and removing it is a separate follow-up.
+
+ **The trail opts out.** `RECOVER_RULES` carries
+ `keepLiveWhenAbsent: ['trail']`, and only `trail`. Nobody clears a trail by
+ leaving it out: a snapshot with no trail means "no rows yet", and the live
+ rows are observations nobody can recompute. `revisions` must never be listed
+ there, because cleared history has to stay cleared. A rig row pins the list
+ to exactly `['trail']`. `trail` goes through `trail.ts` `trailRecover`.
+
+`trailRecover` keeps a day found on one side only. A day on both sides goes
+to the side whose whole document is later: the snapshot's `at` against the
+live `modified`, both in epoch ms. A tie keeps live. A live file with no
+`modified` counts as older. Next, so no day is counted twice, rows are walked
+newest first within each series, and a row whose day falls inside the span
+of a row already kept is dropped. That covers a weekly or monthly bucket
+against single days, and two buckets that overlap. Days are compared as
+labels with `dayIndex`, and only within one series. The result then goes
+through `pruneTrail`. Live's key order is kept, so a snapshot that adds
+nothing raises no banner.
+
+**Undo keeps the asset pool live.** Undo checkpoints omit `assets` for size.
+On 'back', `applyRestore` treats an absent content field as dropped, so a
+checkpoint applied as-is would empty the pool. The undo path alone overrides
+`assets` to 'live' (`UNDO_RULES`). That is what undo did before. A version
+restore and a paste carry their own pool, so there it follows.
+
+**A recovery removes what was removed.** The banner path passes
+`wholeSnapshot: true` explicitly. Kernel #716 made that the default, but the
+spaces call still states it, because the recovery snapshot is
+`contentOnly(doc)`, the whole document. So a content key or an unknown
+top-level key missing from the snapshot was deleted by the person, and it
+stays deleted after recovery. That covers a design, footnotes or a journal
+template removed after the last save. History follows its own rules. A
+snapshot with no `trail` keeps the live rows, through the
+`keepLiveWhenAbsent` opt-out. A snapshot with no `revisions` means they were
+cleared, as described above. The identity, mode and
+capability floor is unchanged.
+
+Verified in `scripts/test-spaces-restore.ts`. Mutations, all red:
+- recovery passed as 'back';
+- Replace from JSON passed as 'recover';
+- the hook returning the snapshot's trail wholesale;
+- the span drop removed;
+- the undo assets override removed;
+- `wholeSnapshot: false` on the recovery path;
+- the revisions hook unbound, or returning the snapshot's list;
+- the absent-to-`[]` normalisation removed;
+- the hook keeping live for `[]`;
+- rule 3 (a foreign live list is kept) dropped;
+- `keepLiveWhenAbsent` removed or emptied, which loses the live trail;
+- `'revisions'` added to `keepLiveWhenAbsent`, together with the
+ normalisation removed, which resurrects cleared drafts. With the
+ normalisation still in place, only the pins catch adding `'revisions'`.
diff --git a/scripts/test-spaces-history.ts b/scripts/test-spaces-history.ts
index 8f4ff0d7..c066ce68 100644
--- a/scripts/test-spaces-history.ts
+++ b/scripts/test-spaces-history.ts
@@ -35,7 +35,7 @@ import { join } from 'node:path'
import { Store } from '../spaces/src/store.ts'
import { parseDoc, docContentKey, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
import { SPACES_FIELDS, SPACES_NOT_EDIT } from '../spaces/src/docclass.ts'
-import { restoreInto } from '../spaces/src/restoregate.ts'
+import { restoreVersion, replaceFromJson } from '../spaces/src/restoregate.ts'
import { extractSpace } from '../spaces/src/portable.ts'
import { starterDoc } from '../spaces/src/starter.ts'
import { validateRevision } from '../kernel/src/docfields.ts'
@@ -173,7 +173,7 @@ console.log('\n2. what is covered comes from the field map\n')
recordOnSave(store) // "this week"
const thisWeek = J(contentOf(store.doc))
const next = restoredDoc(store.doc, 0)!
- ok(restoreInto(store, J(next)), 'restoring last week goes through the gate and is accepted')
+ ok(restoreVersion(store, J(next)), 'restoring last week goes through the gate and is accepted')
const back = store.doc
ok(J(back.footnotes) === J({ 1: 'last week’s note' }), 'last week\'s FOOTNOTES are back')
ok(back.design === 'almanac' && J(back.designs) === J({ mine: { base: 'riso', label: 'Mine' } }), 'last week\'s DESIGN and design registry are back')
@@ -274,11 +274,11 @@ console.log('\n5. history is a log: the dot, the recovery key, undo, replace\n')
const pasted = clone(store.doc) as SpacesDoc & Obj
delete pasted.revisions
pasted.title = 'Pasted'
- store.replaceDoc(pasted)
+ ok(replaceFromJson(store, J(pasted)), 'Replace from JSON accepts Copy document JSON\'s output')
ok(store.doc.title === 'Pasted' && J(store.doc.revisions) === two, 'a whole-document replace keeps the LIVE history (a paste never deletes it)')
const forged = clone(store.doc) as SpacesDoc & Obj
forged.revisions = [{ id: 'forged', at: 't', body: { doc: { title: 'x' } } }] as never
- store.replaceDoc(forged)
+ ok(replaceFromJson(store, J(forged)), 'Replace from JSON accepts a document carrying a history')
ok(J(store.doc.revisions) === two, '…and never installs the pasted document\'s history either')
}
@@ -301,7 +301,7 @@ console.log('\n6. a crafted revision cannot smuggle identity, capability or scri
ok(next.docId === 'd-hist' && (next.collab as Obj).room === 'wROOM' && !('template' in next),
'body.doc only ever applies COVERED fields — docId, collab and the modes are ignored')
ok(next.title === 'Owned', '…while a covered field in it does apply')
- ok(restoreInto(store, J(next)), 'restored through the gate')
+ ok(restoreVersion(store, J(next)), 'restored through the gate')
const html = store.doc.pages[0].blocks[0].html ?? ''
ok(!/onerror|<script/i.test(html) && /hi/.test(html), `block html is sanitized on the way in (${J(html)})`)
ok(store.doc.docId === 'd-hist' && (store.doc.collab as Obj).room === 'wROOM', 'identity and the room are the live space\'s')
diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.ts
index 34c5b6a6..65e5738b 100644
--- a/scripts/test-spaces-model.ts
+++ b/scripts/test-spaces-model.ts
@@ -452,10 +452,12 @@ for (const [label, input, err] of [
// checkpoints undo first, which is what makes the note "Restoring is
// undoable" true rather than reassuring.
ok(/listVersions\(/.test(about), 'Version history… reads the timeline')
- // (through restoreInto since the restore gate: the stored entry is foreign
- // input, gated first — restoregate.ts — and then handed to replaceDoc)
+ // (through restoreVersion → restoreInto since the restore gate: the stored
+ // entry is foreign input, gated first — restoregate.ts — and then handed to
+ // replaceDoc, going 'back')
const gate = fs.readFileSync(new URL('../spaces/src/restoregate.ts', import.meta.url), 'utf8')
- ok(/restoreInto\(h\.store, v\.json\)/.test(about) && /store\.replaceDoc\(g\.doc\)/.test(gate),
+ ok(/restoreVersion\(h\.store, v\.json\)/.test(about) && /store\.replaceDoc\(incoming, direction/.test(gate) &&
+ /function restoreVersion\([^)]*\)[^{]*\{\s*return restoreInto\(store, json, 'back'\)/.test(gate),
'…and restores through replaceDoc, so ⌘Z walks it back')
}
diff --git a/scripts/test-spaces-restore-gate.ts b/scripts/test-spaces-restore-gate.ts
index e631162c..ee70dbcb 100644
--- a/scripts/test-spaces-restore-gate.ts
+++ b/scripts/test-spaces-restore-gate.ts
@@ -32,7 +32,7 @@ import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { Store } from '../spaces/src/store.ts'
import { parseDoc, docContentKey, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
-import { gateRestored, recoveryOffered, restoreInto, MAX_RESTORE_CHARS } from '../spaces/src/restoregate.ts'
+import { gateRestored, recoveryOffered, restoreInto, recoverInto, MAX_RESTORE_CHARS } from '../spaces/src/restoregate.ts'
import { sanitizeInline } from '../spaces/src/sanitize.ts'
let checks = 0
@@ -78,7 +78,8 @@ const editedA = (text = 'edited after the save'): Record<string, any> => {
const first = (s: Store) => String((s.doc.pages as SpacesDoc['pages'] | undefined)?.[0]?.blocks?.[0]?.html ?? '')
/** A restore that THROWS was not refused cleanly — the app would have applied
* whatever it got to before the throw — so it counts as "went through". */
-const restore = (s: Store, json: unknown): boolean => { try { return restoreInto(s, json) } catch { return true } }
+// Both directions run the same gate first; 'back' is the version restore.
+const restore = (s: Store, json: unknown): boolean => { try { return restoreInto(s, json, 'back') } catch { return true } }
const offered = (json: unknown, live: SpacesDoc): boolean => { try { return recoveryOffered(json, live) } catch { return true } }
console.log('bento/spaces restore gate\n')
@@ -125,7 +126,7 @@ console.log('\nidentity and capability stay the open space\'s\n')
{
const noCollab = liveA(); delete noCollab.collab
const snap = editedA(); snap.collab = { v: 2, room: 'wATTACKER', key: 'k', on: true }
- const g = gateRestored(JSON.stringify(snap), noCollab)
+ const g = gateRestored(JSON.stringify(snap), noCollab, 'recover', Date.now())
ok(g.ok && g.doc.collab === undefined, 'a space with no live session does not gain one from an entry')
}
@@ -192,7 +193,7 @@ console.log('\nthe controls: honest restores still work\n')
// recovery: an edit lost in a crash, plus a field this build does not know
const snap = editedA(); snap.futureField = { kept: true }; snap.pages[1].futurePageField = 7
const s = new Store(liveA())
- ok(restore(s, JSON.stringify(snap)), 'an honest recovery snapshot restores')
+ ok(recoverInto(s, { json: JSON.stringify(snap), at: Date.now() }), 'an honest recovery snapshot restores (the banner\'s path, \'recover\')')
ok(first(s) === 'edited after the save', 'with its edit')
ok((s.doc as Record<string, any>).futureField?.kept === true && (s.doc.pages[1] as Record<string, any>).futurePageField === 7,
'and unknown fields survive, as a file open keeps them')
@@ -211,9 +212,11 @@ console.log('\nthe controls: honest restores still work\n')
}
{
const live = liveA()
- const g = gateRestored(JSON.stringify(snapshotOf(live)), live)
- ok(g.ok && docContentKey(g.doc) === docContentKey(live) && JSON.stringify(g.doc) === JSON.stringify(live),
- 'an honest snapshot of the open space comes back byte-identical')
+ for (const dir of ['back', 'recover'] as const) {
+ const g = gateRestored(JSON.stringify(snapshotOf(live)), live, dir, Date.now())
+ ok(g.ok && docContentKey(g.doc) === docContentKey(live) && JSON.stringify(g.doc) === JSON.stringify(live),
+ `an honest snapshot of the open space comes back byte-identical ('${dir}')`)
+ }
}
console.log('\nevery restore path uses the gate\n')
@@ -225,15 +228,15 @@ console.log('\nevery restore path uses the gate\n')
const about = readFileSync(join(root, 'spaces/src/about.ts'), 'utf8') +
readFileSync(join(root, 'spaces/src/doccmds.ts'), 'utf8')
const offer = main.slice(main.indexOf('async function offerRecovery('), main.indexOf('async function offerRecovery(') + 1400)
- ok(/recoveryOffered\(snap\.json, doc\)/.test(offer), 'the recovery check gates before offering')
- ok(/restoreInto\(store, snap\.json\)/.test(offer), 'the banner\'s Restore goes through restoreInto')
- ok(/restoreInto\((h\.)?store, v\.json\)/.test(about), 'History\'s Restore goes through restoreInto')
+ ok(/recoveryOffered\(snap\.json, doc, snap\.at\)/.test(offer), 'the recovery check gates before offering (timed by the snapshot)')
+ ok(/recoverInto\(store, snap\)/.test(offer), 'the banner\'s Restore goes through recoverInto (restoreInto, \'recover\')')
+ ok(/restoreVersion\((h\.)?store, v\.json\)/.test(about), 'History\'s Restore goes through restoreVersion (restoreInto, \'back\')')
ok(!/JSON\.parse\((snap|v)\.json\)/.test(main + about), 'no raw JSON.parse of a stored entry remains')
// the in-file timeline (history.ts) is the document's own, but what it
// applies is still parsed, sanitized and given the live identity
const fileHist = about.slice(about.indexOf('function openFileHistory('), about.indexOf('function summary('))
- ok(/restoreInto\(h\.store, JSON\.stringify\(next\)\)/.test(fileHist) && !/replaceDoc\(/.test(fileHist),
- 'Versions in this file restores through restoreInto, never a bare replaceDoc')
+ ok(/restoreVersion\(h\.store, JSON\.stringify\(next\)\)/.test(fileHist) && !/replaceDoc\(/.test(fileHist),
+ 'Versions in this file restores through restoreVersion, never a bare replaceDoc')
}
console.log('\na design is content, not identity\n')
@@ -248,19 +251,47 @@ console.log('\na design is content, not identity\n')
const snap = clone(live) as SpacesDoc & { design?: string; designs?: Record<string, unknown> }
snap.design = 'mine'
snap.designs = { mine: { base: 'riso', label: 'Mine' } }
- const g = gateRestored(JSON.stringify(snap), live)
+ const g = gateRestored(JSON.stringify(snap), live, 'recover', Date.now())
ok(g.ok && (g.doc as typeof snap).design === 'mine' && JSON.stringify((g.doc as typeof snap).designs) === JSON.stringify(snap.designs),
'the gate passes design and designs through from the snapshot')
ok(recoveryOffered(JSON.stringify(snap), live), 'a snapshot that differs only by its design is offered for recovery')
const designedLive = clone(live) as SpacesDoc & { design?: string }
designedLive.design = 'ledger'
- const g2 = gateRestored(JSON.stringify(clone(live)), designedLive)
- ok(g2.ok && !Object.hasOwn(g2.doc, 'design'), 'restoring a snapshot with no design does not keep the live design (it is content, not identity)')
+ const g2 = gateRestored(JSON.stringify(clone(live)), designedLive, 'back')
+ ok(g2.ok && !Object.hasOwn(g2.doc, 'design'), 'restoring a version with no design does not keep the live design (it is content, not identity)')
+ // A recovery removes what was removed (kernel #716, wholeSnapshot): the
+ // recovery snapshot is the whole document, so a design, footnotes and a
+ // journal template the person removed after the last save stay removed —
+ // through the banner's real path, recoverInto. (This row was pinned as a
+ // KERNEL GAP until #716.)
+ {
+ const fileDoc = clone(live) as SpacesDoc & Record<string, unknown>
+ fileDoc.design = 'ledger'
+ fileDoc.footnotes = { 1: 'a note' }
+ fileDoc.journalTemplate = 't1'
+ fileDoc.futureKey = { from: 'a newer build' }
+ fileDoc.trail = { '2026-09-10': { n: { todo: 1 } } }
+ fileDoc.revisions = [{ id: 'r0', at: '2026-09-10T00:00:00Z', body: {} }]
+ // the crash copy: all four removed, no history in it at all, forged modes
+ const crash = snapshotOf(live)
+ crash.pages[0].blocks[0].html = 'edited before the crash'
+ crash.readonly = true; crash.template = true
+ const s = new Store(fileDoc as SpacesDoc)
+ ok(recoverInto(s, { json: JSON.stringify(crash), at: Date.now() }), 'recovery of a snapshot with design/footnotes/journal template removed applies')
+ const d = s.doc as SpacesDoc & Record<string, unknown>
+ ok(!Object.hasOwn(d, 'design') && !Object.hasOwn(d, 'footnotes') && !Object.hasOwn(d, 'journalTemplate'),
+ 'a design, footnotes and journal template REMOVED after the last save stay removed after recovery')
+ ok(!Object.hasOwn(d, 'futureKey'), 'an UNKNOWN top-level key absent from the snapshot is removed too')
+ ok(JSON.stringify(d.trail) === JSON.stringify(fileDoc.trail), 'an absent trail in the snapshot KEEPS the live rows ("no rows yet")')
+ ok(!Object.hasOwn(d, 'revisions'), 'an absent revisions in the (whole) snapshot means CLEARED: the key is removed')
+ ok(d.docId === live.docId && JSON.stringify(d.collab) === JSON.stringify(LIVE_COLLAB) && d.readonly === undefined && d.template === undefined,
+ 'the identity / mode / capability floor is unchanged (collab live, forged readonly/template ignored)')
+ }
// A PAGE's design (per-page designs) is content too: it lives in `pages`,
// which the gate passes through and the content key already covers
const paged = clone(live) as SpacesDoc
;(paged.pages[0] as { design?: string }).design = 'studio'
- const g3 = gateRestored(JSON.stringify(paged), live)
+ const g3 = gateRestored(JSON.stringify(paged), live, 'recover', Date.now())
ok(g3.ok && (g3.doc.pages[0] as { design?: string }).design === 'studio', 'the gate passes a page\'s own design through from the snapshot')
ok(recoveryOffered(JSON.stringify(paged), live), 'a snapshot that differs only by one page\'s design is offered for recovery')
}
diff --git a/scripts/test-spaces-restore.ts b/scripts/test-spaces-restore.ts
new file mode 100644
index 00000000..2bb45003
--- /dev/null
+++ b/scripts/test-spaces-restore.ts
@@ -0,0 +1,533 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Every whole-document restore in bento/spaces, by DIRECTION.
+//
+// node scripts/test-spaces.mjs restore
+//
+// (Bundled: store.ts imports './model' extensionless — the runner does what CI
+// does. Run from the repo root; the last section reads main.ts and doccmds.ts.)
+//
+// WHAT THIS PROVES. Spaces restores a whole document from six places, and all
+// of them now resolve field-by-field through ONE kernel call
+// (kernel/src/docfields.ts applyRestore) over ONE rule set (store.ts
+// RESTORE_RULES). What differs is the DIRECTION each passes:
+//
+// 'back' undo, redo, a version restore (this browser's timeline and the
+// one inside the file), Replace from JSON, bento.loadDoc;
+// 'recover' the crash-recovery banner.
+//
+// Each section drives the REAL entry point (Store.undo/redo, restoreVersion,
+// replaceFromJson, recoverInto) and checks the three things a direction
+// decides: identity/mode/capability (always live), history (live on 'back';
+// on 'recover', revisions follow the snapshot when it has them and the trail
+// unions by day through trail.ts trailRecover), and content (follows).
+//
+// THE ASSETS TRAP. Undo checkpoints omit `assets` for size, and applyRestore on
+// 'back' reads an absent content field as dropped. store.ts keeps the pool live
+// on the undo path only (UNDO_RULES); section 4 is what goes red without it.
+
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { Store, RESTORE_RULES, RECOVER_RULES, rulesFor, restoreAt } from '../spaces/src/store.ts'
+import { parseDoc, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
+import { recoverInto, restoreVersion, replaceFromJson, recoveryOffered, gateRestored, asWholeRecovery } from '../spaces/src/restoregate.ts'
+import { trailRecover, pruneTrail, TRAIL_BUDGET, TRAIL_MAX, spanOf, dayIndex, parseTrailKey, type Trail, type TrailRow } from '../spaces/src/trail.ts'
+import { recordRevision, restoredDoc, revisionsOf, revisionsRecover, clearHistory } from '../spaces/src/history.ts'
+
+let checks = 0
+let failures = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+const J = (v: unknown) => JSON.stringify(v)
+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T
+type Obj = Record<string, any>
+
+const LIVE_COLLAB = { v: 2, room: 'wLIVE', key: 'live-key', on: true }
+const PHOTO = 'data:image/png;base64,' + 'iVBORw0KGgo'.repeat(40)
+const LIVE_MODIFIED = '2026-09-15T12:00:00.000Z'
+const LIVE_MS = Date.parse(LIVE_MODIFIED)
+const HOUR = 3600_000
+
+const row = (todo: number, extra: Partial<TrailRow> = {}): TrailRow => ({ n: { todo }, ...extra })
+
+function mk(over: Obj = {}): SpacesDoc {
+ const r = parseDoc(J({
+ format: FORMAT, version: 1, docId: 'space-R', title: 'R', home: 'p1', modified: LIVE_MODIFIED,
+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', measure: 720 },
+ pages: [
+ { id: 'p1', title: 'One', blocks: [{ id: 'b1', type: 'p', html: 'live text' }] },
+ { id: 'p2', title: 'Two', parent: 'p1', blocks: [{ id: 'b2', type: 'p', html: 'two' }] },
+ ],
+ assets: { photo: PHOTO },
+ collab: LIVE_COLLAB,
+ trail: { '2026-09-10': row(5), '2026-09-11': row(6) },
+ ...over,
+ }))
+ if (!r.ok) throw new Error('fixture did not parse')
+ return r.doc
+}
+/** What autosave files (kernel contentOnly): the document minus collab. */
+const snapOf = (doc: SpacesDoc): Obj => { const { collab: _c, ...rest } = clone(doc) as Obj; void _c; return rest }
+const text = (d: SpacesDoc) => String(d.pages[0]?.blocks[0]?.html ?? '')
+/** identity, modes and capability are exactly the live ones */
+const identityLive = (d: SpacesDoc) =>
+ d.docId === 'space-R' && J(d.collab) === J(LIVE_COLLAB) && d.readonly === undefined && d.template === undefined
+/** a forged identity block a snapshot / paste / version might carry */
+const FORGED = { docId: 'space-R', collab: { v: 2, room: 'wEVIL', key: 'evil', on: true }, readonly: true, template: true }
+
+console.log('bento/spaces whole-document restore, by direction\n')
+
+// ---------------------------------------------------------------------------
+console.log('0. the rules\n')
+{
+ ok(RESTORE_RULES.recover !== undefined && Object.keys(RESTORE_RULES.recover).sort().join() === 'revisions,trail',
+ 'two recover hooks are bound: trail and revisions')
+ ok(RESTORE_RULES.recover!.trail === trailRecover && RESTORE_RULES.recover!.revisions === revisionsRecover,
+ '…trail.ts trailRecover and history.ts revisionsRecover')
+ ok(RECOVER_RULES.recover === RESTORE_RULES.recover, '…and the recovery rules carry the same hooks')
+ ok(!RESTORE_RULES.keepLive, 'no keepLive override in the shared rules (the undo-only assets override lives beside undo)')
+ ok(J(RECOVER_RULES.keepLiveWhenAbsent) === J(['trail']),
+ 'RECOVER_RULES.keepLiveWhenAbsent is EXACTLY [\'trail\'] — never revisions (cleared history stays cleared)')
+ ok(RESTORE_RULES.keepLiveWhenAbsent === undefined, '…and the \'back\' rules carry no such list')
+ ok(RECOVER_RULES.wholeSnapshot === true && rulesFor('recover') === RECOVER_RULES,
+ 'the recovery banner passes wholeSnapshot: true EXPLICITLY (a recovery snapshot is the whole document)')
+ ok(rulesFor('back') === RESTORE_RULES && RESTORE_RULES.wholeSnapshot === undefined, '\'back\' paths use the shared rules, where the flag does not apply')
+ const a = restoreAt(mk(), 123)
+ ok(a.live === LIVE_MS && a.incoming === 123, 'restoreAt: live = Date.parse(modified), incoming = the snapshot\'s ms')
+ const noMod = mk(); delete noMod.modified
+ ok(restoreAt(noMod, 5).live === undefined, 'restoreAt: no modified → live undefined')
+ const badMod = mk(); badMod.modified = 'not a date'
+ ok(restoreAt(badMod, 5).live === undefined, 'restoreAt: an unparseable modified → live undefined, never NaN')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n1. undo / redo go BACK: content follows, identity and history stay live\n')
+{
+ const s = new Store(mk({ revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { full: 1 } }] }))
+ s.commit(() => { s.doc.pages[0].blocks[0].html = 'edited' })
+ // since the checkpoint: Stop sharing, a mode, and history written outside any commit
+ ;(s.doc.collab as Obj).on = false
+ const collabNow = J(s.doc.collab)
+ ;(s.doc.trail as Obj)['2026-09-12'] = row(7)
+ ;(s.doc.revisions as Obj[]).push({ id: 'r1', at: '2026-09-12T00:00:00Z', body: { full: 2 } })
+ const histNow = J([s.doc.trail, s.doc.revisions])
+ s.undo()
+ ok(text(s.doc) === 'live text', 'undo: content follows the checkpoint')
+ ok(J(s.doc.collab) === collabNow && s.doc.docId === 'space-R', 'undo: identity and capability are the live ones (Stop sharing survives ⌘Z)')
+ ok(J([s.doc.trail, s.doc.revisions]) === histNow, 'undo: history (trail AND revisions) is the live one')
+ ok(s.doc.assets?.photo === PHOTO, 'undo: the asset pool is intact')
+ s.redo()
+ ok(text(s.doc) === 'edited' && J(s.doc.collab) === collabNow && J([s.doc.trail, s.doc.revisions]) === histNow,
+ 'redo: content follows, identity and history stay live')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n2. version restore goes BACK (both timelines)\n')
+{
+ // the timeline inside the file (history.ts)
+ const s = new Store(mk())
+ recordRevision(s.doc)
+ s.commit(() => { s.doc.pages[0].blocks[0].html = 'this week' })
+ recordRevision(s.doc)
+ ;(s.doc.trail as Obj)['2026-09-12'] = row(9)
+ const hist = J([s.doc.trail, s.doc.revisions])
+ const v = restoredDoc(s.doc, 0)!
+ Object.assign(v, FORGED, { trail: { '2020-01-01': row(1) }, revisions: [] })
+ ok(restoreVersion(s, J(v)), 'Versions in this file: restores')
+ ok(text(s.doc) === 'live text', '…content is the version\'s')
+ ok(identityLive(s.doc), '…identity, modes and capability are the live ones')
+ ok(J([s.doc.trail, s.doc.revisions]) === hist, '…history is the live one (a version never installs or drops history)')
+ ok(revisionsOf(s.doc).length === 2, '…both revisions still there')
+}
+{
+ // this browser's timeline: a stored snapshot (the same verb)
+ const s = new Store(mk())
+ const older = snapOf(mk()); older.pages[0].blocks[0].html = 'an hour ago'
+ older.trail = { '2026-09-01': row(1) }; older.revisions = [{ id: 'x', at: 't', body: {} }]
+ Object.assign(older, { collab: FORGED.collab, readonly: true, template: true })
+ ok(restoreVersion(s, J(older)), 'Version history (this browser): restores')
+ ok(text(s.doc) === 'an hour ago' && identityLive(s.doc), '…content follows, identity live')
+ ok(J(s.doc.trail) === J(mk().trail) && s.doc.revisions === undefined, '…history live: no trail swap, no revisions installed')
+ // 'back': an ABSENT content field is dropped — a version is the whole document
+ const s2 = new Store(mk({ footnotes: { 1: 'live note' } }))
+ const noNotes = snapOf(mk())
+ ok(restoreVersion(s2, J(noNotes)) && s2.doc.footnotes === undefined, '…and content absent from the version is absent after it')
+ ok(s2.doc.assets?.photo === PHOTO, '…a version carries its own pool, so assets follow it')
+ s2.undo()
+ ok(J(s2.doc.footnotes) === J({ 1: 'live note' }), '⌘Z walks the version restore back')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n3. Replace from JSON (and bento.loadDoc) go BACK\n')
+{
+ const s = new Store(mk({ revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { full: 1 } }] }))
+ const hist = J([s.doc.trail, s.doc.revisions])
+ // Copy document JSON's output: no history, no collab
+ const pasted = snapOf(s.doc); delete pasted.trail; delete pasted.revisions
+ pasted.pages[0].blocks[0].html = 'pasted'
+ ok(replaceFromJson(s, J(pasted)), 'Copy JSON\'s output replaces')
+ ok(text(s.doc) === 'pasted' && identityLive(s.doc), '…content follows, identity live')
+ ok(J([s.doc.trail, s.doc.revisions]) === hist, '…a paste never DELETES history')
+ const forged = { ...snapOf(s.doc), ...FORGED, docId: 'other-space', trail: { '2020-01-01': row(1) }, revisions: [{ id: 'f', at: 't', body: {} }] }
+ ok(replaceFromJson(s, J(forged)), 'a paste carrying forged identity and history replaces content')
+ ok(identityLive(s.doc), '…but never brings docId, collab, readonly or template')
+ ok(J([s.doc.trail, s.doc.revisions]) === hist, '…and never INSTALLS a history')
+ ok(!replaceFromJson(s, 'not json') && text(s.doc) === 'pasted', 'text that is not a document applies nothing')
+ const ro = new Store(mk()); ro.readOnly = true
+ ok(!replaceFromJson(ro, J(pasted)) && text(ro.doc) === 'live text', 'a read-only store is never replaced')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n4. the assets trap: undo checkpoints omit the pool\n')
+{
+ // an image inserted the way editor.ts does it: internAsset writes the bytes,
+ // ONE commit writes the block
+ const s = new Store(mk({ assets: {} }))
+ const IMG = 'data:image/png;base64,' + 'QUJD'.repeat(64)
+ s.doc.assets!.img = IMG
+ s.commit(() => { s.doc.pages[0].blocks.push({ id: 'bi', type: 'image', src: 'asset:img' } as never) })
+ s.commit(() => { s.doc.pages[0].blocks[0].html = 'a later edit' })
+ s.undo()
+ ok(text(s.doc) === 'live text' && s.doc.pages[0].blocks.some((b) => b.id === 'bi'),
+ 'undo of a LATER edit leaves the image block')
+ ok(s.doc.assets?.img === IMG, '…and the image\'s BYTES (a checkpoint has no pool; it must not empty it)')
+ s.undo()
+ ok(!s.doc.pages[0].blocks.some((b) => b.id === 'bi'), 'undo of the image insert removes the reference')
+ ok(s.doc.assets?.img === IMG, '…but not the bytes (the pool is pruned on save, never by undo)')
+ s.redo()
+ const back = s.doc.pages[0].blocks.find((b) => b.id === 'bi')
+ ok(back?.src === 'asset:img' && s.doc.assets?.img === IMG, 'redo: the image is back WITH its bytes')
+}
+{
+ // the same bytes used on two pages: undoing the second insert keeps the first
+ const s = new Store(mk())
+ s.commit(() => { s.doc.pages[1].blocks.push({ id: 'bp', type: 'image', src: 'asset:photo' } as never) })
+ s.commit(() => { s.doc.pages[0].blocks.push({ id: 'bq', type: 'image', src: 'asset:photo' } as never) })
+ s.undo()
+ ok(!s.doc.pages[0].blocks.some((b) => b.id === 'bq') && s.doc.pages[1].blocks.some((b) => b.src === 'asset:photo'),
+ 'undo of a second use removes that reference only')
+ ok(s.doc.assets?.photo === PHOTO, '…and the bytes the other page still uses stay')
+ s.undo()
+ ok(s.doc.assets?.photo === PHOTO, 'undo of the first use too: bytes stay (unchanged from before the kernel took over)')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n5. crash recovery goes RECOVER\n')
+{
+ // identity, modes and capability: still live
+ const s = new Store(mk())
+ const snap = { ...snapOf(mk()), ...FORGED }
+ snap.pages[0].blocks[0].html = 'lost in the crash'
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }), 'the banner\'s Restore applies')
+ ok(text(s.doc) === 'lost in the crash', '…content follows the snapshot')
+ ok(identityLive(s.doc), '…identity, modes and capability stay live')
+ s.undo()
+ ok(text(s.doc) === 'live text', '⌘Z walks a recovery back')
+}
+{
+ // revisions: follow the snapshot when present
+ const live = mk({ revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }] })
+ const snap = snapOf(live)
+ snap.revisions = [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }, { id: 'r1', at: '2026-09-15T13:00:00Z', body: { a: 2 } }]
+ snap.pages[0].blocks[0].html = 'x'
+ const s = new Store(live)
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }) && J(s.doc.revisions) === J(snap.revisions),
+ 'revisions FOLLOW the snapshot when it carries a READABLE list')
+ const live2 = mk({ revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }] })
+ const snap2 = snapOf(live2); delete snap2.revisions; snap2.pages[0].blocks[0].html = 'y'
+ const s2 = new Store(live2)
+ ok(recoverInto(s2, { json: J(snap2), at: LIVE_MS + HOUR }) && !Object.hasOwn(s2.doc, 'revisions'),
+ 'revisions ABSENT from the (whole) snapshot were CLEARED: the key is removed')
+}
+{
+ // a recovery snapshot is foreign input: a list with ONE entry this build
+ // cannot read must not replace the live, readable log (revisionsRecover)
+ const LIVE_REVS = [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }, { id: 'r1', at: '2026-09-02T00:00:00Z', body: { a: 2 } }]
+ const good = (id: string, at: string) => ({ id, at, body: { a: 3 } })
+ const cases: Array<[string, unknown]> = [
+ ['ONE entry missing its body beside valid ones', [...LIVE_REVS, good('r2', '2026-09-15T13:00:00Z'), { id: 'bad', at: '2026-09-15T14:00:00Z' }]],
+ ['ONE entry with a bad `at` beside valid ones', [good('r2', '2026-09-15T13:00:00Z'), { id: 'bad', at: 42, body: {} }]],
+ ['ONE entry with an unreadable page patch', [good('r2', '2026-09-15T13:00:00Z'), { id: 'bad', at: '2026-09-15T14:00:00Z', body: { pages: [{ put: 'x' }] } }]],
+ ['`revisions` that is not an array', { r0: good('r0', '2026-09-15T13:00:00Z') }],
+ ]
+ for (const [what, revs] of cases) {
+ const live = mk({ revisions: clone(LIVE_REVS), trail: { '2026-09-10': row(5) } })
+ const before = J(live.revisions)
+ const snap = snapOf(live)
+ snap.revisions = revs
+ snap.trail = { '2026-09-12': row(7) }
+ snap.pages[0].blocks[0].html = 'recovered anyway'
+ const s = new Store(live)
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }), `foreign revisions (${what}): the recovery still applies`)
+ ok(J(s.doc.revisions) === before, `…the LIVE list is kept byte-for-byte`)
+ ok(text(s.doc) === 'recovered anyway' && J(Object.keys(s.doc.trail as Obj).sort()) === J(['2026-09-10', '2026-09-12']),
+ '…while the content and the trail merge still apply')
+ }
+ {
+ // no live list + a foreign incoming one: nothing is installed
+ const live = mk()
+ const snap = snapOf(live)
+ snap.revisions = [{ id: 'bad', at: 7 }]
+ snap.pages[0].blocks[0].html = 'no history here'
+ const s = new Store(live)
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }) && text(s.doc) === 'no history here', 'live with no revisions + a foreign recovered list: the recovery applies')
+ ok(!Object.hasOwn(s.doc, 'revisions'), '…and the revisions key stays ABSENT')
+ }
+ ok(revisionsRecover(undefined, [{ id: 'x' }]) === undefined && revisionsRecover(LIVE_REVS, 'junk') === LIVE_REVS,
+ 'revisionsRecover refuses a foreign list WHOLE and never merges')
+}
+{
+ // CLEARED STAYS CLEARED. Clear history deletes the key; autosave then files
+ // the doc without it (kernel contentOnly = the doc minus collab); the file
+ // on disk still carries the old drafts. Restore must not bring them back.
+ const DRAFTS = [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }, { id: 'r1', at: '2026-09-02T00:00:00Z', body: { a: 2 } }]
+ const session = new Store(mk({ revisions: clone(DRAFTS) }))
+ ok(clearHistory(session.doc) && !('revisions' in session.doc), 'the real clearHistory deletes the key')
+ session.commit(() => { session.doc.pages[0].blocks[0].html = 'edited after clearing' })
+ const contentOnly = (d: SpacesDoc) => { const { collab: _c, ...rest } = d as Obj; void _c; return J(rest) }
+ const snapJson = contentOnly(session.doc)
+ const reopened = new Store(mk({ revisions: clone(DRAFTS) })) // the file still has them
+ ok(recoveryOffered(snapJson, reopened.doc, LIVE_MS + HOUR), 'the banner is offered for the crash copy')
+ ok(recoverInto(reopened, { json: snapJson, at: LIVE_MS + HOUR }), 'Restore applies')
+ ok(!('revisions' in reopened.doc), 'CLEARED STAYS CLEARED: after Restore there is NO revisions key')
+ ok(text(reopened.doc) === 'edited after clearing' && J(Object.keys(reopened.doc.trail as Obj).sort()) === J(Object.keys(mk().trail as Obj).sort()),
+ '…and the content and the trail come back as usual')
+ // an explicit [] means the same
+ const s2 = new Store(mk({ revisions: clone(DRAFTS) }))
+ const withEmpty = snapOf(mk()); withEmpty.revisions = []; withEmpty.pages[0].blocks[0].html = 'e'
+ ok(recoverInto(s2, { json: J(withEmpty), at: LIVE_MS + HOUR }) && !('revisions' in s2.doc), 'an incoming [] is cleared too: no key, never `revisions: []`')
+ // the normalisation itself
+ ok(J((asWholeRecovery({ ...mk(), revisions: undefined } as SpacesDoc) as Obj).revisions) === '[]', 'asWholeRecovery states an absent revisions as []')
+ const has = mk({ revisions: clone(DRAFTS) })
+ ok(asWholeRecovery(has) === has, '…and leaves a snapshot that carries revisions untouched')
+ // a FOREIGN LIVE list is never written over by a readable recovered one
+ const foreignLive = [{ id: 'future', at: '2026-09-01T00:00:00Z', body: { v9: true, pages: 'a newer shape' } }]
+ const s3 = new Store(mk({ revisions: clone(foreignLive) }))
+ const before3 = J(s3.doc.revisions)
+ const readableSnap = snapOf(mk()); readableSnap.revisions = clone(DRAFTS); readableSnap.pages[0].blocks[0].html = 'f'
+ ok(recoverInto(s3, { json: J(readableSnap), at: LIVE_MS + HOUR }) && J(s3.doc.revisions) === before3,
+ 'a FOREIGN live list + a readable recovered one → the live list is kept byte-for-byte')
+ // readable over readable still follows
+ const s4 = new Store(mk({ revisions: [DRAFTS[0]] }))
+ ok(recoverInto(s4, { json: J({ ...snapOf(mk()), revisions: DRAFTS }), at: LIVE_MS + HOUR }) && J(s4.doc.revisions) === J(DRAFTS),
+ 'a readable recovered list over a readable live one still FOLLOWS')
+ // the hook's order, directly
+ ok(revisionsRecover(DRAFTS, []) === undefined, 'hook rule 1: [] → undefined (key removed)')
+ ok(revisionsRecover(foreignLive, DRAFTS) === foreignLive, 'hook rule 3: a foreign live list → live')
+ // 'back' is unaffected: history stays live, and a paste after a clear
+ // resurrects nothing
+ const b = new Store(mk({ revisions: clone(DRAFTS) }))
+ clearHistory(b.doc)
+ const pasted = snapOf(mk({ revisions: clone(DRAFTS) })); pasted.pages[0].blocks[0].html = 'pasted'
+ ok(replaceFromJson(b, J(pasted)) && !('revisions' in b.doc), 'Replace from JSON after a clear does not resurrect the drafts (history stays live: none)')
+ const v = new Store(mk({ revisions: clone(DRAFTS) }))
+ const noRevs = snapOf(mk()); noRevs.pages[0].blocks[0].html = 'version'
+ ok(restoreVersion(v, J(noRevs)) && J(v.doc.revisions) === J(DRAFTS), 'a version restore with no revisions keeps the live history (\'back\' is untouched)')
+ v.commit(() => { v.doc.pages[0].blocks[0].html = 'after' }); v.undo()
+ ok(J(v.doc.revisions) === J(DRAFTS), '…and undo keeps it too')
+}
+{
+ // trail through the real banner path: the hook unions by day
+ const live = mk({ trail: { '2026-09-10': row(5), '2026-09-11': row(6), '2026-09-14': row(9) } })
+ const snap = snapOf(live)
+ snap.trail = { '2026-09-11': row(60), '2026-09-12': row(7) }
+ const s = new Store(live)
+ ok(recoveryOffered(J(snap), live, LIVE_MS + HOUR), 'a snapshot whose trail adds a day raises the banner')
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }), 'and Restore applies')
+ ok(J(Object.keys(s.doc.trail as Obj).sort()) === J(['2026-09-10', '2026-09-11', '2026-09-12', '2026-09-14']),
+ 'the trail is the per-day UNION through recoverInto (both sides\' days)')
+ ok((s.doc.trail as Obj)['2026-09-11'].n.todo === 60, '…a newer snapshot wins the shared day')
+ // a snapshot whose trail is a SUBSET of the file's, nothing else different
+ const sub = snapOf(live); sub.trail = { '2026-09-10': row(5) }
+ ok(!recoveryOffered(J(sub), live, LIVE_MS - HOUR), 'an older snapshot holding only days the file has raises no banner')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n5b. a recovery removes what was removed (wholeSnapshot)\n')
+{
+ // the file still has a design, footnotes, a journal template and a key from
+ // a newer build; the crash copy (taken after the person removed all four)
+ // has none of them, and carries no history at all
+ const live = mk({
+ design: 'ledger', footnotes: { 1: 'a note' }, journalTemplate: 't1', futureKey: { from: 'newer' },
+ revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }],
+ })
+ const snap = snapOf(mk())
+ delete snap.trail; delete snap.revisions
+ snap.pages[0].blocks[0].html = 'after removing them'
+ Object.assign(snap, { readonly: true, template: true, collab: FORGED.collab })
+ const s = new Store(live)
+ const histBefore = J([s.doc.trail, s.doc.revisions])
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }), 'recoverInto applies the crash copy')
+ const d = s.doc as SpacesDoc & Obj
+ ok(!('design' in d) && !('footnotes' in d) && !('journalTemplate' in d),
+ 'a design, footnotes and journal template REMOVED after the last save stay removed after recovery')
+ ok(!('futureKey' in d), 'an UNKNOWN top-level key absent from the snapshot is removed too')
+ ok(J(d.trail) === J(JSON.parse(histBefore)[0]), 'an absent trail in the snapshot KEEPS the live rows')
+ ok(!('revisions' in d), 'an absent revisions in the snapshot means cleared: no key')
+ ok(identityLive(d), 'the identity / mode / capability floor is unchanged')
+ ok(!recoveryOffered(J(snapOf(live)), live, LIVE_MS + HOUR), 'a snapshot identical to the file still raises no banner')
+ ok(recoveryOffered(J(snap), live, LIVE_MS + HOUR), 'a snapshot that removed fields raises it')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n6. trailRecover: the four rows, and the edges\n')
+{
+ const L: Trail = { '2026-09-10': row(5), '2026-09-11': row(6), '2026-09-14': row(9) }
+ // 1. an OLDER snapshot keeps the live later days (and live wins shared ones)
+ const older = trailRecover(L, { '2026-09-10': row(50), '2026-09-11': row(60) }, { live: LIVE_MS, incoming: LIVE_MS - HOUR }) as Trail
+ ok(older['2026-09-14']?.n.todo === 9, 'row 1: an OLDER snapshot keeps the live later days')
+ ok(older['2026-09-10'].n.todo === 5 && older['2026-09-11'].n.todo === 6, 'row 1: …and the live side wins every shared day')
+ // 2. a NEWER snapshot wins its shared days
+ const newer = trailRecover(L, { '2026-09-11': row(60), '2026-09-15': row(10) }, { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(newer['2026-09-11'].n.todo === 60, 'row 2: a NEWER snapshot wins its shared days')
+ ok(newer['2026-09-10'].n.todo === 5 && newer['2026-09-14'].n.todo === 9 && newer['2026-09-15'].n.todo === 10,
+ 'row 2: …and every day on one side only is kept')
+ // 3. a snapshot WITHOUT trail leaves live intact (through the real path:
+ // since kernel #726 a whole snapshot removes an absent history key, and
+ // RECOVER_RULES opts trail out — keepLiveWhenAbsent: ['trail'])
+ const live = mk({ trail: clone(L) })
+ const snap = snapOf(live); delete snap.trail; snap.pages[0].blocks[0].html = 'z'
+ const s = new Store(live)
+ ok(recoverInto(s, { json: J(snap), at: LIVE_MS + HOUR }) && J(s.doc.trail) === J(L),
+ 'row 3: a snapshot WITHOUT a trail leaves the live trail intact')
+ // the opt-out is trail's ONLY: in the SAME whole snapshot, absent revisions
+ // are still removed (cleared), and the trail is kept byte-for-byte
+ {
+ const live2 = mk({ trail: clone(L), revisions: [{ id: 'r0', at: '2026-09-01T00:00:00Z', body: { a: 1 } }] })
+ const trailBytes = J(live2.trail)
+ const snap2 = snapOf(live2); delete snap2.trail; delete snap2.revisions; snap2.pages[0].blocks[0].html = 'whole, no history'
+ const s2 = new Store(live2)
+ ok(recoverInto(s2, { json: J(snap2), at: LIVE_MS + HOUR }), 'a whole recovery snapshot with NO trail and NO revisions applies')
+ ok(J(s2.doc.trail) === trailBytes, '…the live trail is kept byte-for-byte (keepLiveWhenAbsent: trail)')
+ ok(!Object.hasOwn(s2.doc, 'revisions'), '…while the absent revisions are still REMOVED (cleared stays cleared)')
+ }
+ // tie → live
+ const tie = trailRecover(L, { '2026-09-11': row(60) }, { live: LIVE_MS, incoming: LIVE_MS }) as Trail
+ ok(tie['2026-09-11'].n.todo === 6, 'a TIE keeps live')
+ // live time unknown, incoming known → incoming
+ const unknownLive = trailRecover(L, { '2026-09-11': row(60) }, { live: undefined, incoming: LIVE_MS }) as Trail
+ ok(unknownLive['2026-09-11'].n.todo === 60, 'live with no modified vs a defined snapshot time → incoming wins shared days')
+ const bothUnknown = trailRecover(L, { '2026-09-11': row(60) }, {}) as Trail
+ ok(bothUnknown['2026-09-11'].n.todo === 6, '…and with neither time known, live keeps them')
+ // and through the real path, a live space with no modified
+ const nm = mk({ trail: clone(L) }); delete nm.modified
+ const nmSnap = snapOf(nm); nmSnap.trail = { '2026-09-11': row(60) }; nmSnap.pages[0].blocks[0].html = 'q'
+ const s2 = new Store(nm)
+ ok(recoverInto(s2, { json: J(nmSnap), at: LIVE_MS }) && (s2.doc.trail as Obj)['2026-09-11'].n.todo === 60,
+ '…through recoverInto too (a file with no modified is OLDER than its snapshot)')
+}
+{
+ // 4. bucket rows vs single days: never count a day twice
+ const covered = (t: Trail, series = '') => {
+ const days = new Map<number, number>()
+ for (const k of Object.keys(t)) {
+ const a = parseTrailKey(k); if (!a || a.series !== series) continue
+ const end = dayIndex(a.day)
+ for (let d = end - spanOf(t[k]) + 1; d <= end; d++) days.set(d, (days.get(d) ?? 0) + 1)
+ }
+ return days
+ }
+ const once = (t: Trail, series = '') => [...covered(t, series).values()].every((n) => n === 1)
+ // live thinned the week of 2026-09-07..13 to its last row (s = 7); the
+ // snapshot (older) still holds three single days inside that week
+ const liveT: Trail = { '2026-09-13': row(20, { s: 7 }), '2026-09-14': row(21) }
+ const snapT: Trail = { '2026-09-08': row(1), '2026-09-09': row(2), '2026-09-12': row(3), '2026-09-01': row(9) }
+ const a = trailRecover(liveT, snapT, { live: LIVE_MS, incoming: LIVE_MS - HOUR }) as Trail
+ ok(once(a), `row 4: a live bucket + snapshot single days inside it count every day ONCE (${J(Object.keys(a).sort())})`)
+ ok(a['2026-09-13']?.s === 7 && !a['2026-09-08'] && !a['2026-09-09'] && !a['2026-09-12'],
+ 'row 4: …the bucket stands, the single days inside its span are dropped')
+ ok(a['2026-09-01']?.n.todo === 9 && a['2026-09-14']?.n.todo === 21, 'row 4: …days outside the span are kept')
+ // the mirror: the bucket arrives from the snapshot, singles are live's
+ const b = trailRecover({ '2026-09-08': row(1), '2026-09-12': row(3) }, { '2026-09-13': row(20, { s: 7 }) },
+ { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(once(b) && b['2026-09-13']?.s === 7 && !b['2026-09-08'] && !b['2026-09-12'], 'row 4: …and the same from the other side')
+ // two overlapping buckets (a weekly and a monthly thinning) never double-count either
+ const c = trailRecover({ '2026-09-30': row(30, { s: 30 }) }, { '2026-09-13': row(20, { s: 7 }), '2026-10-02': row(1) },
+ { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(once(c) && !!c['2026-09-30'] && !c['2026-09-13'] && !!c['2026-10-02'], 'row 4: overlapping buckets resolve to one claim per day')
+ // within budget: a union of two full trails is pruned
+ const big = (from: number, n: number, todo: number): Trail => {
+ const t: Trail = {}
+ for (let i = 0; i < n; i++) {
+ const d = new Date(Date.UTC(2025, 0, 1) + (from + i) * 86400000).toISOString().slice(0, 10)
+ t[d] = { n: { todo: todo + i, doing: 3, done: i }, e: { todo: 13, doing: 5, done: 8 }, x: 1 }
+ }
+ return t
+ }
+ const bl = pruneTrail(big(0, 300, 0)), bi = pruneTrail(big(150, 300, 1000))
+ const u = trailRecover(bl, bi, { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(J(u).length <= TRAIL_BUDGET && Object.keys(u).length <= TRAIL_MAX,
+ `row 4: the union of two full trails is within budget (${J(u).length} B ≤ ${TRAIL_BUDGET}, ${Object.keys(u).length} rows)`)
+ ok(once(u), 'row 4: …and after pruning still counts every day once')
+}
+{
+ // series keys never cross-match
+ const liveT: Trail = { '2026-09-11': row(6), 'sprint/2026-09-13': row(20, { s: 7 }) }
+ const snapT: Trail = { 'sprint/2026-09-11': row(66), '2026-09-12': row(7) }
+ const r = trailRecover(liveT, snapT, { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(r['2026-09-11']?.n.todo === 6 && r['2026-09-12']?.n.todo === 7,
+ 'a sprint bucket never drops a DEFAULT-series day inside its span')
+ ok(!r['sprint/2026-09-11'] && !!r['sprint/2026-09-13'], '…while it does drop its own series\' single day')
+ const r2 = trailRecover({ '2026-09-11': row(6) }, { 'sprint/2026-09-11': row(66) }, { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Trail
+ ok(r2['2026-09-11'].n.todo === 6 && r2['sprint/2026-09-11'].n.todo === 66, 'the same day in two series is two keys, both kept')
+}
+{
+ // edges: foreign shapes, unknown keys, prototype keys
+ const L: Trail = { '2026-09-11': row(6) }
+ ok(trailRecover(undefined, L, {}) === L, 'live has no trail → the snapshot\'s is taken')
+ ok(trailRecover('a future shape', L, { incoming: LIVE_MS + HOUR }) === 'a future shape', 'a foreign live trail is never written over')
+ ok(trailRecover(L, ['x'], { incoming: LIVE_MS + HOUR }) === L, 'a foreign incoming trail never replaces a readable one')
+ const fut = trailRecover(L, { 'a/b/2026-09-11': row(1), '2026-09-11': row(60) }, { live: LIVE_MS, incoming: LIVE_MS + HOUR }) as Obj
+ ok(fut['a/b/2026-09-11']?.n.todo === 1 && fut['2026-09-11'].n.todo === 60, 'a key this build cannot read rides along untouched')
+ const evil = JSON.parse('{"__proto__":{"polluted":true},"2026-09-12":{"n":{"todo":1}}}')
+ const pe = trailRecover(L, evil, { incoming: LIVE_MS + HOUR }) as Obj
+ ok(Object.getPrototypeOf(pe) === Object.prototype && ({} as Obj).polluted === undefined && pe['2026-09-12'], 'a __proto__ key is never assigned')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n7. the gate still runs first, in both directions\n')
+{
+ const live = mk()
+ const other = snapOf(live); other.docId = 'someone-else'
+ ok(!gateRestored(J(other), live, 'recover', LIVE_MS).ok && !gateRestored(J(other), live, 'back').ok,
+ 'a snapshot naming another space is refused before any merge')
+ const s = new Store(mk())
+ ok(!recoverInto(s, { json: J(other), at: LIVE_MS + HOUR }) && !s.canUndo, '…and recoverInto applies nothing')
+ const hostile = snapOf(live); hostile.pages[0].blocks[0].html = 'hi<img src=x onerror="alert(1)">'
+ ok(recoverInto(s, { json: J(hostile), at: LIVE_MS + HOUR }) && !/onerror/.test(text(s.doc)), 'recovered html is sanitized')
+}
+
+// ---------------------------------------------------------------------------
+console.log('\n8. every entry point names its direction\n')
+{
+ const root = process.cwd()
+ const src = (f: string) => readFileSync(join(root, f), 'utf8')
+ const gate = src('spaces/src/restoregate.ts')
+ const main = src('spaces/src/main.ts')
+ const cmds = src('spaces/src/doccmds.ts')
+ const store = src('spaces/src/store.ts')
+ ok(/function recoverInto\([^)]*\)[^{]*\{\s*return restoreInto\(store, snap\.json, 'recover', snap\.at\)/.test(gate), 'recoverInto → \'recover\', timed by the snapshot')
+ ok(/function restoreVersion\([^)]*\)[^{]*\{\s*return restoreInto\(store, json, 'back'\)/.test(gate), 'restoreVersion → \'back\'')
+ ok(/function replaceFromJson[\s\S]{0,400}?store\.replaceDoc\(res\.doc, 'back'\)/.test(gate), 'replaceFromJson → \'back\'')
+ const offer = main.slice(main.indexOf('async function offerRecovery('))
+ ok(/recoverInto\(store, snap\)/.test(offer), 'the recovery banner restores through recoverInto')
+ ok(/loadDoc: \(json: string\)[\s\S]{0,300}?replaceFromJson\(store, json\)/.test(main), 'bento.loadDoc goes through replaceFromJson')
+ ok(/replaceFromJson\(h\.store, ta\.value\)/.test(cmds), 'Replace from JSON goes through replaceFromJson')
+ ok((cmds.match(/restoreVersion\(h\.store, /g) ?? []).length === 2, 'both version timelines go through restoreVersion')
+ const calls = (main + cmds).match(/\.replaceDoc\(/g) ?? []
+ ok(calls.length === 0, 'no app file calls replaceDoc directly (only restoregate.ts does)')
+ ok(!/keepLiveIdentity|keepLiveHistory/.test(store + gate), 'no hand-rolled keep-live remains in store.ts or restoregate.ts')
+ ok(/applyRestore\(this\.doc, JSON\.parse\(entry\.json\) as SpacesDoc, 'back', UNDO_RULES\)/.test(store), 'undo/redo: one applyRestore, \'back\', with the undo-only rules')
+ ok(/keepLive: \{ assets: 'live' \}/.test(store), '…whose only override is the assets pool')
+ ok(/RECOVER_RULES: RestoreRules = \{\s*\.\.\.RESTORE_RULES,\s*wholeSnapshot: true,[\s\S]{0,800}?keepLiveWhenAbsent: \['trail'\],\s*\}/.test(store),
+ 'the recovery rules state wholeSnapshot: true and keepLiveWhenAbsent: [\'trail\'] in source')
+ ok(/recover: \{ trail: trailRecover, revisions: revisionsRecover \}/.test(store), 'both recover hooks are bound in source')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-spaces-trail.ts b/scripts/test-spaces-trail.ts
index e67a25b5..e2d096f9 100644
--- a/scripts/test-spaces-trail.ts
+++ b/scripts/test-spaces-trail.ts
@@ -677,13 +677,13 @@ const tracker = () => {
const rows = Object.keys(trailOf(store.doc)).sort().join(',')
const pasted = docForExport(store.doc)
ok(pasted.trail === undefined, 'Copy document JSON carries no trail')
- store.replaceDoc(JSON.parse(JSON.stringify(pasted)) as SpacesDoc)
+ store.replaceDoc(JSON.parse(JSON.stringify(pasted)) as SpacesDoc, 'back')
ok(Object.keys(trailOf(store.doc)).sort().join(',') === rows,
'replaceDoc keeps the LIVE trail — Replace from JSON does not wipe it')
// and a pasted doc carrying a DIFFERENT trail cannot overwrite the live one
const forged = JSON.parse(JSON.stringify(store.doc)) as SpacesDoc
forged.trail = { '2020-01-01': { n: { todo: 999 } } }
- store.replaceDoc(forged)
+ store.replaceDoc(forged, 'back')
ok(trailOf(store.doc)['2020-01-01'] === undefined && Object.keys(trailOf(store.doc)).sort().join(',') === rows,
'a restored or pasted trail never replaces the live record')
}
diff --git a/scripts/test-spaces-undo.ts b/scripts/test-spaces-undo.ts
index c1f73460..3e7ab249 100644
--- a/scripts/test-spaces-undo.ts
+++ b/scripts/test-spaces-undo.ts
@@ -351,7 +351,7 @@ console.log('bento/spaces undo\n')
;(foreign as Record<string, unknown>).collab = { v: 2, room: 'w-theirs', key: 'kx', on: true }
foreign.readonly = true
foreign.template = true
- s.replaceDoc(foreign)
+ s.replaceDoc(foreign, 'back')
ok(textOf(s, 'z') === 'Z0', 'replaceDoc: the content is replaced')
ok(s.doc.docId === 'u' && room(s) === 'w-room1' && on(s) === false,
'replaceDoc: docId and collab (incl. its off switch) stay the live ones')
diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjs
index 17c9c9c5..7618a027 100755
--- a/scripts/test-spaces.mjs
+++ b/scripts/test-spaces.mjs
@@ -74,6 +74,7 @@ const RIGS = [
{ name: 'reading', file: 'scripts/test-spaces-reading.ts', bundle: true },
{ name: 'md-strict', file: 'scripts/test-spaces-md-strict.ts', bundle: true },
{ name: 'restore-gate', file: 'scripts/test-spaces-restore-gate.ts', bundle: true },
+ { name: 'restore', file: 'scripts/test-spaces-restore.ts', tzs: TZS_TRAIL, bundle: true },
{ name: 'history', file: 'scripts/test-spaces-history.ts', bundle: true },
{ name: 'mentions', file: 'scripts/test-spaces-mentions.ts' },
{ name: 'size', file: 'scripts/test-spaces-size.mjs' },
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 8df05328..d78fed67 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -1354,6 +1354,14 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
square, sunken box. In dark theme, the **Replace from JSON** box was white,
and the link card, view filter and Add property fields sat on a different
shade from the rest.
+- **Restoring after a crash keeps the progress record from both copies.**
+ When the "Unsaved changes from a previous session" banner restores, every
+ day recorded in either the file or the recovered copy is kept. If both have
+ the same day, the newer copy's reading wins. A day is never counted twice
+ when one copy has thinned older days into weekly or monthly rows. Version
+ history comes back with the recovered copy. If you cleared the version
+ history before the crash, it stays cleared. Undo, restoring a version and
+ pasting document JSON still leave both records exactly as they are.
## [0.1.0] — 2026-08-03
diff --git a/spaces/src/doccmds.ts b/spaces/src/doccmds.ts
index dedbb2f0..1799f997 100644
--- a/spaces/src/doccmds.ts
+++ b/spaces/src/doccmds.ts
@@ -26,8 +26,8 @@ import type { Dialog } from '../../kernel/src/ui/dialog.ts'
import { t } from './i18n'
import { ICONS } from './icons'
import { row, type Menu } from './menus.ts'
-import { docForExport, parseDoc, uid, type SpacesDoc } from './model'
-import { restoreInto } from './restoregate'
+import { docForExport, uid, type SpacesDoc } from './model'
+import { restoreVersion, replaceFromJson } from './restoregate'
import {
revisionsOf, historyIsForeign, changesAt, restoredDoc, clearHistory, historyBytes,
tooLargeForHistory, type ChangeReport,
@@ -213,9 +213,10 @@ function openHistory(h: DocHost): void {
// every file:// document shares this IndexedDB. A refusal applies
// nothing and leaves the entry where it is.
if (h.store.readOnly) { h.notice(t('This file is open read-only')); return }
- // replaceDoc (inside restoreInto) checkpoints undo first, so ⌘Z walks
- // this back — the same contract the recovery banner's Restore honours.
- if (!restoreInto(h.store, v.json)) { h.notice(t('That version could not be read')); return }
+ // replaceDoc (inside restoreVersion) checkpoints undo first, so ⌘Z
+ // walks this back — the same contract the recovery banner's Restore
+ // honours. A version goes BACK: its content, the live history.
+ if (!restoreVersion(h.store, v.json)) { h.notice(t('That version could not be read')); return }
h.repaint()
close()
h.notice(t('Restored the version from {when} — ⌘Z undoes it', { when }))
@@ -234,7 +235,7 @@ function openHistory(h: DocHost): void {
*
* A row's summary is DERIVED here, in the reader's language, from the patch;
* the file stores no sentence. Restore goes through the same gate as the
- * browser-local timeline (restoregate.ts restoreInto): the version is the
+ * browser-local timeline (restoregate.ts restoreVersion): the version is the
* document's own, but what is applied is still parsed, sanitized and given the
* live identity, and replaceDoc checkpoints undo so ⌘Z walks it back.
*/
@@ -268,7 +269,7 @@ function openFileHistory(h: DocHost): void {
b.addEventListener('click', () => {
if (h.store.readOnly) { h.notice(t('This file is open read-only')); return }
const next = restoredDoc(h.store.doc, i)
- if (!next || !restoreInto(h.store, JSON.stringify(next))) { h.notice(t('That version could not be read')); return }
+ if (!next || !restoreVersion(h.store, JSON.stringify(next))) { h.notice(t('That version could not be read')); return }
h.repaint()
close()
h.notice(t('Restored the version from {when} — ⌘Z undoes it', { when }))
@@ -361,17 +362,16 @@ function openReplaceJson(h: DocHost): void {
ta.placeholder = t('Paste document JSON here…')
body.append(ta)
const apply = button(t('Replace'), () => {
- const res = parseDoc(ta.value)
- if (!res.ok) {
+ // The live session belongs to THIS document, not to the pasted text:
+ // replaceFromJson parses and applies going BACK (restoregate.ts), so the
+ // live docId, collab, file mode and history all stay — for this and
+ // bento.loadDoc alike.
+ if (!replaceFromJson(h.store, ta.value)) {
ta.classList.add('sp-ab-bad')
apply.textContent = t('That is not a bento/spaces document')
setTimeout(() => { apply.textContent = t('Replace') }, 2000)
return
}
- // The live session belongs to THIS document, not to the pasted text:
- // replaceDoc keeps the live docId, collab and file mode itself
- // (store.ts FROM_LIVE), for this and every other whole-document restore.
- h.store.replaceDoc(res.doc)
h.repaint()
close()
h.notice(t('Document replaced — ⌘Z undoes'))
diff --git a/spaces/src/history.ts b/spaces/src/history.ts
index d94378be..173117b5 100644
--- a/spaces/src/history.ts
+++ b/spaces/src/history.ts
@@ -240,6 +240,36 @@ export function historyIsForeign(doc: SpacesDoc): boolean {
return !Array.isArray(r) || !r.every(readable)
}
+/**
+ * The `revisions` RECOVER HOOK (kernel docfields.ts `RecoverHook`), bound in
+ * store.ts `RESTORE_RULES` and consulted only by the crash-recovery banner
+ * ('recover'), only when the snapshot carries the key. In this ORDER:
+ *
+ * 1. `[]` — CLEARED. restoregate.ts `asWholeRecovery` turns a snapshot with
+ * NO `revisions` into `[]` before the kernel sees it (the snapshot is the
+ * whole document, so absence means the person ran Clear history). Return
+ * `undefined` so the key is REMOVED, exactly as Clear history deletes it
+ * and never stores `[]`. Cleared stays cleared: otherwise drafts somebody
+ * cleared before sharing came back with Restore and left in the next copy
+ * — confidentiality beats integrity behind a banner the person accepted.
+ * 2. FOREIGN incoming — not an array, or any entry failing `readable` (the
+ * check a file's list passes, `historyIsForeign`) → keep LIVE. A recovery
+ * snapshot is foreign input (file:// documents share its IndexedDB); one
+ * unreadable entry used to replace the live, readable log.
+ * 3. FOREIGN live → keep LIVE. A foreign list is never written over (#671),
+ * which also preserves a newer build's history.
+ * 4. Otherwise the readable recovered list FOLLOWS the snapshot — the crash
+ * case: a revision a save wrote into the snapshot must survive.
+ *
+ * It never merges and never picks entries: a list is taken or refused WHOLE.
+ */
+export function revisionsRecover(live: unknown, incoming: unknown): unknown {
+ if (Array.isArray(incoming) && incoming.length === 0) return undefined
+ if (!Array.isArray(incoming) || !incoming.every(readable)) return live
+ if (live !== undefined && (!Array.isArray(live) || !live.every(readable))) return live
+ return incoming
+}
+
/** `doc.revisions`, when this build can read every entry of it; else none. */
export function revisionsOf(doc: SpacesDoc): SpacesRevision[] {
const r = (doc as { revisions?: unknown }).revisions
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index 8f968fa2..875eea36 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -23,7 +23,7 @@ import { APP_VERSION, applyUpdateInPlace } from '../../kernel/src/update.ts'
import { t, locale, applyDirection } from './i18n'
import { i18nApi } from '../../kernel/src/i18n.ts'
import { parseDoc, uid, newPage, type SpacesDoc, type ParseResult } from './model'
-import { recoveryOffered, restoreInto } from './restoregate'
+import { recoveryOffered, recoverInto, replaceFromJson } from './restoregate'
import { recordTrail } from './observe.ts'
import { protectedDays } from './periods.ts'
import {
@@ -662,9 +662,8 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
},
loadDoc: (json: string): boolean => {
if (store.readOnly) return false
- const r = parseDoc(json)
- if (!r.ok) return false
- store.replaceDoc(r.doc)
+ // Replace from JSON's own path ('back': content, never identity or history)
+ if (!replaceFromJson(store, json)) return false
editor.repaint()
return true
},
@@ -735,12 +734,14 @@ function banner(text: string, actions: Array<[string, () => void]> = []): void {
async function offerRecovery(doc: SpacesDoc, store: Store, editor: Editor): Promise<void> {
if (store.readOnly) return // a reading copy, a view-only follower or a frozen file is never rewritten
const snap = await getRecovery(doc.docId)
- if (!snap || !recoveryOffered(snap.json, doc)) return
+ if (!snap || !recoveryOffered(snap.json, doc, snap.at)) return
banner(t('Unsaved changes from a previous session were found.'), [
[t('Restore'), () => {
- // re-gated against the space as it is NOW (restoreInto). A refusal
+ // re-gated against the space as it is NOW (recoverInto). A refusal
// applies nothing and keeps the entry; only Discard deletes it.
- if (!restoreInto(store, snap.json)) { editor.status(t('That version could not be read')); return }
+ // 'recover': the snapshot is a newer copy of this space, so its history
+ // is reconciled (trail unioned by day) rather than kept from the file.
+ if (!recoverInto(store, snap)) { editor.status(t('That version could not be read')); return }
editor.repaint()
}],
[t('Discard'), () => { void clearRecovery(doc.docId) }],
diff --git a/spaces/src/restoregate.ts b/spaces/src/restoregate.ts
index 3fb54379..081cdb9c 100644
--- a/spaces/src/restoregate.ts
+++ b/spaces/src/restoregate.ts
@@ -23,9 +23,18 @@
// and the Markdown import put on arriving blocks — render sanitizes the
// same html again, so what a reader SEES is what a file open shows;
// · identity and capability (store.ts FROM_LIVE: docId, collab, readonly,
-// template) are the OPEN space's, never the snapshot's. replaceDoc applies
-// that too; it is applied here as well so the gate's output is already the
-// document that will be installed, and the recovery check compares that.
+// template) are the OPEN space's, never the snapshot's. That is decided by
+// ONE call — the kernel's `applyRestore` over store.ts rulesFor(direction) —
+// inside store.replaceDoc, AFTER this gate has run. `gateRestored` runs the
+// same call only to SHOW what would be installed (the recovery check
+// compares that); `restoreInto` hands the gated, not-yet-merged document
+// to replaceDoc, so nothing is merged twice.
+//
+// THE DIRECTION is the caller's, and each entry point below names its own:
+// · recoverInto — the crash-recovery banner: 'recover', timed by the
+// snapshot (history reconciled; trail unioned by day);
+// · restoreVersion — either version timeline: 'back' (history kept live);
+// · replaceFromJson — Replace from JSON and bento.loadDoc: 'back'.
//
// What it deliberately does NOT do that slides' gate does: drop unknown keys.
// The spaces format is additive — a file open keeps every field it does not
@@ -36,8 +45,8 @@
import { parseDoc, docContentKey, type SpacesDoc } from './model.ts'
import { sanitizeInline } from './sanitize.ts'
-import type { Store } from './store.ts'
-import { keepLiveIdentity } from '../../kernel/src/docfields.ts'
+import { rulesFor, restoreAt, type Store } from './store.ts'
+import { applyRestore, type RestoreDirection } from '../../kernel/src/docfields.ts'
/**
* The largest snapshot the gate will parse, in UTF-16 code units of JSON.
@@ -49,13 +58,48 @@ export const MAX_RESTORE_CHARS = 128 * 1024 * 1024
export type GateRefusal = 'size' | 'json' | 'proto' | 'format' | 'frozen' | 'docId'
+type Gated = { ok: true; doc: SpacesDoc } | { ok: false; why: GateRefusal }
+
/**
* Gate a snapshot's JSON against the open space. Returns the document to
- * install — content from the snapshot, identity from `live` — or why it was
- * refused. A refusal is never applied and never deletes the entry.
+ * install — content from the snapshot, identity (and, by direction, history)
+ * from `live`, exactly as replaceDoc would merge it — or why it was refused. A
+ * refusal is never applied and never deletes the entry.
*/
-export function gateRestored(json: unknown, live: SpacesDoc):
- { ok: true; doc: SpacesDoc } | { ok: false; why: GateRefusal } {
+export function gateRestored(
+ json: unknown, live: SpacesDoc, direction: RestoreDirection, incomingAt?: number,
+): Gated {
+ const g = gateOnly(json, live)
+ if (!g.ok) return g
+ const incoming = direction === 'recover' ? asWholeRecovery(g.doc) : g.doc
+ return { ok: true, doc: applyRestore(live, incoming, direction, rulesFor(direction), restoreAt(live, incomingAt)) }
+}
+
+/**
+ * The recovery path only ('recover', RECOVER_RULES — the whole-snapshot
+ * path): a snapshot with NO `revisions` means the person CLEARED them.
+ *
+ * The snapshot is kernel autosave's `contentOnly(doc)`, the WHOLE document, so
+ * a missing key is a deleted one. When this was written the kernel kept an
+ * ABSENT history field live before any hook ran, so Restore brought back
+ * drafts Clear history had removed; the absence is therefore stated as `[]`,
+ * which history.ts `revisionsRecover` reads as "cleared" and answers by
+ * removing the key. Since kernel #726 a whole snapshot removes an absent
+ * history key itself, so this is now REDUNDANT (same result) and kept as a
+ * second guard; removing it is a separate follow-up.
+ *
+ * `trail` is NOT normalised, and RECOVER_RULES opts it out of #726's removal
+ * (keepLiveWhenAbsent: ['trail']): a whole snapshot with no trail means "no
+ * rows yet", so the live rows stay.
+ */
+export function asWholeRecovery(doc: SpacesDoc): SpacesDoc {
+ if ((doc as { revisions?: unknown }).revisions !== undefined) return doc
+ return { ...doc, revisions: [] } as SpacesDoc
+}
+
+/** The gate itself — bounded, prototype-safe, this space's docId, parseDoc,
+ * sanitized — WITHOUT the keep-live merge, which replaceDoc does. */
+function gateOnly(json: unknown, live: SpacesDoc): Gated {
if (typeof json !== 'string' || json.length > MAX_RESTORE_CHARS) return { ok: false, why: 'size' }
// PROTOTYPE-SAFE: a `__proto__` key anywhere refuses the whole entry. No
@@ -83,18 +127,18 @@ export function gateRestored(json: unknown, live: SpacesDoc):
for (const b of page.blocks) if (typeof b.html === 'string' && b.html) b.html = sanitizeInline(b.html)
}
- keepLiveIdentity(doc as Record<string, unknown>, live as Record<string, unknown>)
return { ok: true, doc }
}
/**
* Should the recovery banner be shown at all? Only for a snapshot that passes
- * the gate AND, compared as it would be restored, differs from what is open.
- * A forged or junk entry therefore never raises a banner — it cannot be used
- * to keep one on screen, any more than to restore through it.
+ * the gate AND, compared as it would be restored ('recover', timed by the
+ * snapshot), differs from what is open. A forged or junk entry therefore never
+ * raises a banner — it cannot be used to keep one on screen, any more than to
+ * restore through it.
*/
-export function recoveryOffered(json: unknown, live: SpacesDoc): boolean {
- const g = gateRestored(json, live)
+export function recoveryOffered(json: unknown, live: SpacesDoc, at?: number): boolean {
+ const g = gateRestored(json, live, 'recover', at)
return g.ok && docContentKey(g.doc) !== docContentKey(live)
}
@@ -105,11 +149,45 @@ export function recoveryOffered(json: unknown, live: SpacesDoc): boolean {
* listed — and a refusal applies nothing and deletes nothing. A read-only
* store (a reading copy, a view-only follower, a frozen file) is never
* rewritten from this browser's storage.
+ *
+ * Callers use the named entry points below, which fix the direction.
*/
-export function restoreInto(store: Store, json: unknown): boolean {
+export function restoreInto(store: Store, json: unknown, direction: RestoreDirection, incomingAt?: number): boolean {
if (store.readOnly) return false
- const g = gateRestored(json, store.doc)
+ const g = gateOnly(json, store.doc)
if (!g.ok) return false
- store.replaceDoc(g.doc)
+ // 'recover' is the whole-snapshot path: an absent `revisions` was cleared
+ const incoming = direction === 'recover' ? asWholeRecovery(g.doc) : g.doc
+ store.replaceDoc(incoming, direction, restoreAt(store.doc, incomingAt))
+ return true
+}
+
+/** The crash-recovery banner's Restore: the snapshot is a NEWER copy of this
+ * space, so 'recover' — history reconciled with it, trail unioned by day,
+ * timed by the snapshot's own `at` against the live `modified`. */
+export function recoverInto(store: Store, snap: { json: unknown; at?: number }): boolean {
+ return restoreInto(store, snap.json, 'recover', snap.at)
+}
+
+/** A version restore, from either timeline (this browser's, or the one inside
+ * the file): going BACK — content follows the version, history stays live. */
+export function restoreVersion(store: Store, json: unknown): boolean {
+ return restoreInto(store, json, 'back')
+}
+
+/**
+ * Replace from JSON and `window.bento.loadDoc`: the pasted text is parsed
+ * (`parseDoc` — the format, version and shape check a file open runs) and
+ * applied going BACK, so it brings content and never identity, modes,
+ * capability or history — a paste can neither delete this space's history
+ * nor install a forged one. Not docId-gated: pasting another space's content
+ * into this one is what the command is for. Returns false (applying nothing)
+ * for text that is not a bento/spaces document, or on a read-only store.
+ */
+export function replaceFromJson(store: Store, text: string): boolean {
+ if (store.readOnly) return false
+ const res = parseDoc(text)
+ if (!res.ok) return false
+ store.replaceDoc(res.doc, 'back')
return true
}
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index 48e45a30..940b92d9 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -15,8 +15,12 @@ type Scope = 'doc' | 'page'
import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'
import { buildTagIndex, type TagIndex } from './tags.ts'
-import { FROM_LIVE, keepLiveIdentity as keepLive } from '../../kernel/src/docfields.ts'
+import {
+ FROM_LIVE, applyRestore, validateRestoreRules, type RestoreDirection, type RestoreRules,
+} from '../../kernel/src/docfields.ts'
import { SPACES_FIELDS } from './docclass.ts'
+import { trailRecover } from './trail.ts'
+import { revisionsRecover } from './history.ts'
type Listener = () => void
type Event = 'doc' | 'page' | 'tree' | 'selection' | 'dirty'
@@ -47,47 +51,108 @@ const UNDO_BUDGET = 24 * 1024 * 1024
* NOT on the list, deliberately: `theme` (and any design setting) is content
* and undoes like content; `format`/`version`/`policy` describe how the content
* is encoded and travel with it; `assets` is kept by undo/redo for a different
- * reason — snapshots omit it for size — and a replaceDoc brings its own.
+ * reason — snapshots omit it for size (UNDO_RULES) — and a replaceDoc brings
+ * its own.
*
- * The shared list now lives in the kernel (kernel/src/docfields.ts) and is
- * re-exported here, so restoregate.ts keeps importing it from `./store.ts`.
+ * The list is the kernel's (kernel/src/docfields.ts) and is re-exported here;
+ * what ENFORCES it now is the field map's classes (identity / mode /
+ * capability, docclass.ts) through `applyRestore`, whose floor keeps those
+ * classes live in every direction and refuses an override that says otherwise.
*/
export { FROM_LIVE }
-/** Overwrite `next`'s FROM_LIVE keys with `live`'s — including deleting one the
- * live document does not have. Mutates and returns `next`. The kernel's
- * keepLiveIdentity does the work, so this app and the kernel cannot disagree
- * about what "kept live" means. */
-function keepLiveIdentity(live: SpacesDoc, next: SpacesDoc): SpacesDoc {
- keepLive(next as Record<string, unknown>, live as Record<string, unknown>)
- keepLiveHistory(live, next)
- return next
+/**
+ * THE restore rules: one map, one call (`applyRestore`), two directions.
+ *
+ * 'back' — undo, redo, a version restore (either timeline), Replace from
+ * JSON and bento.loadDoc. Content follows what is restored (an
+ * ABSENT content field is dropped — a restored version is the
+ * whole document); identity, modes, capability AND history keep
+ * the live value. History is a LOG of the space (`revisions`,
+ * `trail`), not its content: without that, ⌘Z after a save
+ * un-recorded the revision that save wrote, a paste of Copy
+ * document JSON (which carries no history) deleted it, and a
+ * pasted or restored document could INSTALL a forged one.
+ * 'recover' — the crash-recovery banner only. The snapshot is a NEWER copy of
+ * this space, so history is reconciled with it rather than kept:
+ * `revisions` follows the snapshot when it carries a READABLE
+ * list, is REMOVED when the snapshot has none (a whole snapshot
+ * without it was CLEARED — restoregate.ts asWholeRecovery), and
+ * a foreign list on either side keeps live (history.ts
+ * `revisionsRecover`); `trail` unions by day (trail.ts
+ * `trailRecover`), so an absent trail keeps the live rows.
+ * Content absent from the snapshot was removed and stays removed
+ * (RECOVER_RULES, wholeSnapshot).
+ *
+ * Identity, mode and capability are live in BOTH directions; the kernel's floor
+ * holds that even against a mistaken override.
+ */
+export const RESTORE_RULES: RestoreRules = {
+ classes: SPACES_FIELDS,
+ recover: { trail: trailRecover, revisions: revisionsRecover },
}
+validateRestoreRules(RESTORE_RULES)
/**
- * The fields the kernel's map classes 'history' (docclass.ts: `revisions`,
- * `trail`). They are a LOG of the space, not its content, so — like identity —
- * every whole-document restore keeps the LIVE value, and undo snapshots omit
- * them (they would be up to 128 KB per entry, identical in nearly every one).
- *
- * Without this, three ordinary actions silently rewrote the file's history:
- * ⌘Z after a save un-recorded the revision that save wrote; "Replace from
- * JSON" with the output of Copy document JSON (which drops history by the
- * copy table) deleted it outright; and restoring a version or a recovery
- * snapshot rolled the list back to whatever it was when that copy was taken.
- * Read from the map, so a history field added later is kept the same way.
+ * The recovery banner's rules: RESTORE_RULES with `wholeSnapshot: true`,
+ * stated EXPLICITLY although the kernel (#716) defaults to it. The recovery
+ * snapshot is kernel autosave's `contentOnly(doc)` — the WHOLE document — so a
+ * content or unknown key absent from it is one the person REMOVED after the
+ * last save (a design, footnotes, a journal template), and it must stay
+ * removed rather than come back from the file. History is exempt in the
+ * kernel (an absent `trail`/`revisions` still keeps live), and the identity /
+ * mode / capability floor is unchanged. Only 'recover' reads the flag; every
+ * 'back' path already drops an absent field.
*/
-const HISTORY_KEYS: readonly string[] = Object.entries(SPACES_FIELDS)
- .filter(([, cls]) => cls === 'history').map(([k]) => k)
+export const RECOVER_RULES: RestoreRules = {
+ ...RESTORE_RULES,
+ wholeSnapshot: true,
+ // Since kernel #726 a whole snapshot REMOVES an absent history key (absent =
+ // the person cleared it). That is right for `revisions` — cleared history
+ // must stay cleared, so it is deliberately NOT listed here — but not for
+ // `trail`: nobody "clears" a trail by omission; a snapshot without one means
+ // "no rows yet" (recorded nothing before the crash), and the live rows are
+ // observations nobody can recompute. ONLY 'trail', never 'revisions'.
+ keepLiveWhenAbsent: ['trail'],
+}
+validateRestoreRules(RECOVER_RULES)
-function keepLiveHistory(live: SpacesDoc, next: SpacesDoc): void {
- const n = next as Record<string, unknown>, l = live as Record<string, unknown>
- for (const k of HISTORY_KEYS) {
- if (Object.hasOwn(l, k) && l[k] !== undefined) n[k] = l[k]
- else delete n[k]
+/** The rules a direction restores by: the recovery banner's for 'recover'
+ * (the only caller of that direction), the shared ones for 'back'. */
+export const rulesFor = (direction: RestoreDirection): RestoreRules =>
+ direction === 'recover' ? RECOVER_RULES : RESTORE_RULES
+
+/**
+ * Undo and redo only. Their checkpoints OMIT `assets` (the largest thing in the
+ * document, and unchanged by an ordinary edit — see `snapshot()`), and
+ * `applyRestore` on 'back' reads an absent content field as DROPPED. Fed a
+ * checkpoint as-is it would delete every embedded image. So on this one path
+ * the pool keeps the LIVE value — exactly what undo did before the kernel took
+ * over: undoing an image insert removes the block's `asset:` reference, never
+ * the bytes (the pool is pruned on save, where nothing else can still be
+ * pointing at it). Version restore and Replace from JSON carry their own pool,
+ * so there `assets` follows like any content.
+ */
+const UNDO_RULES: RestoreRules = { ...RESTORE_RULES, keepLive: { assets: 'live' } }
+validateRestoreRules(UNDO_RULES)
+
+/** The whole-doc times a recover hook compares, as epoch ms on both sides
+ * (kernel `RecoverHook`): the live document's `modified`, and the snapshot's
+ * own time. A live space with no `modified` gives `live: undefined`, which the
+ * hook treats as OLDER. */
+export function restoreAt(live: SpacesDoc, incomingAt?: number): { live?: number; incoming?: number } {
+ const l = typeof live.modified === 'string' ? Date.parse(live.modified) : NaN
+ return {
+ live: Number.isFinite(l) ? l : undefined,
+ incoming: typeof incomingAt === 'number' && Number.isFinite(incomingAt) ? incomingAt : undefined,
}
}
+/** History-class keys (docclass.ts: `revisions`, `trail`), read from the map so
+ * a history field added later is omitted from undo checkpoints the same way. */
+const HISTORY_KEYS: readonly string[] = Object.entries(SPACES_FIELDS)
+ .filter(([, cls]) => cls === 'history').map(([k]) => k)
+
/**
* One undoable step.
*
@@ -310,7 +375,7 @@ export class Store {
private snapshot(): string {
// assets are excluded: they are the largest thing in the document and never
// change during an ordinary edit, so snapshotting them 100 times is waste.
- // History fields are excluded too, and restored from live (keepLiveHistory).
+ // History fields are excluded too; 'back' keeps them live (RESTORE_RULES).
// That includes `trail`: a row is an OBSERVATION written outside any
// commit, so an undo that restored it could put a stale row over a newer
// one. `periods` is content, NOT excluded: starting a period is something a
@@ -355,9 +420,9 @@ export class Store {
// CONTENT moves, identity does not: the snapshot's docId/collab/readonly
// are whatever they were when it was taken, and Stop sharing, a key
// rotation or a mode change since then must survive ⌘Z and ⌘⇧Z alike.
- const live = this.doc
- const assets = live.assets
- this.doc = keepLiveIdentity(live, { ...(JSON.parse(entry.json) as SpacesDoc), ...(assets ? { assets } : {}) })
+ // 'back', with the pool kept live: the checkpoint has no `assets` key
+ // (UNDO_RULES says why), and absent-means-dropped would empty it.
+ this.doc = applyRestore(this.doc, JSON.parse(entry.json) as SpacesDoc, 'back', UNDO_RULES)
}
this.pageId = entry.viewId
this.reindex()
@@ -415,12 +480,17 @@ export class Store {
* recovery path. Content is replaced; identity is not (FROM_LIVE): a version
* from before Stop sharing or Rotate keys, or JSON pasted from another space,
* never brings its own docId, room credentials or file mode with it.
+ *
+ * `direction` is REQUIRED, so no caller gets one by default: 'recover' for
+ * the crash-recovery banner (with `at` from `restoreAt`), 'back' for
+ * everything else (RESTORE_RULES). Untrusted input is gated BEFORE it gets
+ * here (restoregate.ts); this only decides which side each field comes from.
*/
- replaceDoc(next: SpacesDoc): void {
+ replaceDoc(next: SpacesDoc, direction: RestoreDirection, at: { live?: number; incoming?: number } = {}): void {
this.dirty = true
this.endRun()
this.checkpoint()
- this.doc = keepLiveIdentity(this.doc, next)
+ this.doc = applyRestore(this.doc, next, direction, rulesFor(direction), at)
this.reindex()
this.pageId = homePage(next)?.id ?? ''
this.emit('doc')
diff --git a/spaces/src/trail.ts b/spaces/src/trail.ts
index 13d6f059..96fe0dd0 100644
--- a/spaces/src/trail.ts
+++ b/spaces/src/trail.ts
@@ -471,6 +471,89 @@ function stampCut(trail: Trail): Trail {
export const wasCut = (trail: Trail, series = ''): boolean =>
seriesRows(trail, series)[0]?.row.cut === true
+// ---- crash recovery: the per-day union -------------------------------------
+
+/**
+ * The trail's RECOVER HOOK (kernel docfields.ts `RecoverHook`): what a crash
+ * recovery keeps when the open file and the recovered snapshot BOTH carry a
+ * trail. Bound in store.ts `RESTORE_RULES` for direction 'recover' only — the
+ * kernel never consults it on undo, redo, a version restore or a paste, which
+ * all keep the live trail outright.
+ *
+ * Neither side is simply newer. The recovery snapshot holds rows written while
+ * editing that the file never got (main.ts recordToday writes outside any
+ * save), and the file may hold days written AFTER the snapshot (it was saved
+ * from another tab, or the snapshot is stale). Taking either whole map loses
+ * observations nobody can recompute, so it is a UNION BY DAY:
+ *
+ * 1. a key on ONE side only is kept — it is an observation the other side
+ * never made;
+ * 2. a key on BOTH sides goes to the side whose WHOLE DOCUMENT is later
+ * (`at`, epoch ms): incoming when `at.incoming > at.live`; a tie keeps
+ * live; an unknown live time (a file with no `modified`) counts as OLDER,
+ * so a known incoming time wins it; an unknown incoming time never wins;
+ * 3. no day is counted twice. A thinned row stands for the `s` days ENDING on
+ * its own key, so a bucket row from one side and single-day rows inside
+ * its span from the other would both claim those days. Rows are walked
+ * newest-anchor first, per series, and a row whose own day lies inside the
+ * span of a row already kept is dropped. (That is "drop a single day inside
+ * a kept bucket", generalised: two overlapping buckets resolve the same
+ * way, and no two kept rows of a series ever cover the same day.) Day
+ * arithmetic is `dayIndex` on the LABEL and only ever within one series —
+ * never `new Date(label)`, and `sprint/2026-09-11` never meets
+ * `2026-09-11`;
+ * 4. the result goes through `pruneTrail`, so a union can never exceed the
+ * budget either side was held to.
+ *
+ * A side that is not a trail object (a newer build's shape — `trailIsForeign`)
+ * is never written over: an open foreign trail stays, and a foreign incoming
+ * one does not replace a readable live one. Keys this build cannot parse are
+ * carried by rules 1 and 2 untouched, and never take part in rule 3.
+ */
+export function trailRecover(
+ live: unknown, incoming: unknown, at: { live?: number; incoming?: number },
+): unknown {
+ if (live === undefined) return incoming
+ if (!isObj(live) || !isObj(incoming)) return live
+ const incomingWins = at.incoming !== undefined && (at.live === undefined || at.incoming > at.live)
+ const merged: Record<string, unknown> = {}
+ const put = (k: string, v: unknown): void => {
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') return
+ merged[k] = v
+ }
+ // LIVE's key order first, then the snapshot's new keys: a snapshot holding
+ // nothing the file lacks merges to a map byte-identical to the live one, so
+ // the recovery check (which compares serialized content) raises no banner
+ for (const k of Object.keys(live)) {
+ put(k, Object.hasOwn(incoming, k) && incomingWins ? incoming[k] : live[k])
+ }
+ for (const k of Object.keys(incoming)) {
+ if (!Object.hasOwn(live, k)) put(k, incoming[k])
+ }
+
+ // 3. one claim per day, per series: newest anchor first
+ const bySeries = new Map<string, Array<{ k: string; day: number; span: number }>>()
+ for (const k of Object.keys(merged)) {
+ const addr = parseTrailKey(k)
+ const row = merged[k]
+ if (!addr || !isObj(row)) continue
+ const list = bySeries.get(addr.series) ?? []
+ list.push({ k, day: dayIndex(addr.day), span: spanOf(row as unknown as TrailRow) })
+ bySeries.set(addr.series, list)
+ }
+ for (const [, list] of bySeries) {
+ list.sort((a, b) => b.day - a.day)
+ const kept: Array<{ from: number; to: number }> = []
+ for (const r of list) {
+ if (kept.some((c) => r.day >= c.from && r.day <= c.to)) { delete merged[r.k]; continue }
+ kept.push({ from: r.day - r.span + 1, to: r.day })
+ }
+ }
+
+ // 4. the budget
+ return pruneTrail(merged as Trail)
+}
+
// ---- drawing slots ---------------------------------------------------------
/**