Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: every copy goes through the kernel's field classes (#665)
nyblnet01494222f745
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2e8d83e4..818e946b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -165,6 +165,19 @@ jobs:--outfile="$RUNNER_TEMP/test-spaces-invite.mjs"node "$RUNNER_TEMP/test-spaces-invite.mjs"+ - name: Spaces copy-tier rig+ # Every copy of a space is built by the kernel's copy table+ # (docfields.ts projectForCopy) over spaces' exhaustive field map. This+ # runs each real builder against one source carrying every class of+ # field, every collab secret, in-file history and an undeclared key, and+ # asserts the EXACT top-level key set each emits: no history or unknown+ # key in a reader copy or Copy JSON, history kept in an invite, both+ # kept in a duplicate. (Bundled: share.ts imports the kernel transport.)+ run: |+ slides/node_modules/.bin/esbuild scripts/test-spaces-copytiers.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-spaces-copytiers.mjs"+ node "$RUNNER_TEMP/test-spaces-copytiers.mjs"+- name: Spaces undo rig# Every checkpoint used to stringify the WHOLE document: measured on a# 200-page, 2.5 MB handbook, fifty edits left an undo depth of NINE,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 501053e7..a655dc8a 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -9839,3 +9839,43 @@ definitions (and no other page's), held by the roundtrip rig.**Cost.** Shell 364,703 → 368,299 B (+3,596), ten new strings in nine languages(one retired: the import no longer adopts a space-level design).++## 2026-10-10 — bento/spaces adopts the kernel's field classes for every copy++Spaces is the first app to build its copies through the kernel's copy table+(`kernel/src/docfields.ts` `projectForCopy`). Its map is+`spaces/src/docclass.ts` (`SPACES_FIELDS`), named to stay clear of+`fields.ts`, which is page properties. The map is exhaustive over the keys+`SpacesDoc` DECLARES: the type has an `[extra: string]` index signature, so+`keyof SpacesDoc` is `string` and a plain `Record<keyof SpacesDoc, …>` would+check nothing. The map strips the index signature first, then `satisfies` it.+`revisions` and `trail` are declared as optional, loosely typed fields before+the features that write them land, so they are already classed `history`.++Builders and tiers: the view-only copy is `reader`; "Invite to edit" is+`invite`; Copy document JSON (`docForExport`) is `copyJSON`; "Duplicate as new+space" is `duplicate`; "Save a copy" is `file`. Spaces has no audience, link or+whole-file template builder yet. The only things a builder still adds itself+are the ones the table has no rule for: the new docId on a duplicate,+`collab.on = true` on a share copy, and the extract's own changes below.++**The page extract ("Export page as a space") is `duplicate` minus two+fields.** It is a new identity holding a few pages, not the space. So it drops+`template` (as it already did: template re-mints the docId it was just given)+and the `history` class, because history records the whole space, including+the pages left out. No kernel tier fits a partial new-identity copy. If one is+added, the extract moves onto it.++**A view-only copy can now carry `readonly: true`.** The banner checks the+collab role BEFORE `readonly`, so the copy still says it follows the live+session. The kernel sets a mode only when the source document already has the+field (`projectForCopy` walks the source's keys), so a space with no+`readonly` key gets a reader copy without one. That is a kernel issue and+is reported there. `scripts/test-spaces-copytiers.ts` records the current+behaviour so the fix shows up as a red row.++**Recovery uses the kernel's `docContentKey`** with `modified` as the only+field that does not count as an edit. The kernel key is a superset of the old+one: theme, assets, fonts and undeclared keys now count as unsaved work. That+is safe because the only comparison is snapshot against live after+`keepLiveIdentity`, and no key is ever stored.diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.tsindex c007b0b7..b719b9b9 100644--- a/scripts/test-export-secrets.ts+++ b/scripts/test-export-secrets.ts@@ -57,6 +57,15 @@ function ok(cond: boolean, msg: string) {* matching cannot be thrown by a `{` that lives inside a message, a comment or* a template. Offsets stay 1:1 with the original, which is what gets sliced.*/+/** A call to the kernel copy table with the tier `re` names, in CODE: the tier+ * is a string literal (which mask() blanks), so the match is taken on the raw+ * body and must begin where the masked body still reads `projectForCopy(` —+ * a comment or string quoting the call does not count. */+function tableCall(body: string, re: RegExp): boolean {+ const m = re.exec(body)+ return !!m && mask(body).startsWith('projectForCopy(', m.index)+}+function mask(src: string): string {const out = src.split('')const blank = (i: number) => { if (src[i] !== '\n') out[i] = ' ' }@@ -394,6 +403,25 @@ for (const app of CLIP_APPS) {const body = src.slice(src.indexOf('export function docForExport'))// A docForExport that delegates to the kernel's shared scrubber is checked// THROUGH it: the rule is how capabilities leave, not which file spells it.+ // A docForExport built by the kernel's COPY TABLE (projectForCopy, tier+ // 'copyJSON', over the app's field map) is checked by RUNNING it: that path+ // builds from empty, so "removing" is the wrong question — what must hold is+ // that the table drops the capability class for copyJSON, the app's map+ // classes collab as that class, and the projection really has no collab.+ const table = /projectForCopy\(doc, (\w+), 'copyJSON'\)/.exec(body.slice(0, 200))+ if (table) {+ const mapName = table[1]+ const from = new RegExp(`import \\{[^}]*\\b${mapName}\\b[^}]*\\} from '\\./([\\w-]+\\.ts)'`).exec(src)+ ok(!!from, `${app}/src/model.ts: docForExport's field map (${mapName}) is imported from the app`)+ const kernel = await import('../kernel/src/docfields.ts')+ const map = from ? (await import(`../${app}/src/${from[1]}`))[mapName] as Record<string, string> : {}+ ok(kernel.CLASS_RULES.capability.copyJSON === 'drop', `${app}: the kernel copy table DROPS the capability class from copyJSON`)+ ok(map.collab === 'capability', `${app}: the app's field map classes collab as capability`)+ const out = kernel.projectForCopy({ title: 't', collab: { room: 'r', key: 'K', ownerPriv: 'P' } }, map as never, 'copyJSON') as Record<string, unknown>+ ok(!('collab' in out) && !JSON.stringify(out).includes('ownerPriv'),+ `${app}/src/model.ts: docForExport (the copy table, copyJSON) carries no collab at all`)+ continue+ }const delegated = /withoutCaps\(/.test(body.slice(0, 160)) && /from '\.\.\/\.\.\/kernel\/src\/docfields\.ts'/.test(src)const stripper = delegated ? read('kernel/src/docfields.ts').slice(read('kernel/src/docfields.ts').indexOf('export function withoutCaps')) : bodyok(/\.\.\.rest|delete .*collab|const \{ collab|delete out\[k\]/.test(stripper.slice(0, 400)),@@ -492,8 +520,13 @@ for (const app of ['spaces', 'type', 'slides']) {ok(!/stripCollabSecrets/.test(src), `${rel}: the delete-based stripper is gone — the kernel allowlist replaces it`)const inviteFn = mask(exportedBody(src, 'inviteCopy'))const readerFn = mask(exportedBody(src, 'readerCopy'))- ok(/collabForInvite\(/.test(inviteFn), `${rel}: inviteCopy routes through collabForInvite`)- ok(/collabForReader\(/.test(readerFn), `${rel}: readerCopy routes through collabForReader`)+ // Routed directly, or through the kernel's COPY TABLE with the matching tier —+ // projectForCopy projects collab through collabForInvite / collabForReader+ // (CLASS_RULES.capability, pinned just below the loop).+ ok(/collabForInvite\(/.test(inviteFn) || tableCall(exportedBody(src, 'inviteCopy'), /projectForCopy\([^;]*'invite', \{ invite \}\)/),+ `${rel}: inviteCopy routes through collabForInvite`)+ ok(/collabForReader\(/.test(readerFn) || tableCall(exportedBody(src, 'readerCopy'), /projectForCopy\([^;]*'reader'\)/),+ `${rel}: readerCopy routes through collabForReader`)ok(/mintInvite\(/.test(inviteFn), `${rel}: inviteCopy still mints a SCOPED invite`)// the bypass: rebuilding collab by spreading ANY source expression (`{ ...c }`,// `{ ...doc.collab }`, `{ ...out.collab }`) instead of the kernel helper carries@@ -502,6 +535,15 @@ for (const app of ['spaces', 'type', 'slides']) {`${rel}: neither builder rebuilds collab by spreading the source — only a collabFor* projection`)}+// A builder routed through the copy table is only as good as the table's+// capability cells: reader and invite must project through the allowlists.+{+ const { CLASS_RULES } = await import('../kernel/src/docfields.ts')+ const cap = CLASS_RULES.capability as Record<string, unknown>+ ok(JSON.stringify(cap.reader) === '{"allowlist":"reader"}' && JSON.stringify(cap.invite) === '{"allowlist":"invite"}',+ 'kernel copy table: the reader and invite tiers project collab through the allowlists (collabForReader / collabForInvite)')+}+// type's call site: collab.ts must build every copy through share.ts.{const collab = read('type/src/collab.ts')@@ -569,7 +611,7 @@ for (const app of ['spaces', 'type', 'slides']) {const src = read(rel)for (const fn of fns) {const b = mask(exportedBody(src, fn))- const routed = /collabFor(Reader|Invite)\(/.test(b)+ const routed = /collabFor(Reader|Invite)\(/.test(b) || tableCall(exportedBody(src, fn), /projectForCopy\([^;]*'(reader|invite)'/)const spread = /\{\s*\.\.\.(?!collabFor)/.test(b)if (!b || !routed || spread) { bypasses++; console.log(` (bypass: ${rel} ${fn})`) }}diff --git a/scripts/test-spaces-copytiers.ts b/scripts/test-spaces-copytiers.tsnew file mode 100644index 00000000..c5cdd3e8--- /dev/null+++ b/scripts/test-spaces-copytiers.ts@@ -0,0 +1,338 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/spaces copy-tier rig — what each copy of a space carries, field by field.+//+// node scripts/test-spaces.mjs copytiers # bundled, like the invite rig+//+// (Bundled, not run directly: share.ts imports the kernel transport, which uses+// TypeScript parameter properties that node's strip-only loader refuses.)+//+// WHAT THIS PROVES. Every copy of a space that leaves the open document is built+// by the kernel's copy table (kernel/src/docfields.ts projectForCopy) over this+// app's exhaustive field map (spaces/src/docclass.ts). This rig runs each REAL+// builder — share.ts readerCopy / inviteCopy / duplicateAsNew, portable.ts+// extractSpace, model.ts docForExport (Copy document JSON) and the 'file' tier+// main.ts writes "Save a copy…" through — against ONE source carrying every+// class of field: content, identity, both modes, a full collab with every+// secret, in-file history (`revisions`, `trail`) and a top-level key this build+// has never heard of (`futureField`). It asserts the EXACT top-level key set+// each builder emits, not just the absence of a few names, so a field that+// starts riding a copy by accident fails here.+//+// The rules it holds spaces to (the kernel's, 2026-10-10):+// · reader / Copy JSON (and audience / link / template, which spaces has no+// builder for yet): no history, no undeclared key, no capability secret;+// readonly SET on a reader copy, template dropped from it+// · invite: no undeclared key; history KEPT; the modes dropped+// · duplicate / file: the undeclared key and the history KEPT+//+// Mutation controls (run by hand, listed in the PR): make readerCopy skip+// projectForCopy (clone + collabForReader, the shape it had before); classify+// `revisions` as content; route docForExport through withoutCaps. Each reds+// named rows below. In-rig, a planted builder of the old shape is run against+// the same expectations and must FAIL them — so the checks are not vacuous.++const store = new Map<string, string>()+const shim = {+ getItem: (k: string) => (store.has(k) ? store.get(k)! : null),+ setItem: (k: string, v: string) => { store.set(k, String(v)) },+ removeItem: (k: string) => { store.delete(k) },+ clear: () => store.clear(),+ key: (i: number) => [...store.keys()][i] ?? null,+ get length() { return store.size },+}+const g = globalThis as unknown as Record<string, unknown>+g.localStorage = shim+g.window = g.window ?? { localStorage: shim, addEventListener() {}, setTimeout, clearTimeout }++const { inviteCopy, readerCopy, duplicateAsNew } = await import('../spaces/src/share.ts')+const { extractSpace } = await import('../spaces/src/portable.ts')+const { docForExport, FORMAT } = await import('../spaces/src/model.ts')+const { SPACES_FIELDS } = await import('../spaces/src/docclass.ts')+const { projectForCopy, collabForReader, COLLAB_READER_KEEP, COLLAB_INVITE_KEEP } = await import('../kernel/src/docfields.ts')+const { mintCollab } = await import('../kernel/src/sync/online.ts')+import type { SpacesDoc } from '../spaces/src/model.ts'+import type { Tier } from '../kernel/src/docfields.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (cond) console.log(` ✓ ${msg}`)+ else { failures++; console.error(` ✗ ${msg}`) }+}+type Obj = Record<string, unknown>+const keys = (o: object) => Object.keys(o).sort()+const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i])+const show = (o: object) => keys(o).join(',')+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x)) as T++// ---------------------------------------------------------------------------+// ONE source with every class of field. The collab is a REAL owner mint (the+// invite builder signs against ownerPriv), with every other secret planted.+const minted = await mintCollab()+const SECRET = {+ writerPriv: 'WRITERPRIV-SECRET',+ invitePriv: 'SRC-INVITE-PRIV-SECRET',+ audiencePriv: 'AUDIENCE-PRIV-SECRET',+ future: 'COLLAB-FUTURE-SECRET',+}+const collab = {+ ...minted,+ writerPriv: SECRET.writerPriv,+ invite: { pub: 'SRC-INVITE-PUB', priv: SECRET.invitePriv, role: 'writer', sig: 'S', exp: 0 },+ audience: { invite: { priv: SECRET.audiencePriv } },+ links: [{ url: 'https://bento.page/x', id: 'L1' }],+ sync: { v: 2, tag: 'STAMP' },+ futureSecret: SECRET.future,+}+const OWNER_PRIV = (collab as Obj).ownerPriv as string++/** Content fields of the fixture — everything the map classes 'content'. */+const CONTENT = ['format', 'version', 'title', 'home', 'pages', 'theme', 'modified', 'assets', 'footnotes', 'design', 'journalTemplate']+function source(extra: Obj = {}): SpacesDoc {+ return {+ format: FORMAT, version: 1,+ docId: 'doc-source',+ title: 'Handbook',+ home: 'p1',+ modified: '2026-10-10T00:00:00.000Z',+ pages: [+ { id: 'p1', title: 'Home', blocks: [{ id: 'b1', type: 'p', html: 'hello [^1]' }] },+ { id: 'p2', title: 'Child', parent: 'p1', blocks: [{ id: 'b2', type: 'p', html: 'kid' }] },+ ],+ theme: { background: '#FFFFFF', color: '#1E2A3A', accent: '#F7A600', fontFamily: 'sans-serif', measure: 720 },+ assets: { a1: 'data:image/png;base64,AAAA' },+ footnotes: { 1: 'a note' },+ design: 'almanac',+ journalTemplate: 't1',+ collab: clone(collab),+ revisions: [{ id: 'r1', at: '2026-10-09T00:00:00Z', body: { pages: 'THE-WHOLE-SPACE' } }],+ trail: { '2026-10-09': { done: 3 } },+ futureField: 'FROM-A-NEWER-BUILD',+ ...extra,+ } as unknown as SpacesDoc+}++/** No capability secret anywhere in the serialized copy — a full-text scan. */+function noSecrets(o: object, label: string, allowFreshInvite = false) {+ const text = JSON.stringify(o)+ ok(!text.includes(OWNER_PRIV), `${label}: the owner private key appears nowhere`)+ ok(!text.includes(SECRET.writerPriv), `${label}: no writerPriv anywhere`)+ ok(!text.includes(SECRET.invitePriv), `${label}: the SOURCE invite's private half appears nowhere`)+ ok(!text.includes(SECRET.audiencePriv) && !text.includes(SECRET.future) && !text.includes('bento.page/x'),+ `${label}: no audience key, link record or unknown collab field`)+ const c = (o as Obj).collab as Obj | undefined+ if (c) {+ const allowed = allowFreshInvite ? [...COLLAB_INVITE_KEEP, 'invite', 'role'] : [...COLLAB_READER_KEEP, 'role']+ ok(keys(c).every((k) => allowed.includes(k)), `${label}: collab holds only allowlisted keys (${show(c)})`)+ }+}++const sorted = (xs: string[]) => [...xs].sort()++// ---------------------------------------------------------------------------+console.log('\nthe source: one field of every class, and every secret')+{+ const s = source() as Obj+ ok(Object.keys(SPACES_FIELDS).every((k) => k in s || ['readonly', 'template', 'policy', 'fonts', 'templates', 'designs'].includes(k)),+ 'the fixture carries every declared field except the optional ones exercised separately')+ ok(!('futureField' in SPACES_FIELDS), '`futureField` is undeclared — the case the unknown-key rule exists for')+ ok(SPACES_FIELDS.revisions === 'history' && SPACES_FIELDS.trail === 'history', 'revisions and trail are classed history')+ ok(SPACES_FIELDS.collab === 'capability' && SPACES_FIELDS.docId === 'identity', 'collab is the capability, docId the identity')+ ok(SPACES_FIELDS.readonly === 'mode' && SPACES_FIELDS.template === 'mode', 'readonly and template are the modes')+}++// ---------------------------------------------------------------------------+console.log('\nreader — "Share → view-only copy" (share.ts readerCopy)')+const EXPECT_READER = sorted([...CONTENT, 'docId', 'collab', 'readonly'])+// THE ABSENT-FIELD CASE. A space with no `readonly` key at all — almost every+// space — must still get `readonly:true` in a reader copy. This rig found that+// projectForCopy only fired a {set} mode rule when the source already carried+// the field (an editable "reader" copy); the kernel now applies every {set}+// cell for the tier regardless (#666), and this row holds it there.+function checkReader(out: SpacesDoc | null, label: string): boolean {+ const before = failures+ ok(!!out, `${label}: a copy is made`)+ if (!out) return false+ const o = out as Obj+ ok(same(keys(o), EXPECT_READER), `${label}: EXACT top-level keys (${show(o)})`)+ ok(!('revisions' in o) && !('trail' in o), `${label}: no revisions, no trail`)+ ok(!('futureField' in o), `${label}: the undeclared key is dropped`)+ ok(o.readonly === true, `${label}: readonly is SET (the kernel's mode rule)`)+ ok(!('template' in o), `${label}: template is dropped`)+ ok((o.collab as Obj)?.role === 'reader', `${label}: collab.role is reader`)+ ok((o.collab as Obj)?.sync === undefined, `${label}: no sync stamp`)+ noSecrets(o, label)+ return failures === before+}+{+ const src = source({ readonly: false })+ checkReader(readerCopy(src), 'reader')+ checkReader(readerCopy(source({ template: true, readonly: false })), 'reader of a template/editable source')+ {+ const bare = readerCopy(source()) as Obj+ ok(same(keys(bare), EXPECT_READER) && bare.readonly === true && !('template' in bare),+ `reader of a source with NO mode fields: readonly is SET anyway (${show(bare)})`)+ ok(!('revisions' in bare) && !('trail' in bare) && !('futureField' in bare), 'reader of a source with no mode fields: still no history, no undeclared key')+ noSecrets(bare, 'reader of a source with no mode fields')+ }+ ok(((readerCopy(src) as Obj).collab as Obj).on === true, 'reader: the copy is live (collab.on)')+ ok(JSON.stringify(src) === JSON.stringify(source({ readonly: false })), 'reader: the open document is untouched')++ // NOT VACUOUS: the shape readerCopy had before the kernel table — a deep+ // clone with collab re-projected — carries the history and the unknown key,+ // and must fail the same expectations.+ const planted = (d: SpacesDoc): SpacesDoc => {+ const out = clone(d)+ out.collab = { ...collabForReader(d.collab!), on: true } as SpacesDoc['collab']+ return out+ }+ const f0 = failures, c0 = checks+ console.log(' (planted old-shape builder — these rows MUST fail:)')+ const passed = checkReader(planted(src), 'planted')+ const plantedFailed = failures - f0+ failures = f0; checks = c0 // the planted run's own rows are the control, not results+ ok(!passed && plantedFailed >= 3, `a reader builder that skips projectForCopy FAILS these checks (${plantedFailed} rows red)`)+}++// ---------------------------------------------------------------------------+console.log('\ninvite — "Share → invite to edit" (share.ts inviteCopy)')+{+ const EXPECT = sorted([...CONTENT, 'docId', 'collab', 'revisions', 'trail'])+ for (const [label, src] of [['invite', source()], ['invite of a template/read-only source', source({ template: true, readonly: true })]] as const) {+ const out = await inviteCopy(src)+ ok(!!out, `${label}: the owner can mint one`)+ const o = out as Obj+ ok(same(keys(o), EXPECT), `${label}: EXACT top-level keys (${show(o)})`)+ ok(!('futureField' in o), `${label}: the undeclared key is dropped`)+ ok('revisions' in o && 'trail' in o, `${label}: history is KEPT (the kernel's invite rule)`)+ ok(!('readonly' in o) && !('template' in o), `${label}: the modes are dropped`)+ const c = o.collab as Obj+ ok(c.role === 'writer' && (c.invite as Obj)?.pub !== 'SRC-INVITE-PUB', `${label}: a FRESH writer invite, never the source's`)+ ok((c.sync as Obj)?.tag === 'STAMP', `${label}: keeps the sync stamp (it contributes)`)+ ok(c.on === true, `${label}: the copy is live (collab.on)`)+ noSecrets(o, label, true)+ }+}++// ---------------------------------------------------------------------------+console.log('\nCopy document JSON (model.ts docForExport, what doccmds copyJson writes)')+{+ const EXPECT = sorted([...CONTENT, 'docId'])+ for (const [label, src] of [['copy JSON', source()], ['copy JSON of a template/read-only source', source({ template: true, readonly: true })]] as const) {+ const o = docForExport(src) as Obj+ ok(same(keys(o), EXPECT), `${label}: EXACT top-level keys (${show(o)})`)+ ok(!('revisions' in o) && !('trail' in o), `${label}: no revisions, no trail`)+ ok(!('futureField' in o), `${label}: the undeclared key is dropped`)+ ok(!('collab' in o), `${label}: no collab at all`)+ ok(!('readonly' in o) && !('template' in o), `${label}: the modes are dropped (the kernel's copyJSON rule)`)+ noSecrets(o, label)+ }+}++// ---------------------------------------------------------------------------+console.log('\nduplicate — "Duplicate as new space…" (share.ts duplicateAsNew)')+{+ const src = source({ readonly: false, template: true })+ const o = duplicateAsNew(src, 'doc-fresh', '2026-10-11T00:00:00.000Z') as Obj+ ok(same(keys(o), sorted([...CONTENT, 'docId', 'readonly', 'template', 'revisions', 'trail', 'futureField'])),+ `duplicate: EXACT top-level keys (${show(o)})`)+ ok(o.futureField === 'FROM-A-NEWER-BUILD', 'duplicate: the undeclared key is KEPT')+ ok('revisions' in o && 'trail' in o, 'duplicate: history is KEPT')+ ok(o.docId === 'doc-fresh' && !('collab' in o), 'duplicate: a NEW docId, and no collab at all (identity + capability reset)')+ ok(o.modified === '2026-10-11T00:00:00.000Z', 'duplicate: stamped modified now')+ noSecrets(o, 'duplicate')+}++// ---------------------------------------------------------------------------+console.log('\nthe page extract — "Export page as a space…" (portable.ts extractSpace)')+{+ const src = source({ readonly: true, template: true })+ const { doc: out } = extractSpace(src, 'p1', { subtree: true, docId: 'doc-extract', now: '2026-10-11T00:00:00.000Z' })+ const o = out as Obj+ // (no page in the fixture references `a1`, so the extract's own asset rule+ // drops the pool — that is portable.ts, not the table)+ ok(same(keys(o), sorted([...CONTENT.filter((k) => k !== 'assets'), 'docId', 'readonly', 'futureField'])), `extract: EXACT top-level keys (${show(o)})`)+ ok(o.futureField === 'FROM-A-NEWER-BUILD', 'extract: the undeclared key is KEPT (a new identity of the owner\'s own, like a duplicate)')+ ok(!('revisions' in o) && !('trail' in o), 'extract: NO history — it records the whole space, the pages left out included')+ ok(!JSON.stringify(o).includes('THE-WHOLE-SPACE'), 'extract: nothing of the history survives anywhere in it')+ ok(o.readonly === true && !('template' in o), 'extract: readonly kept, template dropped (unchanged from before the table)')+ ok(o.docId === 'doc-extract' && !('collab' in o), 'extract: the supplied docId, and no collab at all')+ noSecrets(o, 'extract')+}++// ---------------------------------------------------------------------------+console.log('\nfile — "Save a copy…" (main.ts writes the table\'s \'file\' tier)')+{+ const src = source({ readonly: true, template: true })+ const o = projectForCopy(src, SPACES_FIELDS, 'file') as Obj+ ok(same(keys(o), keys(src)), `file: every field of the source, the undeclared one and the history included (${show(o)})`)+ ok(JSON.stringify(o.collab) === JSON.stringify(src.collab), 'file: the owner\'s collab whole — it is the owner\'s own file')+}++// ---------------------------------------------------------------------------+console.log('\naudience / link / template — no spaces builder yet; the map as the kernel projects it')+{+ // When a builder for one of these lands it inherits exactly this.+ const audience = (c: Obj): Obj => ({ ...collabForReader(c), role: 'audience' })+ const want: Partial<Record<Tier, string[]>> = {+ audience: sorted([...CONTENT, 'docId', 'collab', 'readonly']),+ link: sorted([...CONTENT, 'docId', 'collab', 'readonly']),+ template: sorted([...CONTENT, 'docId', 'template']),+ }+ for (const tier of ['audience', 'link', 'template'] as const) {+ // NEITHER mode field in the source: the tier's {set} cells must fire anyway+ const o = projectForCopy(source(), SPACES_FIELDS, tier, { projectAudience: audience }) as Obj+ ok(same(keys(o), want[tier]!), `${tier}: EXACT top-level keys (${show(o)})`)+ ok(!('revisions' in o) && !('trail' in o) && !('futureField' in o), `${tier}: no history, no undeclared key`)+ ok(tier === 'template' ? o.template === true && !('readonly' in o) : o.readonly === true && !('template' in o),+ `${tier}: the modes are SET as the kernel rules (${tier === 'template' ? 'template:true, readonly dropped' : 'readonly:true, template dropped'})`)+ noSecrets(o, tier)+ }+}++// ---------------------------------------------------------------------------+// SOURCE: every builder goes through the table, with the tier it claims, and+// nothing in spaces/src hand-strips a copy any more. Located from the CWD — the+// rig runs bundled from a temp directory.+console.log('\nevery builder routes through projectForCopy (source)')+{+ const { readFileSync, existsSync, readdirSync } = await import('node:fs')+ const { dirname, join, resolve } = await import('node:path')+ let root = resolve(process.cwd())+ while (!existsSync(join(root, 'spaces/src/docclass.ts')) && dirname(root) !== root) root = dirname(root)+ const rd = (f: string) => readFileSync(join(root, 'spaces/src', f), 'utf8')+ const body = (src: string, name: string) => {+ const i = src.indexOf(`function ${name}(`)+ if (i < 0) return ''+ const j = src.indexOf('\n}\n', i)+ return src.slice(i, j < 0 ? undefined : j)+ }+ const share = rd('share.ts'), model = rd('model.ts'), portable = rd('portable.ts'), main = rd('main.ts'), cmds = rd('doccmds.ts')+ ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'reader'\)/.test(body(share, 'readerCopy')), 'readerCopy → tier reader')+ ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'invite', \{ invite \}\)/.test(body(share, 'inviteCopy')), 'inviteCopy → tier invite, with the freshly minted invite')+ ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'duplicate'\)/.test(body(share, 'duplicateAsNew')), 'duplicateAsNew → tier duplicate')+ ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'duplicate'\)/.test(body(portable, 'extractSpace')), 'extractSpace → tier duplicate')+ ok(/return projectForCopy\(doc, SPACES_FIELDS, 'copyJSON'\)/.test(body(model, 'docForExport')), 'docForExport → tier copyJSON')+ ok(/docForExport\(h\.store\.doc\)/.test(body(cmds, 'copyJson')), 'Copy document JSON writes docForExport\'s output')+ ok(/projectForCopy\(store\.doc, SPACES_FIELDS, 'file'\)/.test(main), '"Save a copy…" → tier file')+ // nothing rebuilds a copy by hand: no `delete x.collab`, no withoutCaps on a+ // space, no collabFor* re-projection after the table has done it+ const files = readdirSync(join(root, 'spaces/src')).filter((f) => f.endsWith('.ts'))+ const handStrip: string[] = []+ for (const f of files) {+ const s = rd(f)+ if (/delete [\w.]+\.collab\b/.test(s)) handStrip.push(`${f}: delete .collab`)+ if (/collabFor(Reader|Invite)\(/.test(s)) handStrip.push(`${f}: collabFor*`)+ // editor.ts strips a bento/SLIDES deck (pageToDeck), not a space: the one+ // withoutCaps allowed, and it is pinned by name+ const caps = [...s.matchAll(/withoutCaps\(/g)].length+ if (caps && !(f === 'editor.ts' && caps === 1 && /deckForExport = <T extends object>\(deck: T\): T => withoutCaps\(deck\)/.test(s))) handStrip.push(`${f}: withoutCaps`)+ }+ ok(handStrip.length === 0, `no spaces source hand-strips a copy (${handStrip.join('; ') || 'none'})`)+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex 2c503a46..38fefb08 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -1365,7 +1365,8 @@ function fsTable(f: string): string {// later save wrote to the copy while the original stayed frozen at the// moment it was taken. The code even carried a comment claiming the// kernel did the opposite.- ok(/writeUpdatedFileAs\(html, store\.doc/.test(main),+ // (the copy is the kernel copy table's 'file' tier of store.doc — every field)+ ok(/writeUpdatedFileAs\(html, (store\.doc|copy)\b/.test(main) && /const copy = projectForCopy\(store\.doc, SPACES_FIELDS, 'file'\)/.test(main),'a copy is written through writeUpdatedFileAs (keepHandle defaults false)')// EVERY file, not just main.ts. The first version of this check read main.ts// alone and passed while about.ts kept its own "Save a copy…" button calling@@ -4530,10 +4531,17 @@ function fsTable(f: string): string {const rootBlocks = [...flat.matchAll(/(^|\})\s*:root\s*\{([^}]*)\}/g)].map((m) => m[2])ok(rootBlocks.length === 1 && rootBlocks[0].split(';').filter((d) => d.trim()).every((d) => /^\s*--sp-app-[a-z0-9-]+:\s*var\(--[a-z0-9-]+\)\s*$/.test(d)),'the one unscoped :root block only captures chrome tokens (--sp-app-* = var(--…)) and styles nothing')- // The key as main had it before designs (footnotes, templates, the journal- // template): a document with no design must key EXACTLY that, byte for byte.- const docKeyOld = JSON.stringify([plain.title, plain.home, plain.pages, plain.footnotes, plain.templates, plain.journalTemplate])- ok(docContentKey(plain) === docKeyOld, 'a document with no design keys for recovery exactly as it did before designs existed')+ // A document with no design must key EXACTLY as it would if the field had+ // never been invented: the key is the kernel's (docfields.ts docContentKey),+ // which SKIPS an absent field rather than padding it — so the same document+ // with `design: undefined` set (a key that is there and says nothing) keys+ // byte for byte the same, and neither key mentions design at all.+ {+ const padded = { ...plain, design: undefined, designs: undefined } as SpacesDoc+ const k = docContentKey(plain)+ ok(k === docContentKey(padded) && !/"designs?"/.test(k),+ 'a document with no design keys for recovery exactly as it did before designs existed')+ }{const withNotes = base();(withNotes as { footnotes?: Record<string, string> }).footnotes = { a: 'n' }@@ -4541,7 +4549,8 @@ function fsTable(f: string): string {const k0 = docContentKey(withNotes)D.setDesign(withNotes, 'almanac')const k1 = docContentKey(withNotes)- ok(k1 !== k0 && JSON.parse(k1).length === 8 && JSON.parse(k1)[3].a === 'n' && JSON.parse(k1)[5] === 't1',+ const o1 = JSON.parse(k1) as Record<string, unknown>+ ok(k1 !== k0 && o1.design === 'almanac' && (o1.footnotes as Record<string, string>)?.a === 'n' && o1.journalTemplate === 't1','choosing a design changes the content key, and footnotes and the journal template stay in it beside the design');(withNotes as { designs?: unknown }).designs = { mine: { base: 'ledger' } }ok(docContentKey(withNotes) !== k1, 'a custom design is content too')diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex 7f81ae2d..da527fec 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -64,6 +64,7 @@ const RIGS = [{ name: 'caret', file: 'scripts/test-spaces-caret.ts' },{ name: 'undo', file: 'scripts/test-spaces-undo.ts', bundle: true },{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },+ { name: 'copytiers', file: 'scripts/test-spaces-copytiers.ts', bundle: true },{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.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 },diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 355315b9..2933e475 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -1253,6 +1253,23 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.page; an older build shows the space's design and keeps it. Shell 364,703 →368,299 B (+3,596).+- **Every copy of a space is built by one shared table.** The view-only copy,+ the editor invite, Copy document JSON, Duplicate as new space, Export page as+ a space and Save a copy now take their fields from the copy rules every Bento+ app shares, and each field of a space is declared in exactly one class, so a+ new field cannot reach a copy until somebody says what it is. What changes+ for a reader: a view-only copy of a space that has a reading-copy setting is+ marked read-only in the file, so it also opens locked in a build that knows+ nothing about sharing roles (and still says it follows the live session); a+ top-level field this build does not know stays out of a view-only copy, an+ invite and Copy document JSON, and is kept by the file, Save a copy and+ Duplicate; Copy document JSON no longer carries the reading-copy or template+ settings; an invite no longer carries them either, so a template space's+ invite cannot open as a new space outside the session. Version history kept+ in the file (not in this build yet) is already classified: it travels with+ the file, a duplicate and an invite, and never with a view-only copy, Copy+ document JSON or a page export.+## [0.1.0] — 2026-08-03First release.diff --git a/spaces/src/docclass.ts b/spaces/src/docclass.tsnew file mode 100644index 00000000..559d2c9a--- /dev/null+++ b/spaces/src/docclass.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// How each TOP-LEVEL field of a bento/spaces document is copied — the space's+// row in the kernel's field classification (kernel/src/docfields.ts).+//+// Not to be confused with fields.ts, which is a page's PROPERTIES (status,+// due date, assignee). This file is about the document's own keys: which of+// them a copy handed to someone else may carry.+//+// THE MAP IS EXHAUSTIVE, and the compiler holds it to that. `satisfies` over+// the document's DECLARED keys fails tsc on a key that is missing here and on+// one that is not a field, so a new field cannot reach a copy without+// somebody deciding what it is. A field that arrives without being declared at+// all (a newer build's, or an agent's) is unclassified, and the kernel drops it+// from every copy except the file itself and the owner's duplicate.+//+// Every copy for someone else is built by `projectForCopy(doc, SPACES_FIELDS,+// tier)` (share.ts, model.ts docForExport), which starts from an EMPTY object+// and carries a field only when the kernel's table says so for that tier.++import type { FieldClass, ModeFieldsOk } from '../../kernel/src/docfields.ts'+import type { SpacesDoc } from './model.ts'++/** The keys SpacesDoc declares — its index signature (`[extra: string]`)+ * removed, which would otherwise make `keyof` plain `string` and the map+ * exhaustive over nothing. */+type DeclaredKeys<T> = keyof {+ [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K]+}++export const SPACES_FIELDS = {+ // identity — re-minted on a duplicate, never on any other copy+ docId: 'identity',+ // mode — SET per copy by the kernel's MODE_FIELD_RULES (a reader copy is+ // readonly, a template copy is a template), never simply stripped+ readonly: 'mode',+ template: 'mode',+ // capability — every field under it is a bearer key; projected through the+ // kernel's allowlists (collabForReader / collabForInvite), including `sync`+ collab: 'capability',+ // history — file-local version history: kept by the file, the duplicate and+ // an invite; dropped from every reader-tier copy and from Copy document JSON+ revisions: 'history',+ trail: 'history',+ // content — the document itself+ format: 'content',+ version: 'content',+ policy: 'content',+ title: 'content',+ // content, but NOT an edit: excluded from the recovery key (model.ts)+ modified: 'content',+ pages: 'content',+ home: 'content',+ theme: 'content',+ design: 'content',+ designs: 'content',+ // the asset pool+ assets: 'content',+ footnotes: 'content',+ fonts: 'content',+ templates: 'content',+ journalTemplate: 'content',+} satisfies Record<DeclaredKeys<SpacesDoc>, FieldClass>++/** tsc fails here if the fields classed 'mode' stop being exactly the kernel's+ * two (readonly, template). */+const _modeOk: ModeFieldsOk<typeof SPACES_FIELDS> = true+void _modeOk++/** Content that changes without anyone editing — excluded from the recovery+ * key so an autosave of an untouched space is not a phantom edit. */+export const SPACES_NOT_EDIT: ReadonlySet<string> = new Set(['modified'])diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 1c15f97f..9faace1c 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -41,6 +41,8 @@ import { Store } from './store'import { Editor } from './editor'import { SyncSession } from './sync/session.ts'import { isReaderCopy, stampSync } from './share.ts'+import { projectForCopy } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS } from './docclass.ts'import { downloadMarkdown, launchUpdateCheck } from './about'configureApp({@@ -238,10 +240,13 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')const session = new SyncSession(store)editor.connectSync(session)- if (!frozen && doc.readonly) {- banner(t('This is a reading copy. It opens for reading; nothing you do here changes the file.'))- } else if (!frozen && isReaderCopy(doc)) {+ // A view-only copy is asked about FIRST: the kernel's copy table marks it+ // `readonly` as well (share.ts readerCopy), so a build that knows no roles+ // still opens it locked — but it follows the session, and the banner says so.+ if (!frozen && isReaderCopy(doc)) {banner(t('This is a view-only copy — it follows the live session but can’t change this space.'))+ } else if (!frozen && doc.readonly) {+ banner(t('This is a reading copy. It opens for reading; nothing you do here changes the file.'))}if (frozen) {banner(frozen === 'version'@@ -275,8 +280,11 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')// 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 }))+ // tier 'file' of the kernel's copy table: the owner's own whole file,+ // every field kept — taken through the table so no copy path is outside it+ const copy = projectForCopy(store.doc, SPACES_FIELDS, 'file')+ void serializeAuto(copy)+ .then((html) => writeUpdatedFileAs(html, copy, { suffix: suffix === 'copy' ? 'copy' : suffix })).then((ok) => { if (ok) editor.status(t('Copy saved — you are still editing the original')) })}/**diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex 34e5588e..bdad6732 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -20,6 +20,8 @@ import { esc, externalHref } from './sanitize.ts'// A VALUE import, and the cycle it looks like is not one: embed.ts imports// only TYPES from here, and a type import is erased before anything runs.import { isPageRef } from './embed.ts'+import { projectForCopy, docContentKey as kernelContentKey } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS, SPACES_NOT_EDIT } from './docclass.ts'export const FORMAT = 'bento/spaces'export const FORMAT_VERSION = 1@@ -470,6 +472,15 @@ export interface SpacesDoc {* `import type` is erased, so this adds no runtime dependency.*/collab?: CollabCreds+ /**+ * In-file version history (kernel field class 'history', docfields.ts).+ * Declared here, typed loosely, BEFORE the features that write them land, so+ * the copy rules already classify them: kept by the file, a duplicate and an+ * invite; dropped from every reader-tier copy and from Copy document JSON;+ * never synced. Nothing in this build reads or writes either.+ */+ revisions?: unknown[]+ trail?: unknown[extra: string]: unknown}@@ -486,15 +497,16 @@ export interface SpacesDoc {* chat window. bento/slides had this same bug, fixed it, and wrote a rig to* stop it coming back — the rig only ever looked at slides/.*- * DERIVED BY REMOVING, not by listing what to keep: a private field added to- * CollabCreds later is stripped by this without anyone remembering to.- * `room` and `key` go too — together they ARE the read capability, and a room- * id is the thing the relay keys on.+ * BUILT FROM EMPTY by the kernel's copy table (docfields.ts projectForCopy,+ * tier 'copyJSON', this app's map in docclass.ts): `collab` is a capability+ * and is dropped whole — `room` and `key` too, since together they ARE the+ * read capability. The modes (readonly, template), the in-file history and+ * any top-level key this build does not declare are dropped as well: the+ * clipboard is a hand-out, and an undeclared key is exactly the field nobody+ * has decided is safe to hand out. Content and the docId travel.*/export function docForExport(doc: SpacesDoc): SpacesDoc {- const { collab, ...rest } = doc as SpacesDoc & { collab?: unknown }- void collab- return rest as SpacesDoc+ return projectForCopy(doc, SPACES_FIELDS, 'copyJSON')}export const uid = (p = 'b'): string => {@@ -654,24 +666,21 @@ export const newPage = (title = 'Untitled', extra: Partial<Page> = {}): Page =>/** Content that matters for "did this change" — excludes volatile fields. */export function docContentKey(doc: SpacesDoc): string {- // `footnotes` is content: a note's text is somebody's writing and lives- // nowhere else, so a recovery snapshot that ignored it would compare equal to- // a document whose notes had all been rewritten.- //- // Templates are content too: saving one is an edit worth recovering after a- // crash, and without them here a session whose only change was "save this- // page as a template" would compare equal and lose it.+ // The kernel's key (docfields.ts), over this app's field map: every declared+ // and undeclared top-level field that is PRESENT, sorted, except the+ // capability (`collab` — a key is not an edit) and `modified`.//- // The design is content as well: a crash right after choosing one must still- // offer the recovery. It is appended ONLY when present, so a document with- // no design keys exactly as it did before designs existed.+ // So `footnotes` is in it (a note's text is somebody's writing and lives+ // nowhere else), the page templates and the journal template are in it+ // (saving one is an edit worth recovering after a crash), and so are+ // `design`/`designs` (a crash right after choosing one must still offer the+ // recovery). An ABSENT field is skipped, never null-padded, so a document+ // with no design keys exactly as it would with the field never invented.//- // ONE return. Each field arrived on its own branch with its own `return`- // line, and a merge that kept both left the second one dead — footnotes- // silently dropped out of recovery. New content fields are APPENDED here.- const key: unknown[] = [doc.title, doc.home, doc.pages, doc.footnotes, doc.templates, doc.journalTemplate]- if (doc.design !== undefined || doc.designs !== undefined) key.push(doc.design ?? null, doc.designs ?? null)- return JSON.stringify(key)+ // ONE return. Each field once arrived on its own branch with its own+ // `return` line, and a merge that kept both left the second one dead —+ // footnotes silently dropped out of recovery.+ return kernelContentKey(doc, SPACES_FIELDS, SPACES_NOT_EDIT)}// ---- derived, NEVER stored -------------------------------------------------diff --git a/spaces/src/portable.ts b/spaces/src/portable.tsindex 79529c14..762e6cb9 100644--- a/spaces/src/portable.ts+++ b/spaces/src/portable.ts@@ -22,6 +22,8 @@ import { designAssetKeys, designSource } from './designs.ts'import { esc } from './sanitize.ts'import { isPageRef } from './embed.ts'import { allNotes, mergeNotes, renameRefs } from './footnotes.ts'+import { projectForCopy } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS } from './docclass.ts'/** An `<a href="#p/…">` in a block, however many attributes it carries. */const PAGE_LINK = /<a\s([^>]*?)href="#p\/([^"]*)"([^>]*)>([\s\S]*?)<\/a>/g@@ -145,7 +147,8 @@ export function subtreeIds(doc: SpacesDoc, rootId: string, subtree = true): stri** Everything the format guarantees survives: unknown top-level fields, unknown* per-page fields and unknown block types are all carried through untouched- * (PLATFORM §3). Exactly three things are deliberately NOT:+ * (PLATFORM §3). The kernel's copy table builds it (tier 'duplicate',+ * docclass.ts). Exactly four things are deliberately NOT carried:** · `collab` — every credential in it. The room, the read key, the writer and* owner private keys and the invite chain are the capability to read and@@ -154,6 +157,7 @@ export function subtreeIds(doc: SpacesDoc, rootId: string, subtree = true): stri* for reader copies; an extract is a different document, so it keeps none.* · `template` — it re-mints `docId` on every open (model.ts), and a document* that was just given a deliberate identity must keep it.+ * · the in-file history (`revisions`, `trail`): it records the whole space.* · assets nobody in the extract references. An export that carries the whole* document's images is a copy with pages hidden, not an extract — and the* images are the only thing in a space with real weight.@@ -239,7 +243,11 @@ export function extractSpace(}const out: SpacesDoc = {- ...clone(doc),+ // the kernel's copy table, tier 'duplicate' (docfields.ts): a new+ // identity, so docId and collab are RESET (omitted) — every credential in+ // collab is the capability to the WHOLE space — and the rest travels,+ // undeclared keys included+ ...projectForCopy(clone(doc), SPACES_FIELDS, 'duplicate'),docId: opts.docId,title: titleOf.get(rootId) || doc.title,pages,@@ -253,8 +261,15 @@ export function extractSpace(}if (!Object.keys(assets).length) delete out.assetsif (!fonts.length) delete out.fonts- delete out.collab+ // Two things the duplicate tier keeps and an EXTRACT must not, because an+ // extract is a few pages of a space, not the space:+ // · `template` — it re-mints docId on every open, and this file was just+ // given a deliberate identity (the kernel's duplicate tier keeps it,+ // since a duplicated template is still the owner's template);+ // · the in-file history (class 'history': revisions, trail) — it records+ // the WHOLE space, so carrying it would hand over the pages left out.delete out.template+ for (const [k, cls] of Object.entries(SPACES_FIELDS)) if (cls === 'history') delete out[k]return {doc: out,diff --git a/spaces/src/restoregate.ts b/spaces/src/restoregate.tsindex fc99d908..3fb54379 100644--- a/spaces/src/restoregate.ts+++ b/spaces/src/restoregate.ts@@ -36,7 +36,8 @@import { parseDoc, docContentKey, type SpacesDoc } from './model.ts'import { sanitizeInline } from './sanitize.ts'-import { FROM_LIVE, type Store } from './store.ts'+import type { Store } from './store.ts'+import { keepLiveIdentity } from '../../kernel/src/docfields.ts'/*** The largest snapshot the gate will parse, in UTF-16 code units of JSON.@@ -82,12 +83,7 @@ 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)}- const from = live as Record<string, unknown>- const to = doc as Record<string, unknown>- for (const k of FROM_LIVE) {- if (from[k] !== undefined) to[k] = from[k]- else delete to[k]- }+ keepLiveIdentity(doc as Record<string, unknown>, live as Record<string, unknown>)return { ok: true, doc }}diff --git a/spaces/src/share.ts b/spaces/src/share.tsindex d2f586d1..7f83eedc 100644--- a/spaces/src/share.ts+++ b/spaces/src/share.ts@@ -33,8 +33,9 @@// client and the deployed worker drift apart.import { mintInvite } from '../../kernel/src/sync/online.ts'-import { collabForReader, collabForInvite } from '../../kernel/src/docfields.ts'+import { projectForCopy } from '../../kernel/src/docfields.ts'import type { SpacesDoc } from './model.ts'+import { SPACES_FIELDS } from './docclass.ts'/** A share export's filename suffix — also what the UI calls the copy. */export type ShareKind = 'invite' | 'viewonly'@@ -95,12 +96,16 @@ export function canWrite(doc: SpacesDoc): boolean {export async function inviteCopy(doc: SpacesDoc): Promise<SpacesDoc | null> {const c = doc.collabif (!c?.room || !c.key || !isOwner(doc)) return null- const out = clone(doc)- // allowlist (kernel docfields): keeps room/read-key/public keys + sync, drops- // every private half AND anything unknown; the fresh invite and the top-level- // role come from mintInvite, never from the source.const invite = await mintInvite(c.ownerPriv!, 'writer')- out.collab = { ...collabForInvite(c, invite), on: true } as SpacesDoc['collab']+ // Built FROM EMPTY by the kernel's copy table, tier 'invite' (docfields.ts):+ // collab goes through collabForInvite — room/read-key/public keys + sync, the+ // FRESH invite and the role from it, never the source's private halves or+ // anything unknown under it. The modes are dropped (template:true would make+ // the invitee's open a roomless new space), the history travels, and any+ // top-level key this build does not declare stays behind.+ const out = projectForCopy(clone(doc), SPACES_FIELDS, 'invite', { invite })+ // the one thing a space adds: the copy is live from the moment it opens+ if (out.collab) out.collab.on = truereturn out}@@ -121,10 +126,16 @@ export async function inviteCopy(doc: SpacesDoc): Promise<SpacesDoc | null> {export function readerCopy(doc: SpacesDoc): SpacesDoc | null {const c = doc.collabif (!c?.room || !c.key) return null- const out = clone(doc)- // allowlist (kernel docfields): keeps room/read-key/public keys, forces- // role:'reader', drops every private half, the sync stamp AND anything unknown.- out.collab = { ...collabForReader(c), on: true } as SpacesDoc['collab']+ // Built FROM EMPTY by the kernel's copy table, tier 'reader' (docfields.ts):+ // collab goes through collabForReader — room/read-key/public keys, role+ // forced to 'reader', every private half, the sync stamp and anything+ // unknown under it dropped. `readonly` is SET (the copy is a reading copy+ // even to a build that knows no roles), `template` is dropped (it would+ // fork the copy out of its room on open), and the in-file history and any+ // top-level key this build does not declare stay behind.+ const out = projectForCopy(clone(doc), SPACES_FIELDS, 'reader')+ // the one thing a space adds: the copy is live from the moment it opens+ if (out.collab) out.collab.on = truereturn out}@@ -179,9 +190,11 @@ export function stampSync(* 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)+ // the kernel's copy table, tier 'duplicate': docId and collab are RESET+ // (omitted) and everything else — modes, history, undeclared keys — is the+ // owner's own and travels. The caller mints the new identity.+ const out = projectForCopy(clone(doc), SPACES_FIELDS, 'duplicate')out.docId = docId- delete out.collabout.modified = nowreturn out}@@ -189,8 +202,10 @@ export function duplicateAsNew(doc: SpacesDoc, docId: string, now = new Date().t/*** Is this copy a live viewer — one that follows the session read-only?*- * Distinct from `doc.readonly`, which is a SEALED reading copy with no session- * at all. Both lock the editor; only this one keeps receiving.+ * Distinct from `doc.readonly` alone, which is a SEALED reading copy with no+ * session at all. Both lock the editor; only this one keeps receiving. (A+ * view-only copy carries `readonly: true` too — the kernel's copy table sets+ * it — so a role this decides on is asked before the mode is.)*/export function isReaderCopy(doc: SpacesDoc): boolean {// Every collab copy that is not an allowlisted writer — 'reader', 'audience',diff --git a/spaces/src/store.ts b/spaces/src/store.tsindex cff78cdb..01b2308d 100644--- a/spaces/src/store.ts+++ b/spaces/src/store.ts@@ -15,7 +15,7 @@ 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 } from '../../kernel/src/docfields.ts'+import { FROM_LIVE, keepLiveIdentity as keepLive } from '../../kernel/src/docfields.ts'type Listener = () => voidtype Event = 'doc' | 'page' | 'tree' | 'selection' | 'dirty'@@ -54,14 +54,11 @@ const UNDO_BUDGET = 24 * 1024 * 1024export { FROM_LIVE }/** Overwrite `next`'s FROM_LIVE keys with `live`'s — including deleting one the- * live document does not have. Mutates and returns `next`. */+ * 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 {- const from = live as Record<string, unknown>- const to = next as Record<string, unknown>- for (const k of FROM_LIVE) {- if (from[k] !== undefined) to[k] = from[k]- else delete to[k]- }+ keepLive(next as Record<string, unknown>, live as Record<string, unknown>)return next}