Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: field classification v2 — typed per-tier copy table, projectForCopy from empty (#663)
nyblnet5b40d15d018b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 484a5157..1e4c4bb3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -101,10 +101,17 @@ jobs:- name: Typecheck kernel (standalone)# Apps also typecheck kernel transitively through their imports; this- # catches kernel-only errors under the kernel's own flags.+ # catches kernel-only errors under the kernel's own flags. It ALSO+ # evaluates kernel/src/docfields.typecheck.ts (included via "src"): the+ # field-class table's type-level test, whose @ts-expect-error lines fail+ # this step if a guard is weakened (no default cell, 'per-field' only in+ # the mode row, every mode field has a rule).working-directory: slidesrun: node_modules/.bin/tsc -p ../kernel+ - name: Field-classification rig+ run: node scripts/test-field-class.ts+- name: Typecheck convert (standalone)# convert/ is a library beside the apps (the CLI and bento.page/import# use it; no shell does), so no app's tsc -b reaches it. Its own flags,diff --git a/kernel/src/docfields.ts b/kernel/src/docfields.tsindex c7ab6327..eac71f31 100644--- a/kernel/src/docfields.ts+++ b/kernel/src/docfields.ts@@ -116,3 +116,232 @@ export function carryThroughRotation<T extends object>(fresh: T, old: object | ufor (const k of COLLAB_ROTATE_KEEP) if (Object.hasOwn(src, k) && src[k] !== undefined) out[k] = src[k]return out as T}++// ============================================================================+// Field classification v2 — the single typed source for how each document field+// is COPIED. Every app declares an EXHAUSTIVE Record<keyof Doc, FieldClass>+// (tsc fails on a new field), and projectForCopy builds a copy FROM EMPTY using+// only the rule tables below — so a field is carried only if a table cell says+// so, and a new field fails CLOSED (dropped from every outward copy) until it is+// classified. This generalizes the identity/capability lists above; those+// helpers remain and implement the capability projection.+// ============================================================================++/** The five classes. See CLASS_RULES for what each does per copy tier.+ * - content: ordinary document data. Kept in every copy.+ * - identity: docId. Kept; RESET (re-minted at load) on a new-identity copy.+ * - mode: readonly/template file modes. The builder SETS them per tier+ * (MODE_FIELD_RULES) — never stripped, which would turn a+ * read-only copy editable (the fail-open this class exists to stop).+ * - capability: collab — the ONLY stripped/projected class (via the allowlists).+ * - history: revisions/trail. File-local; dropped from reader-tier copies,+ * kept in the file, duplicates and invites. */+export type FieldClass = 'content' | 'identity' | 'mode' | 'capability' | 'history'++/** The copy tiers. `file` is the full saved document (the owner's round-trip);+ * `duplicate` is "Duplicate as new deck" (new identity, still the owner's own+ * copy). The rest are copies handed to someone else. */+export type Tier =+ | 'file' | 'duplicate' | 'invite' | 'reader' | 'audience'+ | 'package' | 'link' | 'template' | 'copyJSON'++export const TIERS: readonly Tier[] =+ ['file', 'duplicate', 'invite', 'reader', 'audience', 'package', 'link', 'template', 'copyJSON']++/** What a copy does with one field in one tier.+ * - keep: copy the live value as-is.+ * - drop: omit the field.+ * - reset: omit it so it is re-minted at load (a fresh docId) / re-minted fresh+ * (new collab creds on a duplicate). The caller mints; projectForCopy+ * only omits — builders never post-edit identity/capability.+ * - {set}: force a fixed value (reader copy -> readonly=true).+ * - {allowlist}: project a capability block through a tier allowlist.+ * NOTE: 'per-field' is DELIBERATELY not a Rule — it is allowed ONLY in the mode+ * row of CLASS_RULES (see its type), so no other class can defer to a per-field+ * table and the mode row can hold nothing else. */+export type Rule =+ | 'keep'+ | 'drop'+ | 'reset'+ | { readonly set: unknown }+ | { readonly allowlist: 'reader' | 'invite' | 'audience' }++/** The deferral literal — only the mode row of CLASS_RULES may hold it. */+type PerField = 'per-field'++/** Per-class x per-tier rules. The `mode` row is EXACTLY PerField in every tier+ * (it can only defer to MODE_FIELD_RULES); every other row is Rule and cannot+ * hold 'per-field'. The object type is written out (no index signature, no+ * default) so adding a FieldClass or a Tier fails tsc until every cell exists. */+export const CLASS_RULES: {+ readonly content: Record<Tier, Rule>+ readonly identity: Record<Tier, Rule>+ readonly mode: Record<Tier, PerField>+ readonly capability: Record<Tier, Rule>+ readonly history: Record<Tier, Rule>+} = {+ content: {+ file: 'keep', duplicate: 'keep', invite: 'keep', reader: 'keep', audience: 'keep',+ package: 'keep', link: 'keep', template: 'keep', copyJSON: 'keep',+ },+ identity: {+ file: 'keep', duplicate: 'reset', invite: 'keep', reader: 'keep', audience: 'keep',+ package: 'keep', link: 'keep', template: 'keep', copyJSON: 'keep',+ },+ mode: {+ file: 'per-field', duplicate: 'per-field', invite: 'per-field', reader: 'per-field',+ audience: 'per-field', package: 'per-field', link: 'per-field', template: 'per-field',+ copyJSON: 'per-field',+ },+ capability: {+ file: 'keep', duplicate: 'reset', invite: { allowlist: 'invite' }, reader: { allowlist: 'reader' },+ audience: { allowlist: 'audience' }, package: 'drop', link: { allowlist: 'reader' },+ template: 'drop', copyJSON: 'drop',+ },+ history: {+ file: 'keep', duplicate: 'keep', invite: 'keep', reader: 'drop', audience: 'drop',+ package: 'drop', link: 'drop', template: 'drop', copyJSON: 'drop',+ },+}++/** Per-mode-FIELD x per-tier rules — the only place the mode row defers to. The+ * two mode fields diverge within a tier (a reader copy SETS readonly=true but+ * keeps template; a template copy is the reverse), which a single mode cell+ * cannot express. ModeField is DERIVED from these keys (below), so classifying a+ * third field 'mode' without adding its rules here fails tsc. */+export const MODE_FIELD_RULES = {+ // readonly is DROPPED from the template copy: instantiating a template does not+ // clear readonly, so a template that carried it would make every instance+ // read-only.+ readonly: {+ file: 'keep', duplicate: 'keep', invite: 'drop', reader: { set: true }, audience: { set: true },+ package: { set: true }, link: { set: true }, template: 'drop', copyJSON: 'drop',+ },+ // template is kept ONLY by the owner's own round-trips and set by the template+ // copy. parseDoc treats template:true as "this open IS a new document" (fresh+ // docId, collab deleted), so any copy meant to stay in its room — invite,+ // reader, audience, package, link — must never carry it, or it forks on open+ // and silently loses the room.+ template: {+ file: 'keep', duplicate: 'keep', invite: 'drop', reader: 'drop', audience: 'drop',+ package: 'drop', link: 'drop', template: { set: true }, copyJSON: 'drop',+ },+} satisfies Record<string, Record<Tier, Rule>>++/** The fields that may be classed 'mode' — derived from MODE_FIELD_RULES, not a+ * hand-written union, so a rule must exist before a field can be a mode field. */+export type ModeField = keyof typeof MODE_FIELD_RULES++/** Unknown / unclassified top-level key: kept only in the file itself and in the+ * owner's own duplicate; dropped from every outward copy INCLUDING invite (an+ * invite is a file for another person — a future secret/history-like field must+ * not ride it). This is the fail-closed default for anything not in the map. */+const UNKNOWN_RULE: Record<Tier, Rule> = {+ file: 'keep', duplicate: 'keep', invite: 'drop', reader: 'drop', audience: 'drop',+ package: 'drop', link: 'drop', template: 'drop', copyJSON: 'drop',+}++/** Extract the field names an app's class map assigns to class C. */+export type FieldsOfClass<M, C extends FieldClass> =+ { [K in keyof M]: M[K] extends C ? K : never }[keyof M]++/** A per-app guard: the fields classed 'mode' must be EXACTLY the kernel's mode+ * fields (readonly, template). Assign `true` to a value of this type in the app+ * (const _ok: ModeFieldsOk<AppMap> = true); a third field classed mode, or a+ * missing one, makes the type a diagnostic string and the assignment fails tsc. */+export type ModeFieldsOk<M> =+ [FieldsOfClass<M, 'mode'>] extends [ModeField]+ ? ([ModeField] extends [FieldsOfClass<M, 'mode'>] ? true+ : 'a kernel mode field is missing from this map')+ : 'a field is classed mode but has no MODE_FIELD_RULES entry'++export interface ProjectOpts {+ /** A freshly-minted invite keypair, required for the invite tier's collab projection. */+ readonly invite?: { role: string }+ /** App projection of a collab block for the audience tier (slides' audience.ts). */+ readonly projectAudience?: (collab: Obj) => Obj+}++/** Build a copy of `doc` for `tier`, FROM EMPTY, using only the rule tables and+ * the app's class map. A field is carried only if its cell says so; anything not+ * in `classes` follows UNKNOWN_RULE (fail-closed). Builders must NOT post-edit+ * identity/mode afterwards — the tables are the single source. */+export function projectForCopy<T extends object>(+ doc: T, classes: Record<string, FieldClass>, tier: Tier, opts: ProjectOpts = {},+): T {+ const src = doc as Obj+ const out: Obj = {}+ for (const key of Object.keys(src)) {+ const v = src[key]+ if (v === undefined) continue+ const cls = classes[key]+ const rule: Rule =+ cls === undefined ? UNKNOWN_RULE[tier]+ : cls === 'mode' ? ((MODE_FIELD_RULES[key as ModeField]?.[tier] as Rule | undefined) ?? UNKNOWN_RULE[tier])+ : (CLASS_RULES[cls][tier] as Rule)+ applyRule(out, key, v, rule, opts)+ }+ return out as T+}++function applyRule(out: Obj, key: string, v: unknown, rule: Rule, opts: ProjectOpts): void {+ if (rule === 'keep') { out[key] = v; return }+ if (rule === 'drop' || rule === 'reset') return // omit; a reset field is re-minted at load / by the builder+ if ('set' in rule) { out[key] = rule.set; return }+ // capability projection via a tier allowlist+ const block = v as Obj+ const projected =+ rule.allowlist === 'reader' ? collabForReader(block)+ : rule.allowlist === 'invite' ? (opts.invite ? collabForInvite(block, opts.invite) : undefined)+ : opts.projectAudience ? opts.projectAudience(block) : undefined+ if (projected !== undefined) out[key] = projected+}++/** Fields that do NOT count as unsaved work (excluded from docContentKey), kept+ * SEPARATE from any signing-exclusion set: conflating the two silently drops a+ * field (e.g. a signature) from crash recovery. Apps extend this with their own+ * bookkeeping fields. Capability fields are already excluded (a key/secret is+ * not a content edit); everything else — content, history, mode, identity, AND+ * an unknown field — counts, so recovery is conservative and never loses data. */+export const DEFAULT_NOT_EDIT: ReadonlySet<string> = new Set(['modified', 'preview', 'autosave'])++/** A stable key over the fields that count as unsaved work, for crash-recovery+ * comparison. ABSENT fields never change the key (skipped, never null-padded),+ * so a document without a newer field keys identically on an older build. */+export function docContentKey(+ doc: object, classes: Record<string, FieldClass>, notEdit: ReadonlySet<string> = DEFAULT_NOT_EDIT,+): string {+ const src = doc as Obj+ const picked: Obj = {}+ for (const key of Object.keys(src).sort()) {+ if (src[key] === undefined) continue+ if (notEdit.has(key)) continue+ if (classes[key] === 'capability') continue // secrets/keys are not a content edit+ picked[key] = src[key]+ }+ return JSON.stringify(picked)+}++/** The shared version-history entry. `body` is APP-DEFINED (a whole snapshot for+ * type, a structural patch for spaces); the kernel treats it as opaque. `label`+ * is OPTIONAL — an app-minted label is frozen in the saver's UI language, so a+ * summary is DERIVED from the body at render when absent. Lives under+ * doc.revisions. */+export interface Revision<Body = unknown> {+ readonly id: string+ readonly at: string+ readonly label?: string+ readonly body: Body+}++/** Envelope-only validation (id/at/label?/body present). Body validation is the+ * app's hook. Call this instead of a bare cast so a malformed entry can't crash+ * a reader. */+export function validateRevision(x: unknown): x is Revision {+ if (typeof x !== 'object' || x === null) return false+ const r = x as Obj+ return typeof r.id === 'string'+ && typeof r.at === 'string'+ && (r.label === undefined || typeof r.label === 'string')+ && 'body' in r+}diff --git a/kernel/src/docfields.typecheck.ts b/kernel/src/docfields.typecheck.tsnew file mode 100644index 00000000..6297e29f--- /dev/null+++ b/kernel/src/docfields.typecheck.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// TYPE-LEVEL test for the field-classification table. This file EMITS NOTHING+// (kernel/tsconfig.json has noEmit); its only job is to be type-checked by CI's+// "Typecheck kernel (standalone)" step (node_modules/.bin/tsc -p ../kernel),+// which includes "src". Every `@ts-expect-error` below marks a line that MUST+// fail to type-check; if a guard is weakened the error disappears, the directive+// becomes unused, and tsc fails the step — so the type half of the table is+// pinned, not merely asserted at runtime. Symbols are exported to satisfy+// noUnusedLocals.+//+// Verify by hand: delete the `readonly:` block from MODE_FIELD_RULES in+// docfields.ts and run `tsc -p kernel` — GOOD_OK below stops type-checking.++import {+ type FieldClass, type ModeFieldsOk, CLASS_RULES, MODE_FIELD_RULES,+} from './docfields.ts'++// A correct map: exactly readonly+template are 'mode'. This assignment HOLDS; it+// breaks (good) if a kernel mode field loses its MODE_FIELD_RULES entry.+export const GOOD = {+ docId: 'identity', title: 'content', collab: 'capability',+ readonly: 'mode', template: 'mode', revisions: 'history',+} satisfies Record<string, FieldClass>+export const GOOD_OK: ModeFieldsOk<typeof GOOD> = true++// A map that classes a THIRD field as 'mode' with no MODE_FIELD_RULES entry.+export const BAD_EXTRA_MODE = {+ docId: 'identity', readonly: 'mode', template: 'mode', locked: 'mode',+} satisfies Record<string, FieldClass>+// @ts-expect-error - `locked` is classed 'mode' but has no MODE_FIELD_RULES rule, so ModeFieldsOk is a diagnostic string, not `true`.+export const BAD_EXTRA_MODE_OK: ModeFieldsOk<typeof BAD_EXTRA_MODE> = true++// A map that omits a kernel mode field (template) from 'mode'.+export const BAD_MISSING_MODE = {+ docId: 'identity', readonly: 'mode', template: 'content',+} satisfies Record<string, FieldClass>+// @ts-expect-error - a kernel mode field is missing from the map, so ModeFieldsOk is a diagnostic string.+export const BAD_MISSING_MODE_OK: ModeFieldsOk<typeof BAD_MISSING_MODE> = true++// 'per-field' is allowed ONLY in the mode row of CLASS_RULES. A non-mode cell+// must reject it.+// @ts-expect-error - a content cell is a Rule and cannot hold the mode-only 'per-field' literal.+export const PER_FIELD_IN_CONTENT: (typeof CLASS_RULES)['content']['file'] = 'per-field'++// The mode row IS 'per-field' everywhere — a scalar Rule may not be written there.+// @ts-expect-error - the mode row only holds 'per-field'; 'keep' is not assignable.+export const KEEP_IN_MODE: (typeof CLASS_RULES)['mode']['reader'] = 'keep'++// MODE_FIELD_RULES is the single source for mode fields; referenced so the import+// is used and a typo in its shape surfaces here too.+export const MODE_FIELDS = Object.keys(MODE_FIELD_RULES)diff --git a/kernel/src/sync/crdt.ts b/kernel/src/sync/crdt.tsindex 2195fb98..01076a71 100644--- a/kernel/src/sync/crdt.ts+++ b/kernel/src/sync/crdt.ts@@ -132,7 +132,10 @@ export const shape = (text = 'html',maps: readonly string[] = [],): DocShape => {- const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version'])+ // 'revisions'/'trail' are in-file version history (docfields.ts class 'history'):+ // file-local, never synced — each replica keeps its own timeline. (PR2 turns+ // skipDoc into a content-class allowlist so unknown fields don't sync either.)+ const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version', 'revisions', 'trail'])// `assets` and `blobs` are per-key for every app and always have been —// unioned rather than defaulted so an app naming its own map cannot drop them.return { parents, children, text, skipDoc, maps: new Set(['assets', 'blobs', ...maps]) }diff --git a/scripts/test-field-class.ts b/scripts/test-field-class.tsnew file mode 100644index 00000000..6ed69f04--- /dev/null+++ b/scripts/test-field-class.ts@@ -0,0 +1,182 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Field-classification rig.+//+// node scripts/test-field-class.ts (Node >= 23.6 strips types natively)+//+// WHAT THIS PROVES. projectForCopy builds every outward copy FROM EMPTY using+// only the typed rule tables (docfields.ts CLASS_RULES + MODE_FIELD_RULES), so a+// field is carried only if a cell says so and an UNCLASSIFIED field fails CLOSED+// (dropped from every outward copy — the writerPriv lesson). It sets one field of+// every class per tier and asserts the EXACT top-level field set each tier emits,+// plus the two load-bearing rows (a reader copy is read-only; a template copy+// stays a template) and the unknown-key rule (kept only in the file + duplicate,+// dropped from invite too).+//+// Mutations (verified by editing kernel/src/docfields.ts and re-running; each+// reds a named row, listed in the PR): reclassify readonly as capability (a+// read-only copy comes out editable); drop reader's readonly set:true cell; make+// any cell default to 'keep'; keep an unknown key in an invite. The TYPE half+// (no default cell; 'per-field' only in the mode row; a mode field with no rule)+// is pinned by kernel/src/docfields.typecheck.ts, checked by CI's standalone+// kernel tsc.++import {+ projectForCopy, docContentKey, validateRevision, TIERS,+ type FieldClass, type Tier,+} from '../kernel/src/docfields.ts'++let checks = 0, failures = 0+function ok(cond: boolean, msg: string): void {+ checks+++ if (cond) { console.log(` ok ${msg}`); return }+ failures+++ console.log(` FAIL ${msg}`)+}+const keysOf = (o: object) => Object.keys(o).sort()+const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i])++// A live document with exactly one representative field per class, plus an+// UNCLASSIFIED ("mystery") key and the two volatile bookkeeping fields.+function liveDoc() {+ return {+ docId: 'D-1', // identity+ title: 'Secret plan', slides: ['a', 'b'], // content+ collab: { // capability+ room: 'w123', key: 'K', owner: 'O', writerPub: 'WP', on: true, v: 2,+ ownerPriv: 'OWNER-SECRET', writerPriv: 'WRITER-SECRET', sync: { s: 1 },+ invite: { role: 'writer' }, role: 'writer',+ },+ readonly: false, template: false, // mode+ revisions: [{ id: 'r1', at: 't', body: {} }], trail: [{ day: 1 }], // history+ modified: 123, preview: 'PNG', autosave: 'snap', // content, but NOT_EDIT+ mystery: 'FROM-A-NEWER-BUILD', // UNCLASSIFIED (absent from the map)+ }+}+const MAP: Record<string, FieldClass> = {+ docId: 'identity',+ title: 'content', slides: 'content', modified: 'content', preview: 'content', autosave: 'content',+ collab: 'capability',+ readonly: 'mode', template: 'mode',+ revisions: 'history', trail: 'history',+ // `mystery` deliberately unmapped.+}+const OPTS = { invite: { role: 'editor' }, projectAudience: (c: Record<string, unknown>) => ({ room: c.room, key: c.key, role: 'audience' }) }++// The EXACT top-level field set every tier must emit from liveDoc().+const EXPECT: Record<Tier, string[]> = {+ // everything, including the unknown key — the owner's own round-trip+ file: ['docId', 'title', 'slides', 'collab', 'readonly', 'template', 'revisions', 'trail', 'modified', 'preview', 'autosave', 'mystery'].sort(),+ // owner's own copy, new identity: docId + collab reset (absent), mystery kept+ duplicate: ['title', 'slides', 'readonly', 'template', 'revisions', 'trail', 'modified', 'preview', 'autosave', 'mystery'].sort(),+ // a file for another editor: collab projected, readonly AND template dropped+ // (template:true would make the invitee's open a roomless new doc), history kept, unknown dropped+ invite: ['docId', 'title', 'slides', 'collab', 'revisions', 'trail', 'modified', 'preview', 'autosave'].sort(),+ // read-only live viewer: readonly forced true, template dropped (would fork on open),+ // collab reader-projected, history dropped, unknown dropped+ reader: ['docId', 'title', 'slides', 'collab', 'readonly', 'modified', 'preview', 'autosave'].sort(),+ audience: ['docId', 'title', 'slides', 'collab', 'readonly', 'modified', 'preview', 'autosave'].sort(),+ // presentation package / player: collab dropped entirely, template dropped+ package: ['docId', 'title', 'slides', 'readonly', 'modified', 'preview', 'autosave'].sort(),+ // published link: reader-like+ link: ['docId', 'title', 'slides', 'collab', 'readonly', 'modified', 'preview', 'autosave'].sort(),+ // template copy: template forced true, readonly DROPPED (instances must be editable),+ // collab dropped, history dropped+ template: ['docId', 'title', 'slides', 'template', 'modified', 'preview', 'autosave'].sort(),+ // Copy document JSON: content only — collab, modes, history, unknown all gone+ copyJSON: ['docId', 'title', 'slides', 'modified', 'preview', 'autosave'].sort(),+}++console.log('projectForCopy emits exactly the ruled field set per tier')+for (const tier of TIERS) {+ const out = projectForCopy(liveDoc(), MAP, tier, OPTS)+ ok(same(keysOf(out), EXPECT[tier]), `${tier}: ${keysOf(out).join(',') || '(empty)'}`)+}++console.log('\nthe two load-bearing mode rows')+{+ const reader = projectForCopy(liveDoc(), MAP, 'reader', OPTS) as Record<string, unknown>+ ok(reader.readonly === true, 'a READER copy is read-only — readonly forced true even though the live value is false')+ const tpl = projectForCopy(liveDoc(), MAP, 'template', OPTS) as Record<string, unknown>+ ok(tpl.template === true, 'a TEMPLATE copy stays a template — template forced true')+ // the source here is read-only: a template carrying readonly would make every instance read-only+ const roSrc = { ...liveDoc(), readonly: true }+ const tplRo = projectForCopy(roSrc, MAP, 'template', OPTS) as Record<string, unknown>+ ok(!('readonly' in tplRo), 'a template copy of a READ-ONLY doc drops readonly, so instances open editable')+ const inv = projectForCopy(liveDoc(), MAP, 'invite', OPTS) as Record<string, unknown>+ ok(!('readonly' in inv), 'an INVITE copy drops readonly (absent), so the editor is not locked')+}++console.log('\ntemplate:true never rides a copy that must stay in its room')+{+ // parseDoc treats template:true as "this open IS a new document" (fresh docId,+ // collab deleted). A source that IS a template is the case that would fork.+ const tplSrc = { ...liveDoc(), template: true }+ for (const tier of ['invite', 'reader', 'audience', 'package', 'link'] as Tier[]) {+ const out = projectForCopy(tplSrc, MAP, tier, OPTS) as Record<string, unknown>+ ok(!('template' in out), `${tier} copy of a template drops template — it keeps its room instead of forking on open`)+ }+ for (const tier of ['file', 'duplicate'] as Tier[]) {+ const out = projectForCopy(tplSrc, MAP, tier, OPTS) as Record<string, unknown>+ ok(out.template === true, `${tier} keeps the source template flag (the owner's own round-trip)`)+ }+}++console.log('\ncapability is the only stripped class; secrets never ride a projected copy')+{+ const reader = projectForCopy(liveDoc(), MAP, 'reader', OPTS) as { collab: Record<string, unknown> }+ ok(!!reader.collab && reader.collab.ownerPriv === undefined && reader.collab.writerPriv === undefined,+ 'reader.collab carries no ownerPriv/writerPriv')+ ok(reader.collab.role === 'reader', 'reader.collab.role is forced to reader (never the source writer role)')+ ok(reader.collab.sync === undefined, 'reader.collab drops the CRDT sync stamp')+ const dup = projectForCopy(liveDoc(), MAP, 'duplicate', OPTS) as Record<string, unknown>+ ok(!('collab' in dup) && !('docId' in dup), 'a duplicate resets identity+capability (docId and collab both omitted, re-minted at load)')+}++console.log('\nthe unknown-key rule: file + duplicate only')+{+ for (const tier of TIERS) {+ const out = projectForCopy(liveDoc(), MAP, tier, OPTS) as Record<string, unknown>+ const kept = 'mystery' in out+ const shouldKeep = tier === 'file' || tier === 'duplicate'+ ok(kept === shouldKeep, `unknown key ${shouldKeep ? 'kept in' : 'dropped from'} ${tier}`)+ }+}++console.log('\nprojectForCopy builds from empty — a field absent from the live doc is never invented')+{+ const bare = { docId: 'D', title: 'only' }+ const out = projectForCopy(bare, MAP, 'reader', OPTS)+ ok(same(keysOf(out), ['docId', 'title']), 'only the present fields appear; no readonly/collab fabricated')+}++console.log('\ndocContentKey: counts content + history, excludes capability + bookkeeping, skips absent')+{+ const base = liveDoc()+ const k1 = docContentKey(base, MAP)+ ok(!k1.includes('OWNER-SECRET') && !k1.includes('writerPriv'), 'capability (collab) is excluded — editing a key is not a content edit')+ ok(!k1.includes('"modified"') && !k1.includes('"preview"') && !k1.includes('"autosave"'), 'bookkeeping (modified/preview/autosave) excluded')+ ok(k1.includes('revisions') && k1.includes('trail'), 'history counts as unsaved work (so recovery keeps it) — the signature/comment loss class')+ // editing content changes the key; touching only a bookkeeping field does not+ const edited = liveDoc(); edited.title = 'changed'+ ok(docContentKey(edited, MAP) !== k1, 'a title edit changes the key')+ const touched = liveDoc(); touched.modified = 999+ ok(docContentKey(touched, MAP) === k1, 'bumping modified alone does not change the key')+ // an ABSENT field never changes the key (older build stays byte-identical)+ const withExtra = liveDoc() as Record<string, unknown>; withExtra.newField = undefined+ ok(docContentKey(withExtra, MAP) === k1, 'an undefined field is skipped, never null-padded — an older build keys identically')+}++console.log('\nvalidateRevision: envelope only, body opaque')+{+ ok(validateRevision({ id: '1', at: 't', body: { anything: true } }), 'id+at+body ok (label optional)')+ ok(validateRevision({ id: '1', at: 't', label: 'typed', body: [] }), 'label allowed when a string')+ ok(!validateRevision({ id: '1', at: 't' }), 'missing body rejected')+ ok(!validateRevision({ id: 1, at: 't', body: {} }), 'non-string id rejected')+ ok(!validateRevision({ id: '1', at: 't', label: 7, body: {} }), 'non-string label rejected')+ ok(!validateRevision(null), 'null rejected (no crash on a malformed entry)')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-sync-shape.ts b/scripts/test-sync-shape.tsindex 7ef45322..a080d411 100644--- a/scripts/test-sync-shape.ts+++ b/scripts/test-sync-shape.ts@@ -115,8 +115,12 @@ const spacesDoc = (blocks: unknown[]) => ({{ok(SLIDES_SHAPE.parents === 'slides' && SLIDES_SHAPE.children === 'elements','slides still means slides → elements')- ok([...SLIDES_SHAPE.skipDoc].sort().join(',') === 'collab,format,modified,slides,version',- 'and its skip set is exactly what the shipped engine hardcoded')+ // EXACT pin — any change to the skip set must be deliberate and land here.+ // `revisions` and `trail` joined it with the field-classification ruling+ // (kernel/src/docfields.ts, class 'history'): in-file version history is+ // file-local and never synced. Everything else is the shipped engine's set.+ ok([...SLIDES_SHAPE.skipDoc].sort().join(',') === 'collab,format,modified,revisions,slides,trail,version',+ 'and its skip set is exactly the shipped engine set plus the history class (revisions, trail)')}// ---- stamping WITHOUT the token history ------------------------------------