From 1a63a3a2727d9de2a212e1d935e71673e9b95278 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 23:09:52 +0000 Subject: [PATCH 1/9] fix(metadata-protocol): the protocol-19 switch writes moved stored forms without the old data binding The stored-form ceremony moved each form "with its body as written", which kept an 18.x Studio save's `data: { provider: 'object', object }` binding: a `form` item refuses `data` by name, so every moved form was served invalid. The move now drops a plain object binding (the source conversion's own test), and the census judges every body the run writes or keeps with the runtime's `form` schema: a refused body refuses the run before anything is written, and the switch is never recorded over one. The action for a kept row names its package's door (`?package=`). Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../39393-stored-form-switch-drops-data.md | 17 ++ packages/cli/src/commands/migrate/protocol.ts | 65 ++++- .../cli/src/commands/migrate/stored-forms.ts | 48 +++- .../src/protocol-stored-form-39393.test.ts | 179 +++++++++++++ .../src/protocol-stored-form-apply.ts | 103 ++------ .../src/protocol-stored-form-bodies.ts | 242 ++++++++++++++++++ .../src/protocol-stored-form-migration.ts | 13 +- 7 files changed, 573 insertions(+), 94 deletions(-) create mode 100644 .changeset/39393-stored-form-switch-drops-data.md create mode 100644 packages/metadata-protocol/src/protocol-stored-form-39393.test.ts create mode 100644 packages/metadata-protocol/src/protocol-stored-form-bodies.ts diff --git a/.changeset/39393-stored-form-switch-drops-data.md b/.changeset/39393-stored-form-switch-drops-data.md new file mode 100644 index 00000000000..889fb2950bb --- /dev/null +++ b/.changeset/39393-stored-form-switch-drops-data.md @@ -0,0 +1,17 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +fix(cli): `os migrate protocol --to 19 --apply` writes each moved stored form without the old `data` binding, and never switches over a form the runtime would serve invalid + +Clause-②: no +Metadata-protocol: none + +Who sees it: an administrator upgrading a deployment whose 18.x database holds forms edited in Studio (a view's `form` or `formViews` saved with the view). + +- **A moved form no longer keeps `data`.** The protocol-19 switch moved each stored form "with its body as written", and an 18.x Studio save stores a form's object binding as `data: { provider: 'object', object }`. A `form` item refuses `data` by name, so every moved form was served `valid: false` and the `form` door refused the same body. The switch now drops a plain object binding, as `os migrate meta --from 18 --write` does for a form in source; the rest of the body moves as written. +- **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. +- **The fix names the package.** For a stored `form` row served invalid, the action is `PUT /api/v1/meta/form/NAME?package=PACKAGE`: the save door addresses a package's row only with `?package=`. + +A deployment that already switched on `19.0.0-next.4` and holds moved forms with `data`: run `os migrate stored-forms` to list them, and save each again without `data` through the door it names. diff --git a/packages/cli/src/commands/migrate/protocol.ts b/packages/cli/src/commands/migrate/protocol.ts index 135e51f7da6..dfa935226cb 100644 --- a/packages/cli/src/commands/migrate/protocol.ts +++ b/packages/cli/src/commands/migrate/protocol.ts @@ -22,7 +22,15 @@ import { describeUnloadableHostConfig } from '../../utils/schema-migration-plugi import { absentTableReads } from '../../utils/absent-table-reads.js'; import { OCCUPANCY_STOP_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; -import { storedFormAddressText, storedFormPlanText, storedFormRowText, storedFormRunRefusal } from './stored-forms.js'; +import { + storedFormAddressText, + storedFormBodyRefusals, + storedFormBodyRefusalSummary, + storedFormBodyRefusalText, + storedFormPlanText, + storedFormRowText, + storedFormRunRefusal, +} from './stored-forms.js'; /** The protocol majors this command switches a deployment to. */ const SWITCH_MAJORS = [19] as const; @@ -49,13 +57,21 @@ export function protocolHolds(census: StoredFormCensus): StoredFormHold[] { } /** - * Whether a census verifies the switch: the precheck lets it switch, and - * nothing is left to move or remove (a ceremony that committed leaves every - * moved form a stored `form` row, which the census reads as kept). + * Whether a census verifies the switch: the precheck lets it switch, nothing + * is left to move or remove (a ceremony that committed leaves every moved form + * a stored `form` row, which the census reads as kept), and no form row it + * keeps is one the protocol-19 `form` schema refuses (ADR-0159 D2): a switch + * is never recorded over a form the runtime serves invalid. */ export function censusVerifiesSwitch(census: StoredFormCensus): boolean { const { canSwitch, counts } = census.precheck; - return canSwitch && counts.move === 0 && counts.remove === 0 && counts.hold === 0; + return canSwitch && counts.move === 0 && counts.remove === 0 && counts.hold === 0 && storedFormBodyRefusals(census).length === 0; +} + +/** The refusal when a form body the protocol-19 `form` schema refuses stands: nothing is written. */ +export function protocolBodyRefusalText(to: number, census: StoredFormCensus): string { + return `The deployment does not switch to protocol ${to}: ${storedFormBodyRefusalSummary(storedFormBodyRefusals(census))} ` + + `Take each action, then run \`os migrate protocol --to ${to}\` again. Nothing was written.`; } /** The refusal sentence when the deployment cannot switch, naming where each action is taken. */ @@ -127,6 +143,13 @@ async function confirm(question: string): Promise { * is taken on (the one running now). `--json` carries the same holds. No new * protocol error code: the refusal is the command's. * + * A form body the protocol-19 `form` schema refuses refuses the switch too, + * before anything is written (ADR-0159 D2): one the ceremony would write, or a + * stored `form` row the census keeps, which the runtime serves invalid. Each is + * listed with the site, the schema's words and the action, whose door names + * the package the row is saved in (`?package=`). A switch is never recorded + * over one. + * * `os migrate stored-forms` stays the read-only look and has no `--apply`. * * Exit status: 0 when the preview finds a deployment that can switch, or when @@ -282,7 +305,8 @@ export default class MigrateProtocol extends Command { if (!apply) { const holds = protocolHolds(before); const runRefused = storedFormRunRefusal(before, (protocol as { engine?: unknown }).engine); - const canSwitch = before.precheck.canSwitch && runRefused === undefined; + const bodyRefusals = storedFormBodyRefusals(before); + const canSwitch = before.precheck.canSwitch && runRefused === undefined && bodyRefusals.length === 0; if (json) { reads.notice(true); await emitJson({ @@ -291,6 +315,7 @@ export default class MigrateProtocol extends Command { ...(runRefused !== undefined ? { runRefused } : {}), counts: before.precheck.counts, holds, + bodyRefusals, forms: before.forms, drafts: before.drafts, sharedSlugs: before.sharedSlugs, @@ -309,6 +334,10 @@ export default class MigrateProtocol extends Command { printWarning(protocolRefusalText(to, holds)); return 1; } + if (bodyRefusals.length > 0) { + printWarning(protocolBodyRefusalText(to, before)); + return 1; + } printSuccess(`The deployment can switch to protocol ${to}. Run \`os migrate protocol --to ${to} --apply\` to switch ${chalk.dim(`(${timer.display()})`)}`); return 0; } @@ -318,12 +347,13 @@ export default class MigrateProtocol extends Command { // roll back are refused here, before the ceremony is asked. const engine = (protocol as { engine?: unknown }).engine; const runRefused = storedFormRunRefusal(before, engine); - if (!before.precheck.canSwitch || runRefused !== undefined) { + const bodyRefusals = storedFormBodyRefusals(before); + if (!before.precheck.canSwitch || runRefused !== undefined || bodyRefusals.length > 0) { const holds = protocolHolds(before); - const message = runRefused ?? protocolRefusalText(to, holds); + const message = runRefused ?? (before.precheck.canSwitch ? protocolBodyRefusalText(to, before) : protocolRefusalText(to, holds)); if (json) { reads.notice(true); - await emitJson({ ...header, switched: false, canSwitch: false, refusal: message, counts: before.precheck.counts, holds, duration: timer.elapsed() }); + await emitJson({ ...header, switched: false, canSwitch: false, refusal: message, counts: before.precheck.counts, holds, bodyRefusals, duration: timer.elapsed() }); return 1; } this.printPreamble(stack, reads); @@ -358,17 +388,19 @@ export default class MigrateProtocol extends Command { // The ceremony committed but the re-run still finds work: no marker. // The commit cannot be undone here, so the message says what it left. const holds = protocolHolds(after); + const afterRefusals = storedFormBodyRefusals(after); const message = `The stored forms have already moved: the transaction committed, and the rows listed above are form rows now. ` - + `The census run again still finds ${after.precheck.counts.move} to move, ${after.precheck.counts.remove} to remove ` - + `and ${holds.length} holding the switch, so the switch was not recorded. Do not start this deployment on the release ` + + `The census run again still finds ${after.precheck.counts.move} to move, ${after.precheck.counts.remove} to remove, ` + + `${holds.length} holding the switch and ${afterRefusals.length} form row(s) the form schema refuses, so the switch was not recorded. Do not start this deployment on the release ` + 'it was running: that release reads a form only from a view row, so it cannot read a moved form or the switch-off it ' + `carries. Take each action listed, then run \`os migrate protocol --to ${to} --apply --yes\` again until it records the switch.`; if (json) { - await emitJson({ ...header, switched: false, moved: true, canSwitch: after.precheck.canSwitch, refusal: message, counts: after.precheck.counts, holds, ceremony: ceremonyJson(result), duration: timer.elapsed() }); + await emitJson({ ...header, switched: false, moved: true, canSwitch: after.precheck.canSwitch, refusal: message, counts: after.precheck.counts, holds, bodyRefusals: afterRefusals, ceremony: ceremonyJson(result), duration: timer.elapsed() }); return 1; } this.printCeremony(result); this.printHolds(holds); + this.printBodyRefusals(afterRefusals); printError(message); return 1; } @@ -428,6 +460,7 @@ export default class MigrateProtocol extends Command { for (const d of census.drafts) console.log(` • ${d.type} "${d.name}", ${d.packageId !== undefined ? `package '${d.packageId}'` : 'no package'}`); console.log(''); } + this.printBodyRefusals(storedFormBodyRefusals(census)); for (const shared of census.sharedSlugs) { printInfo(`/forms/${shared.slug} is declared by ${shared.forms.map((f) => `'${f}'`).join(' and ')}.`); } @@ -435,6 +468,14 @@ export default class MigrateProtocol extends Command { printInfo(`${c.keep} kept, ${c.move} to move, ${c.remove} to remove, ${c.left_in_place} left in place, ${census.precheck.holds.length} holding the switch.`); } + /** Each form body the protocol-19 `form` schema refuses, with its site and the action for it (ADR-0159 D2). */ + private printBodyRefusals(refusals: ReturnType): void { + if (refusals.length === 0) return; + console.log(chalk.bold(`${refusals.length} form body(ies) the protocol-19 form schema refuses:`)); + for (const refusal of refusals) console.log(` • ${storedFormBodyRefusalText(refusal)}`); + console.log(''); + } + /** What the ceremony wrote and removed: each moved row, and each removed form with its body. */ private printCeremony(result: StoredFormApplyResult | undefined): void { const c = ceremonyJson(result); diff --git a/packages/cli/src/commands/migrate/stored-forms.ts b/packages/cli/src/commands/migrate/stored-forms.ts index 53262aef1e0..a7bc088945e 100644 --- a/packages/cli/src/commands/migrate/stored-forms.ts +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -52,6 +52,31 @@ export function storedFormRunRefusal(census: StoredFormCensus, engine: unknown): + 'Run the upgrade against a database whose driver supports transactions, or stay on the release you are running.'; } +/** A body the protocol-19 `form` schema refuses, as the census reports it (ADR-0159 D2). */ +export type StoredFormBodyRefusal = NonNullable[number]; + +/** The census's verdict on the bodies it plans to write or keeps: every one the `form` schema refuses. */ +export function storedFormBodyRefusals(census: StoredFormCensus): readonly StoredFormBodyRefusal[] { + return census.bodyRefusals ?? []; +} + +/** One refused body: the row, the site the schema names, its words, and the action (which names the package's door). */ +export function storedFormBodyRefusalText(refusal: StoredFormBodyRefusal): string { + const verb = refusal.outcome === 'move' ? 'would be written as a form row the protocol-19 form schema refuses' : 'is a form row the protocol-19 form schema refuses, so it is served invalid'; + return `${storedFormRowText(refusal.row)}: '${refusal.form}' ${verb}, at ${refusal.path || '(root)'}: ${refusal.message} ${refusal.action}`; +} + +/** The sentence beneath the refused bodies: the upgrade does not run, or is not clean, while one stands. */ +export function storedFormBodyRefusalSummary(refusals: readonly StoredFormBodyRefusal[]): string { + const writes = refusals.filter((r) => r.writes).length; + const served = refusals.length - writes; + return [ + writes > 0 ? `${writes} form(s) the upgrade would write are refused by the protocol-19 form schema, so the upgrade's run writes nothing while they stand.` : '', + served > 0 ? `${served} stored form row(s) are served invalid today.` : '', + 'Each is listed above with the action for it.', + ].filter((part) => part !== '').join(' '); +} + /** One row as the report names it. */ export function storedFormRowText(row: StoredFormRowRef): string { const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; @@ -181,9 +206,14 @@ function holdText(hold: StoredFormHold): string { * `serve`'s two flags that move that composition, with its meaning. The boot * is read-only (deferred DDL, no seed, no file brought into existence). * - * Exit status: 0 when the census ran, whatever it found (`precheck.canSwitch` - * in `--json` says whether the upgrade would switch); 1 when the composition - * could not be read or booted. + * A form body the protocol-19 `form` schema refuses is listed with its site, + * the schema's words and the action (`bodyRefusals`): one the upgrade would + * write refuses the upgrade's run, and a stored `form` row the census keeps is + * served invalid today. The report is never green over one (ADR-0159 D2). + * + * Exit status: 0 when the census ran, whatever it found (`canSwitch` in + * `--json` says whether the upgrade would switch, a refused body included); 1 + * when the composition could not be read or booted. */ export default class MigrateStoredForms extends Command { static override description = @@ -284,16 +314,18 @@ export default class MigrateStoredForms extends Command { const census = reads.absent('sys_metadata') ? EMPTY : await listStoredFormsOf(protocol as Parameters[0]); const { precheck } = census; const runRefused = storedFormRunRefusal(census, (protocol as { engine?: unknown }).engine); + const bodyRefusals = storedFormBodyRefusals(census); if (json) { reads.notice(true); await emitJson({ database: stack.dbLabel, hostConfig: stack.composition.hostConfigPath, - canSwitch: precheck.canSwitch, + canSwitch: precheck.canSwitch && bodyRefusals.length === 0, ...(runRefused !== undefined ? { runRefused } : {}), counts: precheck.counts, holds: precheck.holds, + bodyRefusals, forms: census.forms, unreadable: census.unreadable, drafts: census.drafts, @@ -326,6 +358,11 @@ export default class MigrateStoredForms extends Command { for (const d of census.drafts) console.log(` • ${d.type} "${d.name}", ${d.packageId !== undefined ? `package '${d.packageId}'` : 'no package'}`); console.log(''); } + if (bodyRefusals.length > 0) { + console.log(chalk.bold(`${bodyRefusals.length} form body(ies) the protocol-19 form schema refuses:`)); + for (const refusal of bodyRefusals) console.log(` • ${storedFormBodyRefusalText(refusal)}`); + console.log(''); + } for (const shared of census.sharedSlugs) { printInfo(`/forms/${shared.slug} is declared by ${shared.forms.map((f) => `'${f}'`).join(' and ')}.`); } @@ -333,6 +370,9 @@ export default class MigrateStoredForms extends Command { printInfo(`${c.keep} kept, ${c.move} to move, ${c.remove} to remove, ${c.left_in_place} left in place, ${precheck.holds.length} holding the upgrade.`); if (runRefused !== undefined) { printWarning(runRefused); + } else if (bodyRefusals.length > 0) { + // Never green over a body the runtime would serve invalid (ADR-0159 D2). + printWarning(storedFormBodyRefusalSummary(bodyRefusals)); } else if (precheck.canSwitch) { printSuccess(`The upgrade can switch: no stored row holds it ${chalk.dim(`(${timer.display()})`)}`); } else { diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts new file mode 100644 index 00000000000..66281fdf059 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -0,0 +1,179 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D2, D7] The body the stored-form ceremony writes, and the + * census's verdict on it (`protocol-stored-form-bodies.ts`). + * + * The ceremony moves a stored old-shape form "with its body as written". The + * old shapes bind a form with `data` (`{ provider: 'object', object }`), which + * a `form` item refuses by name: a moved row that kept it was served + * `valid: false`, and the `form` save door refused the same body. The move now + * drops a plain object binding, as the source conversion + * `view-forms-to-form-items` does; any body the `form` schema still refuses is + * named by the census (`bodyRefusals`), which refuses the run before anything + * is written, and a stored `form` row served invalid today is named with the + * door of the package it is saved in. + * + * The rows are built as the `form` read builds them + * (`storedViewRowHoldings`), and the plans by the census's own planner. + */ +import { describe, expect, it } from 'vitest'; +import { installedManifestsOf } from '@objectstack/metadata-core'; +import { deriveViewContainerObject, expandViewContainer } from '@objectstack/spec'; +import { FormSchema } from '@objectstack/spec/ui'; +import { storedViewRowHoldings, type StoredFormPlace } from './protocol-form-reads.js'; +import { + plannedFormWrite, + servedFormBody, + storedFormBodyRefusals, + storedFormBodyRefusalText, + withoutPlainObjectBinding, +} from './protocol-stored-form-bodies.js'; +import { + planStoredForms, + type PairFixReading, + type ShippedForm, + type StoredFormAddressPlan, + type StoredFormPlanInput, +} from './protocol-stored-form-migration.js'; + +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const OBJECT = 'crm_lead'; +const NAME = `${OBJECT}.intake`; +const SLUG = 'lead-intake'; +const BINDING = { provider: 'object', object: OBJECT }; + +const expandHost = { + expandStoredViewContainers: (_type: string, entries: readonly { data: unknown; packageId: string | undefined }[]) => + entries.flatMap((container) => { + const object = deriveViewContainerObject(container.data) ?? ''; + return expandViewContainer(object, container.data).map((item) => ({ item: item as unknown as Record, container })); + }), +} as never; + +const sharing = (enabled: boolean) => ({ sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true } }); + +/** A stored container, as Studio saved it on 18.x: its forms carry the old `data` binding. */ +function containerRow(name: string, data: Record, packageId?: string): StoredFormPlace { + const entry = { name, data: { name, ...data }, packageId, organizationId: null, type: 'view' }; + return { type: 'view', packageId, entry, grain: 'expansion', holds: storedViewRowHoldings(expandHost, entry) }; +} + +/** A stored `form` row: a pair's declared override when bound to the pair. */ +function formRow(body: Record, packageId?: string): StoredFormPlace { + const data = { name: NAME, object: OBJECT, ...body }; + const entry = { name: NAME, data, packageId, organizationId: null, type: 'form' }; + return { type: 'form', packageId, entry, grain: 'item', holds: new Map([[NAME, { kind: 'form', item: data }]]) }; +} + +const PAIR_OK: PairFixReading = { ok: true, pair: PAIR, basedOn: '1.0.0' }; +const linkedBase = { [NAME]: [{ packageId: BASE, writable: false, form: { name: NAME, object: OBJECT, ...sharing(true) } }] }; + +function plan(places: StoredFormPlace[], ships: Record = linkedBase, over: Partial = {}) { + return planStoredForms({ + places, + installed: installedManifestsOf(undefined), + shippedForms: (name) => ships[name] ?? [], + shipsView: (name) => (ships[name] ?? []).map((s) => s.packageId), + isWritable: (pkg) => pkg === PAIR, + actionTargets: new Set(), + pairFix: () => PAIR_OK, + sealedFormShippers: () => [], + servedToday: () => true, + objectHasFieldGroups: () => true, + unreadable: [], + ...over, + }); +} + +const written = (p: StoredFormAddressPlan, place: StoredFormPlace) => + plannedFormWrite(p as StoredFormAddressPlan & { outcome: 'move' | 'keep' }, place); + +describe('[ADR-0159 D2] the ceremony writes a moved form without the old `data` binding', () => { + // The 18.x Studio save of a showcase view: the container's named form carries `data`. + const container = () => containerRow(OBJECT, { + object: OBJECT, + list: { type: 'grid', columns: ['name'], data: BINDING }, + formViews: { intake: { type: 'simple', data: BINDING, sections: [{ fields: [{ field: 'name' }] }], ...sharing(false) } }, + }); + + it('the written row keeps no `data`, and the protocol-19 form schema accepts it (ablate: write the projected body as it is)', () => { + const place = container(); + const census = plan([place]); + const [move] = census.forms; + expect(move).toMatchObject({ form: NAME, outcome: 'move', destination: { kind: 'pair_override', pair: PAIR } }); + const row = written(move!, place); + expect(row?.key).toEqual({ type: 'form', name: NAME, packageId: PAIR }); + expect(Object.keys(row!.body).sort()).toEqual(['name', 'object', 'overrides', 'sections', 'sharing', 'type']); + // The body as written otherwise: its switch-off included (D7-a). + expect(row!.body.sharing).toEqual({ publicLink: `/forms/${SLUG}`, enabled: false, allowAnonymous: true }); + const parsed = FormSchema.safeParse(row!.body); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + expect(storedFormBodyRefusals(census.forms, [place])).toEqual([]); + }); + + it('a binding that is not a plain object binding is kept, and the census names it: the run would write a body the schema refuses', () => { + const schemaBound = { provider: 'schema', schema: { type: 'object' } }; + expect(withoutPlainObjectBinding({ object: OBJECT, data: schemaBound })).toEqual({ object: OBJECT, data: schemaBound }); + // A binding to another object is not this form's binding either. + expect(withoutPlainObjectBinding({ object: OBJECT, data: { provider: 'object', object: 'crm_other' } })) + .toHaveProperty('data'); + const place = containerRow(OBJECT, { + object: OBJECT, + formViews: { intake: { type: 'simple', data: { ...schemaBound, object: OBJECT }, sections: [{ fields: [{ field: 'name' }] }], ...sharing(true) } }, + }); + const census = plan([place]); + const refusals = storedFormBodyRefusals(census.forms, [place]); + expect(refusals).toEqual([expect.objectContaining({ form: NAME, outcome: 'move', writes: true, path: '' })]); + expect(refusals[0]!.message).toContain('data'); + // The action names the door of the row as it is stored, today. + expect(refusals[0]!.action).toContain(`PUT /api/v1/meta/view/${OBJECT}`); + }); + + it('the report of a removed internal record form still writes out its body as it was stored', () => { + const place = containerRow(OBJECT, { object: OBJECT, form: { type: 'simple', data: BINDING, sections: [{ fields: [{ field: 'name' }] }] } }); + expect(servedFormBody(place, `${OBJECT}.form`)).toMatchObject({ data: BINDING }); + }); +}); + +describe('[ADR-0159 D3] a container stored under a name apart from its object', () => { + it('its form is served as OBJECT.CONTAINER.KEY, which the form schema refuses: the census names it and the run would write nothing (ablate: no verdict on the body)', () => { + const place = containerRow(`${OBJECT}_quick`, { object: OBJECT, form: { type: 'simple', sections: [{ fields: [{ field: 'name' }] }], ...sharing(true) } }); + const census = plan([place], {}); + const name = `${OBJECT}.${OBJECT}_quick.form`; + expect(census.forms).toEqual([expect.objectContaining({ form: name, outcome: 'move', destination: { kind: 'environment_form' } })]); + const refusals = storedFormBodyRefusals(census.forms, [place]); + expect(refusals).toEqual([expect.objectContaining({ form: name, outcome: 'move', writes: true, path: 'name' })]); + expect(storedFormBodyRefusalText(refusals)).toContain('Nothing was written'); + }); +}); + +describe('[ADR-0159 D2] a stored `form` row the census keeps is judged as it is served', () => { + it('a row a previous switch wrote with `data` is named, with the door of the package it is saved in (ablate: drop `?package=`)', () => { + const place = formRow({ type: 'simple', data: BINDING, sections: [{ fields: [{ field: 'name' }] }], overrides: { package: BASE, basedOn: '1.0.0' } }, PAIR); + const census = plan([place]); + expect(census.forms).toEqual([expect.objectContaining({ form: NAME, outcome: 'keep' })]); + const refusals = storedFormBodyRefusals(census.forms, [place]); + expect(refusals).toEqual([expect.objectContaining({ form: NAME, outcome: 'keep', writes: false, path: '' })]); + expect(refusals[0]!.action).toContain(`PUT /api/v1/meta/form/${NAME}?package=${PAIR}`); + }); + + it('CONTROL: a kept row the schema accepts is not named', () => { + const place = formRow({ type: 'simple', sections: [{ fields: [{ field: 'name' }] }], overrides: { package: BASE, basedOn: '1.0.0' } }, PAIR); + expect(storedFormBodyRefusals(plan([place]).forms, [place])).toEqual([]); + }); + + it('a kept row the run writes again to carry a withdrawal is written without its plain `data` binding', () => { + const kept = formRow({ type: 'simple', data: BINDING, sections: [{ fields: [{ field: 'name' }] }], overrides: { package: BASE, basedOn: '1.0.0' }, ...sharing(true) }, PAIR); + // A package-less row behind it that withdraws the form: the kept row takes its switch (D7-d). + const behind = containerRow(OBJECT, { object: OBJECT, formViews: { intake: { type: 'simple', sections: [{ fields: [{ field: 'name' }] }], ...sharing(false) } } }); + const census = plan([kept, behind]); + const keep = census.forms.find((p) => p.outcome === 'keep'); + expect(keep).toMatchObject({ carries: { slug: SLUG } }); + const row = written(keep!, kept); + expect(row!.body).not.toHaveProperty('data'); + expect(row!.body.sharing).toMatchObject({ enabled: false }); + expect(storedFormBodyRefusals(census.forms, [kept, behind])).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-stored-form-apply.ts b/packages/metadata-protocol/src/protocol-stored-form-apply.ts index edc305d6542..1d992d80247 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-apply.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-apply.ts @@ -23,12 +23,18 @@ * public form may re-open), so a switch-off is never left in a `form` row the * pre-upgrade release does not read. * + * ⛔ Nor does it write a body the `form` schema refuses: where the census's + * verdict refuses one the run would write (`bodyRefusals`), the run throws + * before anything is written, naming each row, the site and the action. + * * ## The writes * * 1. The pairs the moves land in are ensured through the ensure door, the * only creation path (ADR-0146 D3), before anything else is written. * 2. Each destination row is written: a `form` row with the served body as - * written (D7-a, D7-b), the withdrawal a folded row carries switched off + * written (D7-a, D7-b), less a plain `data` object binding a `form` item + * does not carry (D2; `protocol-stored-form-bodies.ts`, the source + * conversion's own test), the withdrawal a folded row carries switched off * on it (D7-d), and, at a base, the declared override of the base * (`overrides: { package, basedOn }`); the pair's own `form` item * (`pair_form`, maintainer ruling `7250977204`) declares none. A stored @@ -60,11 +66,18 @@ */ import { engineCanRollBack } from '@objectstack/core'; -import { isAggregatedViewContainer, PROJECTED_FORM_SOURCE_KEY } from '@objectstack/spec/ui'; +import { isAggregatedViewContainer } from '@objectstack/spec/ui'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; import { oldShapeFormRowRemovals } from './protocol-form-writes.js'; import { storedFormPlaces, storedViewRowHoldings, type StoredFormPlace } from './protocol-form-reads.js'; import { protocolHost, type ProtocolHost } from './protocol-host.js'; +import { + placeOfStoredForm as placeOf, + plannedFormWrite, + servedFormBody, + storedFormBodyRefusalText, + type StoredFormRowKey, +} from './protocol-stored-form-bodies.js'; import { listStoredForms, type StoredFormAddressPlan, @@ -76,11 +89,7 @@ import { import type { ObjectStackProtocolImplementation } from './protocol.js'; /** A stored row the ceremony wrote, re-saved or deleted, by its key. */ -export interface StoredFormRowKey { - readonly type: string; - readonly name: string; - readonly packageId?: string; -} +export type { StoredFormRowKey } from './protocol-stored-form-bodies.js'; /** One `form` row the ceremony wrote (a move, or a carried withdrawal on a row already in place). */ export interface StoredFormWritten { @@ -126,68 +135,8 @@ export type StoredFormApplyHost = StoredFormCensusHost readonly ensurePair: (base: string) => Promise; }; -const isRecord = (value: unknown): value is Record => - !!value && typeof value === 'object' && !Array.isArray(value); - const rowKeyOf = (type: string, name: string, packageId: string | undefined): string => `${type}\u0000${name}\u0000${packageId ?? ''}`; -/** The stored row a reference names, among the places the census read. */ -function placeOf(places: readonly StoredFormPlace[], ref: StoredFormRowRef): StoredFormPlace { - const place = places.find((p) => p.entry.type === ref.type && p.entry.name === ref.name - && p.packageId === ref.packageId && p.grain === ref.grain && p.holds.has(ref.form)); - if (place === undefined) { - throw new Error(`The stored ${ref.type} row '${ref.name}' the plan for '${ref.form}' names was not found again; nothing was written.`); - } - return place; -} - -/** - * The form body a row holds at `form`, as the read serves it, cleaned of the - * read's envelope: the projection's source marker, and the provenance a - * container's expansion wears from the package that ships the container - * (`_packageId`, `_packageVersion`, `_provenance`). The destination row's - * package is its own provenance; a base's stamp written into a pair's or a - * package-less row would read as that base's shipped code. - */ -function formBodyOf(place: StoredFormPlace, form: string): Record { - const holding = place.holds.get(form); - if (holding?.kind !== 'form') throw new Error(`The stored ${place.entry.type} row '${place.entry.name}' holds no form at '${form}'.`); - const { - _packageId: _pkg, _packageVersion: _version, _provenance: _prov, - [PROJECTED_FORM_SOURCE_KEY]: _source, ...body - } = holding.item as Record; - return { ...body, name: form }; -} - -/** The row a destination is, and the body written there. */ -function destinationRow( - destination: StoredFormDestination, - form: string, - body: Record, -): { key: StoredFormRowKey; packageId: string | null; body: Record } { - const { overrides: _declared, ...undeclared } = body; - switch (destination.kind) { - case 'pair_override': - return { - key: { type: 'form', name: form, packageId: destination.pair }, - packageId: destination.pair, - body: { ...undeclared, overrides: { package: destination.base, basedOn: destination.basedOn } }, - }; - case 'pair_form': - // [maintainer ruling 7250977204] The pair's own item: no `overrides`. - return { key: { type: 'form', name: form, packageId: destination.pair }, packageId: destination.pair, body: undeclared }; - case 'package_form': - return { key: { type: 'form', name: form, packageId: destination.packageId }, packageId: destination.packageId, body: undeclared }; - case 'environment_form': - return { key: { type: 'form', name: form }, packageId: null, body: undeclared }; - } -} - -/** The body with its `sharing` switched off, its link kept (the carried withdrawal, D7-d). */ -function switchedOff(body: Record): Record { - return { ...body, sharing: { ...(isRecord(body.sharing) ? body.sharing : {}), enabled: false } }; -} - /** * [ADR-0159 D7; rulings 7142585849 (items 2 and 3), 7250977204, 7249158572, * 7265816895] The ceremony's write half. See the module header. @@ -199,6 +148,10 @@ export async function applyStoredForms(host: StoredFormApplyHost, request: { act const nothing = { census, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }; // All or nothing: a row that holds the upgrade holds every write. if (!census.precheck.canSwitch) return { applied: false, ...nothing }; + // ⛔ Nor is a body the `form` schema refuses ever written: the runtime would + // serve it invalid (ADR-0159 D2). The switch command refuses before it asks. + const refused = (census.bodyRefusals ?? []).filter((r) => r.writes); + if (refused.length > 0) throw new Error(storedFormBodyRefusalText(refused)); const places = await storedFormPlaces(host); const writes = new Map }>(); @@ -212,9 +165,9 @@ export async function applyStoredForms(host: StoredFormApplyHost, request: { act entry.forms.add(ref.form); goes.set(key, entry); }; - const write = (plan: StoredFormAddressPlan & { outcome: 'keep' | 'move' }, body: Record): void => { - const carried = plan.carries !== undefined ? switchedOff(body) : body; - const row = destinationRow(plan.destination, plan.form, carried); + const write = (plan: StoredFormAddressPlan & { outcome: 'keep' | 'move' }, place: StoredFormPlace): void => { + const row = plannedFormWrite(plan, place); + if (row === undefined) return; const key = rowKeyOf(row.key.type, row.key.name, row.key.packageId); if (writes.has(key)) { // The planner holds a slot more than one plan claims; reaching here is a planner defect, never a guess. @@ -232,19 +185,15 @@ export async function applyStoredForms(host: StoredFormApplyHost, request: { act for (const plan of census.forms) { if (plan.outcome === 'move') { - write(plan, formBodyOf(placeOf(places, plan.served), plan.form)); + write(plan, placeOf(places, plan.served)); take(plan.served); for (const row of plan.behind) take(row); } else if (plan.outcome === 'keep') { // Already a stored `form` row at its destination: written again only to carry a withdrawal. - if (plan.carries !== undefined) { - const place = placeOf(places, plan.served); - const { _packageId: _pkg, ...stored } = place.entry.data as Record; - write(plan, stored); - } + write(plan, placeOf(places, plan.served)); for (const row of plan.behind) take(row); } else if (plan.outcome === 'remove') { - const body = formBodyOf(placeOf(places, plan.served), plan.form); + const body = servedFormBody(placeOf(places, plan.served), plan.form); removed.push({ form: plan.form, row: plan.served, ...(plan.object !== undefined ? { object: plan.object } : {}), diff --git a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts new file mode 100644 index 00000000000..b2f205e65eb --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts @@ -0,0 +1,242 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The body a stored form is written with, and the verdict on it (ADR-0159 D2, D7) + * + * The stored-form ceremony (`protocol-stored-form-apply.ts`) writes each moved + * form as a `form` row "with its body as written" (D7-a, D7-b): the projected + * body, cleaned of the read's envelope. A projected body is the OLD shape's + * body (`projectViewForms` lifts it unchanged and never parses it by + * `FormSchema`), so it can carry what a `form` item refuses by name: + * + * - **`data`, the old shapes' object binding.** A `form` item is bound by + * `object` alone (D2). Where `data` is a plain object binding that agrees + * with the form's `object` (`{ provider: 'object' }`, its `object` absent or + * equal), it says nothing `object` does not, and the move drops it, as the + * source conversion `view-forms-to-form-items` drops it from a stack + * ({@link withoutPlainObjectBinding}, the same test). Any other `data` is + * kept, and the verdict below refuses it. + * - **anything else the schema refuses**, such as a name whose prefix is not + * the form's `object` (D3): a container stored under a name apart from its + * object expands its forms under `OBJECT.CONTAINER.KEY`. + * + * ⛔ The ceremony never writes a row the `form` schema refuses: the runtime + * would serve it `valid: false`, and the `form` save door refuses the same + * body. {@link storedFormBodyRefusals} is the census's verdict on every body a + * run would write, and on every stored `form` row the census keeps: the + * switch command refuses to run while one stands, and its census is not green + * over one. The verdict is the runtime's own (`servedInvalidVerdict`, the one + * `os migrate meta --stored` asks), so nothing here is a second rule. + * + * Pure over what the census read: no I/O. + */ + +import { PROJECTED_FORM_SOURCE_KEY } from '@objectstack/spec/ui'; +import type { StoredFormPlace } from './protocol-form-reads.js'; +import type { StoredFormAddress, StoredFormAddressPlan, StoredFormDestination, StoredFormRowRef } from './protocol-stored-form-migration.js'; +import { servedInvalidVerdict } from './protocol-stored-view-selection.js'; + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +/** The stored row a reference names, among the places the census read. */ +export function placeOfStoredForm(places: readonly StoredFormPlace[], ref: StoredFormRowRef): StoredFormPlace { + const place = places.find((p) => p.entry.type === ref.type && p.entry.name === ref.name + && p.packageId === ref.packageId && p.grain === ref.grain && p.holds.has(ref.form)); + if (place === undefined) { + throw new Error(`The stored ${ref.type} row '${ref.name}' the plan for '${ref.form}' names was not found again; nothing was written.`); + } + return place; +} + +/** + * [ADR-0159 D2] `body` without its `data` key where that key is a plain + * object binding that agrees with `body.object`: the test the source + * conversion `view-forms-to-form-items` applies before it moves a form. A + * body without `data`, or with any other `data`, is returned as it is. + */ +export function withoutPlainObjectBinding(body: Record): Record { + const data = body.data; + if (data === undefined) return body; + const plain = isRecord(data) + && data.provider === 'object' + && (data.object === undefined || data.object === body.object) + && Object.keys(data).every((k) => k === 'provider' || k === 'object'); + if (!plain) return body; + const { data: _binding, ...rest } = body; + return rest; +} + +/** + * The form body a row holds at `form`, as the read serves it, cleaned of the + * read's envelope: the projection's source marker, and the provenance a + * container's expansion wears from the package that ships the container + * (`_packageId`, `_packageVersion`, `_provenance`). The destination row's + * package is its own provenance; a base's stamp written into a pair's or a + * package-less row would read as that base's shipped code. A plain `data` + * object binding goes too ({@link withoutPlainObjectBinding}). + */ +export function movedFormBody(place: StoredFormPlace, form: string): Record { + return withoutPlainObjectBinding(servedFormBody(place, form)); +} + +/** + * The form body a row holds at `form`, as the read serves it, cleaned of the + * read's envelope only: what the report of a removed internal record form + * writes out, as it was stored. + */ +export function servedFormBody(place: StoredFormPlace, form: string): Record { + const holding = place.holds.get(form); + if (holding?.kind !== 'form') throw new Error(`The stored ${place.entry.type} row '${place.entry.name}' holds no form at '${form}'.`); + const { + _packageId: _pkg, _packageVersion: _version, _provenance: _prov, + [PROJECTED_FORM_SOURCE_KEY]: _source, ...body + } = holding.item as Record; + return { ...body, name: form }; +} + +/** A stored `form` row's own body, as the ceremony writes it again to carry a withdrawal (D7-d). */ +export function keptFormBody(place: StoredFormPlace): Record { + const { _packageId: _pkg, ...stored } = place.entry.data as Record; + return withoutPlainObjectBinding(stored); +} + +/** A stored row the ceremony writes, by its key. */ +export interface StoredFormRowKey { + readonly type: string; + readonly name: string; + readonly packageId?: string; +} + +/** The row a destination is, and the body written there. */ +export function destinationRow( + destination: StoredFormDestination, + form: string, + body: Record, +): { key: StoredFormRowKey; packageId: string | null; body: Record } { + const { overrides: _declared, ...undeclared } = body; + switch (destination.kind) { + case 'pair_override': + return { + key: { type: 'form', name: form, packageId: destination.pair }, + packageId: destination.pair, + body: { ...undeclared, overrides: { package: destination.base, basedOn: destination.basedOn } }, + }; + case 'pair_form': + // [maintainer ruling 7250977204] The pair's own item: no `overrides`. + return { key: { type: 'form', name: form, packageId: destination.pair }, packageId: destination.pair, body: undeclared }; + case 'package_form': + return { key: { type: 'form', name: form, packageId: destination.packageId }, packageId: destination.packageId, body: undeclared }; + case 'environment_form': + return { key: { type: 'form', name: form }, packageId: null, body: undeclared }; + } +} + +/** The body with its `sharing` switched off, its link kept (the carried withdrawal, D7-d). */ +export function switchedOff(body: Record): Record { + return { ...body, sharing: { ...(isRecord(body.sharing) ? body.sharing : {}), enabled: false } }; +} + +/** + * The row a plan writes, and its body: the served body ({@link movedFormBody} + * for a move, {@link keptFormBody} for a kept row), the carried withdrawal + * switched off on it, at its destination. `undefined` for a kept row that + * carries nothing: the run does not write it. + */ +export function plannedFormWrite( + plan: StoredFormAddressPlan & { outcome: 'keep' | 'move' }, + place: StoredFormPlace, +): ReturnType | undefined { + if (plan.outcome === 'keep' && plan.carries === undefined) return undefined; + const body = plan.outcome === 'move' ? movedFormBody(place, plan.form) : keptFormBody(place); + return destinationRow(plan.destination, plan.form, plan.carries !== undefined ? switchedOff(body) : body); +} + +/** A body the `form` schema refuses: one the run would write, or a stored `form` row the census keeps. */ +export interface StoredFormBodyRefusal { + readonly form: string; + readonly address: StoredFormAddress; + /** `move`: the body a move would write; `keep`: a stored `form` row the census keeps, served invalid today unless the run writes it. */ + readonly outcome: 'move' | 'keep'; + /** Whether the run would write this body (a move, or a kept row that takes a withdrawal): the run then writes nothing at all. */ + readonly writes: boolean; + /** The stored row whose body it is. */ + readonly row: StoredFormRowRef; + /** Where the schema refuses the body (`''` for the root). */ + readonly path: string; + /** The schema's own message for that site. */ + readonly message: string; + /** What to do, naming the door and the package the row is saved in. */ + readonly action: string; +} + +/** The metadata door of a row, with the package it is saved in: the save door addresses a package's row only by `?package=`. */ +function doorOf(type: string, name: string, packageId: string | undefined): string { + return `PUT /api/v1/meta/${type}/${name}${packageId !== undefined ? `?package=${packageId}` : ''}`; +} + +function actionFor(plan: StoredFormAddressPlan & { outcome: 'move' | 'keep' }): string { + const row = plan.served; + if (plan.outcome === 'keep' && row.type === 'form') { + return `Save the form again with a body the schema accepts, in Studio or with ${doorOf('form', row.name, row.packageId)} ` + + 'carrying the corrected body, then run this command again.'; + } + return 'The upgrade writes nothing while this body stands. On the release you are running, correct the form where it ' + + `is stored and save it again, in Studio or with ${doorOf(row.type, row.name, row.packageId)} carrying the corrected ` + + 'body, then run this command again.'; +} + +/** + * [ADR-0159 D2, D7] The verdict of the `form` schema on every body the census + * plans to write (a move's, and a kept row's that takes a withdrawal) and on + * every stored `form` row it keeps: one entry per refused body, in plan order. + * A row planned at several addresses is named once. + */ +export function storedFormBodyRefusals( + forms: readonly StoredFormAddressPlan[], + places: readonly StoredFormPlace[], +): StoredFormBodyRefusal[] { + const out: StoredFormBodyRefusal[] = []; + const seen = new Set(); + for (const plan of forms) { + if (plan.outcome !== 'move' && plan.outcome !== 'keep') continue; + const row = plan.served; + const key = `${row.type}\u0000${row.name}\u0000${row.packageId ?? ''}\u0000${row.form}`; + if (seen.has(key)) continue; + const place = placeOfStoredForm(places, row); + // The body the run writes at its destination; a kept row it does not + // write is judged as it is stored, the body the runtime serves. + const planned = plannedFormWrite(plan, place); + const body = planned?.body ?? place.entry.data; + const verdict = servedInvalidVerdict('form', body); + if (verdict === undefined) continue; + seen.add(key); + out.push({ + form: plan.form, + address: plan.address, + outcome: plan.outcome, + writes: planned !== undefined, + row, + path: verdict.path, + message: verdict.message, + action: actionFor(plan), + }); + } + return out; +} + +/** One refused body, as the switch command and the census name it: the row, the site, the schema's words and the action. */ +export function storedFormBodyRefusalLine(refusal: StoredFormBodyRefusal): string { + const row = refusal.row; + const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; + const member = row.name !== row.form ? ` (member '${row.form}')` : ''; + return `${row.type} "${row.name}"${member}, ${where} — the form '${refusal.form}' it ${refusal.outcome === 'move' ? 'would be written as' : 'is'} ` + + `is refused by the protocol-19 form schema at ${refusal.path || '(root)'}: ${refusal.message} ${refusal.action}`; +} + +/** The refusal of a run that would write a body the `form` schema refuses: nothing is written. */ +export function storedFormBodyRefusalText(refused: readonly StoredFormBodyRefusal[]): string { + return `The stored-form upgrade refuses to run: ${refused.length} form(s) it would write are refused by the protocol-19 ` + + 'form schema, so the runtime would serve each one invalid. Nothing was written. ' + + refused.map(storedFormBodyRefusalLine).join(' '); +} diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts index 89bc5fd8428..1948e52f9f4 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -151,6 +151,7 @@ import { type StoredFormPlace, } from './protocol-form-reads.js'; import { protocolHost, type ProtocolHost } from './protocol-host.js'; +import { storedFormBodyRefusals, type StoredFormBodyRefusal } from './protocol-stored-form-bodies.js'; import type { ShipsName } from './suite-moved-overlay.js'; import type { ObjectStackProtocolImplementation } from './protocol.js'; @@ -336,6 +337,14 @@ export interface StoredFormCensus { /** A public slug declared by more than one form name across the stored rows (a retired form and its successor, say). */ readonly sharedSlugs: readonly { readonly slug: string; readonly forms: readonly string[] }[]; readonly precheck: StoredFormPrecheck; + /** + * [ADR-0159 D2] Every body the protocol-19 `form` schema refuses: one the + * run would write, which refuses the run (nothing is written), or a stored + * `form` row the census keeps, which the runtime serves invalid + * (`protocol-stored-form-bodies.ts`). Set by {@link listStoredForms}; + * absent from the pure plan, which reads no schema. + */ + readonly bodyRefusals?: readonly StoredFormBodyRefusal[]; } /** A draft row the report names. */ @@ -1836,7 +1845,7 @@ export async function listStoredForms(host: StoredFormCensusHost): Promise Date: Thu, 3 Dec 2026 23:17:03 +0000 Subject: [PATCH 2/9] test(metadata-protocol): the container-name case expands under its own name, as the runtime door does Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../src/protocol-stored-form-39393.test.ts | 20 ++++++++++++++++--- .../src/protocol-stored-form-bodies.ts | 5 +++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts index 66281fdf059..c4c9cc70083 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -52,12 +52,26 @@ const expandHost = { }), } as never; +/** + * The runtime door's expansion of a container named apart from its object, + * filed against another package's object: under its own name + * (`expandUnderOwnName`), so its form members are `OBJECT.CONTAINER.KEY`. + */ +const ownNameHost = { + expandStoredViewContainers: (_type: string, entries: readonly { data: unknown; packageId: string | undefined }[]) => + entries.flatMap((container) => { + const data = container.data as { name: string; object: string }; + return expandViewContainer(`${data.object}.${data.name}`, data) + .map((item) => ({ item: { ...item, object: data.object } as unknown as Record, container })); + }), +} as never; + const sharing = (enabled: boolean) => ({ sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true } }); /** A stored container, as Studio saved it on 18.x: its forms carry the old `data` binding. */ -function containerRow(name: string, data: Record, packageId?: string): StoredFormPlace { +function containerRow(name: string, data: Record, packageId?: string, host = expandHost): StoredFormPlace { const entry = { name, data: { name, ...data }, packageId, organizationId: null, type: 'view' }; - return { type: 'view', packageId, entry, grain: 'expansion', holds: storedViewRowHoldings(expandHost, entry) }; + return { type: 'view', packageId, entry, grain: 'expansion', holds: storedViewRowHoldings(host, entry) }; } /** A stored `form` row: a pair's declared override when bound to the pair. */ @@ -139,7 +153,7 @@ describe('[ADR-0159 D2] the ceremony writes a moved form without the old `data` describe('[ADR-0159 D3] a container stored under a name apart from its object', () => { it('its form is served as OBJECT.CONTAINER.KEY, which the form schema refuses: the census names it and the run would write nothing (ablate: no verdict on the body)', () => { - const place = containerRow(`${OBJECT}_quick`, { object: OBJECT, form: { type: 'simple', sections: [{ fields: [{ field: 'name' }] }], ...sharing(true) } }); + const place = containerRow(`${OBJECT}_quick`, { object: OBJECT, form: { type: 'simple', sections: [{ fields: [{ field: 'name' }] }], ...sharing(true) } }, undefined, ownNameHost); const census = plan([place], {}); const name = `${OBJECT}.${OBJECT}_quick.form`; expect(census.forms).toEqual([expect.objectContaining({ form: name, outcome: 'move', destination: { kind: 'environment_form' } })]); diff --git a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts index b2f205e65eb..2c1157ff78e 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts @@ -230,8 +230,9 @@ export function storedFormBodyRefusalLine(refusal: StoredFormBodyRefusal): strin const row = refusal.row; const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; const member = row.name !== row.form ? ` (member '${row.form}')` : ''; - return `${row.type} "${row.name}"${member}, ${where} — the form '${refusal.form}' it ${refusal.outcome === 'move' ? 'would be written as' : 'is'} ` - + `is refused by the protocol-19 form schema at ${refusal.path || '(root)'}: ${refusal.message} ${refusal.action}`; + const what = refusal.writes ? `written as the form '${refusal.form}', it would be` : `the form '${refusal.form}' is`; + return `${row.type} "${row.name}"${member}, ${where} — ${what} refused by the protocol-19 form schema at ` + + `${refusal.path || '(root)'}: ${refusal.message} ${refusal.action}`; } /** The refusal of a run that would write a body the `form` schema refuses: nothing is written. */ From 188c76c02fb4ac898c85cd5e60d811d36bd706e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 00:05:48 +0000 Subject: [PATCH 3/9] test(rest): the switch through both doors writes a moved form without `data`, and writes nothing under a name the form schema refuses The #37112 pin for a package-less container's member moved it to `OBJECT.intake.contact`, a name ADR-0159 D3 refuses: the row it wrote was served invalid. It now pins the census naming that body and the ceremony refusing before any write; the stored-withdrawal move pins the written row without the old `data` binding. `runSwitch` mirrors the command's verdict. Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../39393-stored-form-switch-drops-data.md | 2 +- .../src/protocol-stored-form-39393.test.ts | 2 +- .../src/stored-forms-switch-37112.test.ts | 36 ++++++++++++++----- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/.changeset/39393-stored-form-switch-drops-data.md b/.changeset/39393-stored-form-switch-drops-data.md index 889fb2950bb..52aa689dff9 100644 --- a/.changeset/39393-stored-form-switch-drops-data.md +++ b/.changeset/39393-stored-form-switch-drops-data.md @@ -11,7 +11,7 @@ Metadata-protocol: none Who sees it: an administrator upgrading a deployment whose 18.x database holds forms edited in Studio (a view's `form` or `formViews` saved with the view). - **A moved form no longer keeps `data`.** The protocol-19 switch moved each stored form "with its body as written", and an 18.x Studio save stores a form's object binding as `data: { provider: 'object', object }`. A `form` item refuses `data` by name, so every moved form was served `valid: false` and the `form` door refused the same body. The switch now drops a plain object binding, as `os migrate meta --from 18 --write` does for a form in source; the rest of the body moves as written. -- **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. +- **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. This includes a form served under a name the protocol-19 naming rule refuses, such as a member of a container stored apart from its object's package (`OBJECT.CONTAINER.KEY`): the switch renames no form, so it no longer writes one there. - **The fix names the package.** For a stored `form` row served invalid, the action is `PUT /api/v1/meta/form/NAME?package=PACKAGE`: the save door addresses a package's row only with `?package=`. A deployment that already switched on `19.0.0-next.4` and holds moved forms with `data`: run `os migrate stored-forms` to list them, and save each again without `data` through the door it names. diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts index c4c9cc70083..b44f7a93c52 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -159,7 +159,7 @@ describe('[ADR-0159 D3] a container stored under a name apart from its object', expect(census.forms).toEqual([expect.objectContaining({ form: name, outcome: 'move', destination: { kind: 'environment_form' } })]); const refusals = storedFormBodyRefusals(census.forms, [place]); expect(refusals).toEqual([expect.objectContaining({ form: name, outcome: 'move', writes: true, path: 'name' })]); - expect(storedFormBodyRefusalText(refusals)).toContain('Nothing was written'); + expect(storedFormBodyRefusalText(refusals)).toContain(`view "${OBJECT}_quick"`); }); }); diff --git a/packages/rest/src/stored-forms-switch-37112.test.ts b/packages/rest/src/stored-forms-switch-37112.test.ts index 0ccbab9aa4d..bd884a42b0c 100644 --- a/packages/rest/src/stored-forms-switch-37112.test.ts +++ b/packages/rest/src/stored-forms-switch-37112.test.ts @@ -171,12 +171,16 @@ async function allRows(b: Booted) { */ async function runSwitch(b: Booted) { const before = await listStoredFormsOf(b.protocol); - if (!before.precheck.canSwitch) return { switched: false as const, before, ceremony: undefined, after: undefined }; + // [ADR-0159 D2] A body the `form` schema refuses refuses the command before the ceremony, as a hold does. + if (!before.precheck.canSwitch || (before.bodyRefusals ?? []).length > 0) { + return { switched: false as const, before, ceremony: undefined, after: undefined }; + } const ceremony = await applyStoredFormsOf(b.protocol, { actor: ACTOR }); if (!ceremony.applied) return { switched: false as const, before, ceremony, after: undefined }; const after = await listStoredFormsOf(b.protocol); const { canSwitch, counts } = after.precheck; - return { switched: canSwitch && counts.move === 0 && counts.remove === 0 && counts.hold === 0, before, ceremony, after }; + const verified = canSwitch && counts.move === 0 && counts.remove === 0 && counts.hold === 0 && (after.bodyRefusals ?? []).length === 0; + return { switched: verified, before, ceremony, after }; } const CLOSED = { get: [404, 'FORM_NOT_FOUND'], post: [404, 'FORM_NOT_FOUND'], wrote: 0 }; @@ -263,10 +267,21 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(before).toEqual(CLOSED); const run = await runSwitch(b); expect(run.before.forms.filter((f) => f.form === NAME).map((f) => f.outcome)).toEqual(['move']); + expect(run.before.bodyRefusals).toEqual([]); expect(run.ceremony?.applied).toBe(true); expect(run.switched).toBe(true); expect(run.after?.forms.filter((f) => f.form === NAME).map((f) => f.outcome)).toEqual(['keep']); expect(await doors(b)).toEqual(CLOSED); + // [ADR-0159 D2] The written row is a `form` item: the old view form's `data` binding stays behind. + // Ablation: write the projected body as it is → `data` stored, and the re-run census names the row. + const written = run.ceremony!.written.map((w) => w.row); + expect(written).toEqual([expect.objectContaining({ type: 'form', name: NAME })]); + const rows = (await b.engine.find('sys_metadata', { where: { type: 'form', name: NAME }, context: { isSystem: true } })) as any[]; + expect(rows).toHaveLength(1); + const stored = typeof rows[0].metadata === 'string' ? JSON.parse(rows[0].metadata) : rows[0].metadata; + expect(stored).not.toHaveProperty('data'); + expect(stored).toMatchObject({ name: NAME, object: OBJECT }); + expect(run.after?.bodyRefusals).toEqual([]); }); it('an internal record form is removed, and nothing a door answers changes', async () => { @@ -406,15 +421,20 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(await doors(b)).toEqual(CLOSED); }); - it('the census counts an open form member of a package-less stored container, and the switch moves it', async () => { + it('⛔ a container stored under a name apart from its object serves its member under a name the form schema refuses: the census names it and the ceremony writes nothing', async () => { + // A package-less container on a packaged object expands under its own name, `OBJECT.CONTAINER.KEY` + // (the runtime door's own-name arm): ADR-0159 D3 refuses that name, and ruled question 2 renames no form. const MEMBER = `${OBJECT}.intake.contact`; const b = await boot({}); await b.seedRow('view', 'intake', null, { name: 'intake', ...container(true) }); - const run = await runSwitch(b); - expect(run.before.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['move']); - expect(run.before.precheck.counts.move).toBe(1); - expect(run.switched).toBe(true); - expect(run.after?.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['keep']); + const rows = await allRows(b); + const census = await listStoredFormsOf(b.protocol); + expect(census.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['move']); + expect(census.bodyRefusals).toEqual([expect.objectContaining({ form: MEMBER, outcome: 'move', writes: true, path: 'name' })]); + // The library refuses too, whoever calls it. Ablation: drop the guard → the row is written, served invalid. + await expect(applyStoredFormsOf(b.protocol, { actor: ACTOR })).rejects.toThrow(MEMBER); + expect(await allRows(b)).toBe(rows); + expect((await runSwitch(b)).switched).toBe(false); }); }); }); From 5a9a3101cdfb3eaae22388200c2adcda1e93816a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 00:07:43 +0000 Subject: [PATCH 4/9] test(rest): pin the moved row of a stored container's form without `data`, the shape an 18.x Studio save stores Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../src/stored-forms-switch-37112.test.ts | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/rest/src/stored-forms-switch-37112.test.ts b/packages/rest/src/stored-forms-switch-37112.test.ts index bd884a42b0c..1550cdf63c4 100644 --- a/packages/rest/src/stored-forms-switch-37112.test.ts +++ b/packages/rest/src/stored-forms-switch-37112.test.ts @@ -272,16 +272,28 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(run.switched).toBe(true); expect(run.after?.forms.filter((f) => f.form === NAME).map((f) => f.outcome)).toEqual(['keep']); expect(await doors(b)).toEqual(CLOSED); - // [ADR-0159 D2] The written row is a `form` item: the old view form's `data` binding stays behind. - // Ablation: write the projected body as it is → `data` stored, and the re-run census names the row. - const written = run.ceremony!.written.map((w) => w.row); - expect(written).toEqual([expect.objectContaining({ type: 'form', name: NAME })]); + }); + + // [ADR-0159 D2] An 18.x Studio save of a container stores each form with + // `data: { provider: 'object', object }`, which a `form` item refuses by name. + // Ablation: write the projected body as it is → `data` stored, the census names + // the body and the run refuses before it writes. + it('⛔ a stored container\'s form moves as a `form` row without the old `data` binding, and the form stays closed', async () => { + const b = await boot({ forms: [formItem(true)] }); + await b.seedRow('view', OBJECT, BASE, { name: OBJECT, ...container(false) }); + expect(await doors(b)).toEqual(CLOSED); + const run = await runSwitch(b); + expect(run.before.forms.filter((f) => f.form === NAME).map((f) => f.outcome)).toEqual(['move']); + expect(run.before.bodyRefusals).toEqual([]); + expect(run.switched).toBe(true); + expect(run.ceremony!.written.map((w) => w.row)).toEqual([expect.objectContaining({ type: 'form', name: NAME })]); const rows = (await b.engine.find('sys_metadata', { where: { type: 'form', name: NAME }, context: { isSystem: true } })) as any[]; expect(rows).toHaveLength(1); const stored = typeof rows[0].metadata === 'string' ? JSON.parse(rows[0].metadata) : rows[0].metadata; expect(stored).not.toHaveProperty('data'); expect(stored).toMatchObject({ name: NAME, object: OBJECT }); expect(run.after?.bodyRefusals).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); }); it('an internal record form is removed, and nothing a door answers changes', async () => { From e1057beb49a3d60d44573f19b8d0b6505caa4007 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 00:14:07 +0000 Subject: [PATCH 5/9] test(cli): the switch is not verified over a kept form row the protocol-19 form schema refuses Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../src/commands/migrate/stored-forms.test.ts | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/migrate/stored-forms.test.ts b/packages/cli/src/commands/migrate/stored-forms.test.ts index ab79859ea88..1eac6a84f53 100644 --- a/packages/cli/src/commands/migrate/stored-forms.test.ts +++ b/packages/cli/src/commands/migrate/stored-forms.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { StoredFormAddressPlan, StoredFormCensus } from '@objectstack/metadata-protocol'; -import { storedFormRunRefusal } from './stored-forms.js'; +import { storedFormBodyRefusalSummary, storedFormBodyRefusalText, storedFormRunRefusal } from './stored-forms.js'; // The report's sentence is read alone: no stack is booted here, so nothing the // command loads to boot one is loaded (each package the boot reaches is mocked). @@ -49,3 +49,24 @@ describe('[ADR-0159 D7] the census report says where the upgrade\'s run will be expect(storedFormRunRefusal(census([plan('move')], false), engine(false))).toBeUndefined(); }); }); + +describe('[ADR-0159 D2] the census is never green over a form body the protocol-19 `form` schema refuses', () => { + const refusal = (writes: boolean) => ({ + form: 'crm_lead.intake', address: { kind: 'environment' }, outcome: writes ? 'move' : 'keep', writes, row: ROW, + path: '', message: 'Unrecognized key(s) on this form: data', action: 'PUT /api/v1/meta/form/crm_lead.intake?package=com.acme.crm.custom', + }) as unknown as NonNullable[number]; + const kept = (bodyRefusals?: StoredFormCensus['bodyRefusals']): StoredFormCensus => ({ ...census([plan('keep')]), ...(bodyRefusals ? { bodyRefusals } : {}) }); + + it('a kept form row the schema refuses keeps the switch from being recorded (ablate: drop the verdict from censusVerifiesSwitch)', async () => { + const { censusVerifiesSwitch } = await import('./protocol.js'); + expect(censusVerifiesSwitch(kept([refusal(false)]))).toBe(false); + expect(storedFormBodyRefusalSummary([refusal(false)])).toContain('1 stored form row(s)'); + expect(storedFormBodyRefusalText(refusal(false))).toContain('?package=com.acme.crm.custom'); + }); + + it('CONTROL: the same census with no refused body verifies the switch', async () => { + const { censusVerifiesSwitch } = await import('./protocol.js'); + expect(censusVerifiesSwitch(kept([]))).toBe(true); + expect(censusVerifiesSwitch(kept())).toBe(true); + }); +}); From 2e8f486ee45b3af0d8129a5700485d23a58348d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 01:21:28 +0000 Subject: [PATCH 6/9] test: pay the dynamically imported dependency's first load during collection (check:test-source-alias) Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- packages/cli/src/commands/migrate/stored-forms.test.ts | 3 +++ .../metadata-protocol/src/protocol-stored-form-39393.test.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/cli/src/commands/migrate/stored-forms.test.ts b/packages/cli/src/commands/migrate/stored-forms.test.ts index 1eac6a84f53..ad518189c08 100644 --- a/packages/cli/src/commands/migrate/stored-forms.test.ts +++ b/packages/cli/src/commands/migrate/stored-forms.test.ts @@ -1,6 +1,9 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, expect, it, vi } from 'vitest'; +// Paid during collection, not inside a case's clocked window (check:test-source-alias): +// `censusVerifiesSwitch`'s module reaches it through a dynamic import. +import '@objectstack/spec/migrations'; import type { StoredFormAddressPlan, StoredFormCensus } from '@objectstack/metadata-protocol'; import { storedFormBodyRefusalSummary, storedFormBodyRefusalText, storedFormRunRefusal } from './stored-forms.js'; diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts index b44f7a93c52..1e815b7f7d2 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -18,6 +18,9 @@ * (`storedViewRowHoldings`), and the plans by the census's own planner. */ import { describe, expect, it } from 'vitest'; +// Paid during collection, not inside a case's clocked window (check:test-source-alias): +// the verdict's diagnostics reach it through a dynamic import. +import '@objectstack/lint'; import { installedManifestsOf } from '@objectstack/metadata-core'; import { deriveViewContainerObject, expandViewContainer } from '@objectstack/spec'; import { FormSchema } from '@objectstack/spec/ui'; From 9c150689d66149fb43d3eaf2a38b270be7e4ff16 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 01:54:50 +0000 Subject: [PATCH 7/9] fix(metadata-protocol): the stored pass's fix line names `?package=` for a package-bound row, and a refused container form name gets the remedies that exist `os migrate meta --stored` printed `PUT /api/v1/meta/TYPE/NAME` for a row served invalid; the save door addresses a package's row only by `?package=`, so the printed fix was refused for every package-bound row. A form the switch refuses because its served name is `OBJECT.CONTAINER.KEY` (ADR-0159 D3) cannot be fixed by correcting the body: the upgrade renames no form. Its action now names the two remedies that exist on the running release: delete the container, or save its forms again in a container named after the object, bound to the package that ships it or its customization package. Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../src/protocol-stored-form-39393.test.ts | 28 +++++++++++++++++++ .../src/protocol-stored-form-bodies.ts | 13 +++++++-- .../metadata-protocol/src/stored-migration.ts | 5 +++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts index 1e815b7f7d2..00eabd68119 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -25,6 +25,7 @@ import { installedManifestsOf } from '@objectstack/metadata-core'; import { deriveViewContainerObject, expandViewContainer } from '@objectstack/spec'; import { FormSchema } from '@objectstack/spec/ui'; import { storedViewRowHoldings, type StoredFormPlace } from './protocol-form-reads.js'; +import { formatStoredMigrationReport, type StoredMigrationReport, type StoredMigrationRow } from './stored-migration.js'; import { plannedFormWrite, servedFormBody, @@ -163,6 +164,10 @@ describe('[ADR-0159 D3] a container stored under a name apart from its object', const refusals = storedFormBodyRefusals(census.forms, [place]); expect(refusals).toEqual([expect.objectContaining({ form: name, outcome: 'move', writes: true, path: 'name' })]); expect(storedFormBodyRefusalText(refusals)).toContain(`view "${OBJECT}_quick"`); + // The action names the remedies that exist: no correction of the body renames the form. + // Ablation: the generic action → neither door is named. + expect(refusals[0]!.action).toContain(`DELETE /api/v1/meta/view/${OBJECT}_quick`); + expect(refusals[0]!.action).toContain(`PUT /api/v1/meta/view/${OBJECT}?package=`); }); }); @@ -194,3 +199,26 @@ describe('[ADR-0159 D2] a stored `form` row the census keeps is judged as it is expect(storedFormBodyRefusals(census.forms, [kept, behind])).toEqual([]); }); }); + +describe('[#39393] `os migrate meta --stored` names the package door for a row served invalid', () => { + const row = (packageId: string | null): StoredMigrationRow => ({ + id: `r_${packageId ?? 'none'}`, type: 'form', name: NAME, organizationId: null, packageId, state: 'active', + outcome: 'skipped', notices: [], todos: [], servedInvalid: { path: '', message: 'Unrecognized key(s) on this form: data' }, + }); + const report = (rows: StoredMigrationRow[]): StoredMigrationReport => ({ + apply: false, protocol: '19.0.0', scanned: rows.length, canonical: 0, pending: 0, rewritten: 0, skipped: rows.length, failed: 0, + servedInvalid: rows.length, rows, decisionModeReview: [], viewAllFieldsReview: [], + }); + const fixLines = (rows: StoredMigrationRow[]) => formatStoredMigrationReport(report(rows)).filter((l) => l.trimStart().startsWith('fix:')); + + it('a row saved in a package: the fix line addresses it with `?package=` (ablate: drop it from the door)', () => { + const [fix] = fixLines([row(PAIR)]); + expect(fix).toContain(`PUT /api/v1/meta/form/${NAME}?package=${PAIR} `); + }); + + it('CONTROL: a package-less row is addressed without one', () => { + const [fix] = fixLines([row(null)]); + expect(fix).toContain(`PUT /api/v1/meta/form/${NAME} `); + expect(fix).not.toContain('?package='); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts index 2c1157ff78e..e08e5748c77 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts @@ -175,12 +175,21 @@ function doorOf(type: string, name: string, packageId: string | undefined): stri return `PUT /api/v1/meta/${type}/${name}${packageId !== undefined ? `?package=${packageId}` : ''}`; } -function actionFor(plan: StoredFormAddressPlan & { outcome: 'move' | 'keep' }): string { +function actionFor(plan: StoredFormAddressPlan & { outcome: 'move' | 'keep' }, path: string, object: unknown): string { const row = plan.served; if (plan.outcome === 'keep' && row.type === 'form') { return `Save the form again with a body the schema accepts, in Studio or with ${doorOf('form', row.name, row.packageId)} ` + 'carrying the corrected body, then run this command again.'; } + if (path === 'name' && row.type === 'view' && row.grain === 'expansion' && typeof object === 'string' && object !== '') { + // [ADR-0159 D3; ruled question 2] The name is the one the container's form is served under, + // and the upgrade renames no form: no correction of the body gives it a name the rule accepts. + return `The upgrade writes nothing while this form stands, and it renames no form. On the release you are running, ` + + `either delete the container once nothing needs its forms (DELETE /api/v1/meta/view/${row.name}` + + `${row.packageId !== undefined ? `?package=${row.packageId}` : ''}), or save its forms again in a container named '${object}' ` + + `bound to the package that ships '${object}' or its customization package (PUT /api/v1/meta/view/${object}?package=PACKAGE), ` + + `where each is served as '${object}.KEY'; then run this command again.`; + } return 'The upgrade writes nothing while this body stands. On the release you are running, correct the form where it ' + `is stored and save it again, in Studio or with ${doorOf(row.type, row.name, row.packageId)} carrying the corrected ` + 'body, then run this command again.'; @@ -219,7 +228,7 @@ export function storedFormBodyRefusals( row, path: verdict.path, message: verdict.message, - action: actionFor(plan), + action: actionFor(plan, verdict.path, (body as Record | undefined)?.object), }); } return out; diff --git a/packages/metadata-protocol/src/stored-migration.ts b/packages/metadata-protocol/src/stored-migration.ts index 317c8780038..9b8212c8893 100644 --- a/packages/metadata-protocol/src/stored-migration.ts +++ b/packages/metadata-protocol/src/stored-migration.ts @@ -682,7 +682,10 @@ function servedInvalidFix(report: StoredMigrationReport, row: StoredMigrationRow } const where = `the row (sys_metadata id ${row.id})`; const todo = row.todos.length > 0 ? ' Each TODO line under the row above names the hand rewrite.' : ''; - return `correct ${where} at the site named and save it again — in Studio, or with PUT /api/v1/meta/${row.type}/${row.name} ` + + // The save door addresses a package's row only by `?package=` (#39393): + // without it the body is judged as a package-less row, and refused. + const pkg = row.packageId !== null ? `?package=${row.packageId}` : ''; + return `correct ${where} at the site named and save it again — in Studio, or with PUT /api/v1/meta/${row.type}/${row.name}${pkg} ` + `carrying the corrected body — or delete it by name through the metadata API once nothing needs it.${todo} ` + `Re-run this pass to confirm (protocol ${report.protocol}).`; } From d67cb2ca95eb6edcd93e16ff7ef1a1ee7977dc29 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 01:55:24 +0000 Subject: [PATCH 8/9] chore(changeset): the stored pass's fix line, and the refused-name remedy Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .changeset/39393-stored-form-switch-drops-data.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.changeset/39393-stored-form-switch-drops-data.md b/.changeset/39393-stored-form-switch-drops-data.md index 52aa689dff9..6af0d0e66ee 100644 --- a/.changeset/39393-stored-form-switch-drops-data.md +++ b/.changeset/39393-stored-form-switch-drops-data.md @@ -12,6 +12,7 @@ Who sees it: an administrator upgrading a deployment whose 18.x database holds f - **A moved form no longer keeps `data`.** The protocol-19 switch moved each stored form "with its body as written", and an 18.x Studio save stores a form's object binding as `data: { provider: 'object', object }`. A `form` item refuses `data` by name, so every moved form was served `valid: false` and the `form` door refused the same body. The switch now drops a plain object binding, as `os migrate meta --from 18 --write` does for a form in source; the rest of the body moves as written. - **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. This includes a form served under a name the protocol-19 naming rule refuses, such as a member of a container stored apart from its object's package (`OBJECT.CONTAINER.KEY`): the switch renames no form, so it no longer writes one there. -- **The fix names the package.** For a stored `form` row served invalid, the action is `PUT /api/v1/meta/form/NAME?package=PACKAGE`: the save door addresses a package's row only with `?package=`. +- **The fix names the package.** For a stored `form` row served invalid, the action is `PUT /api/v1/meta/form/NAME?package=PACKAGE`: the save door addresses a package's row only with `?package=`. `os migrate meta --stored` does the same: its fix line for any row saved in a package (every type) now reads `PUT /api/v1/meta/TYPE/NAME?package=PACKAGE`, where it printed a door that refused the save. +- **A form whose name cannot move says what can be done.** A container's form served as `OBJECT.CONTAINER.KEY` is refused rather than renamed; its action names deleting the container, or saving its forms again in a container named after the object, in the package that ships it or its customization package. A deployment that already switched on `19.0.0-next.4` and holds moved forms with `data`: run `os migrate stored-forms` to list them, and save each again without `data` through the door it names. From b063f1895915653b05abab4169799e87912d7703 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 02:00:39 +0000 Subject: [PATCH 9/9] fix(metadata-protocol): a refused container form name names the remedy that works, for any container whose package does not own its object The own-name arm applies wherever the container's package is not the one that owns its object (package-less, a customization pair, any other package), so re-saving the container in the pair does not change the name. The action now says: delete the container, re-create each form as its own `OBJECT.KEY` item, re-point what opened the old name, run again. A unit and a both-doors case pin a container bound to another package. Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .../39393-stored-form-switch-drops-data.md | 4 ++-- .../src/protocol-stored-form-39393.test.ts | 19 +++++++++++---- .../src/protocol-stored-form-bodies.ts | 23 ++++++++++++------- .../src/stored-forms-switch-37112.test.ts | 14 +++++++++++ 4 files changed, 46 insertions(+), 14 deletions(-) diff --git a/.changeset/39393-stored-form-switch-drops-data.md b/.changeset/39393-stored-form-switch-drops-data.md index 6af0d0e66ee..d6220c1548b 100644 --- a/.changeset/39393-stored-form-switch-drops-data.md +++ b/.changeset/39393-stored-form-switch-drops-data.md @@ -11,8 +11,8 @@ Metadata-protocol: none Who sees it: an administrator upgrading a deployment whose 18.x database holds forms edited in Studio (a view's `form` or `formViews` saved with the view). - **A moved form no longer keeps `data`.** The protocol-19 switch moved each stored form "with its body as written", and an 18.x Studio save stores a form's object binding as `data: { provider: 'object', object }`. A `form` item refuses `data` by name, so every moved form was served `valid: false` and the `form` door refused the same body. The switch now drops a plain object binding, as `os migrate meta --from 18 --write` does for a form in source; the rest of the body moves as written. -- **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. This includes a form served under a name the protocol-19 naming rule refuses, such as a member of a container stored apart from its object's package (`OBJECT.CONTAINER.KEY`): the switch renames no form, so it no longer writes one there. +- **No switch over a form the `form` schema refuses.** The census (`os migrate stored-forms`, and the preview of `os migrate protocol --to 19`) now judges every form body the switch would write, and every stored `form` row it keeps, with the runtime's own schema. A body it refuses is listed with the site, the schema's words and the action; `os migrate protocol --to 19` then exits 1 and writes nothing, and `--apply` records no switch while one stands. `--json` carries the list as `bodyRefusals`, and `canSwitch` is `false` beside it. This includes a form served under a name the protocol-19 naming rule refuses, such as a form a container serves as `OBJECT.CONTAINER.KEY` when the container's package (none, a customization package, or any other) is not the package that owns the object: the switch renames no form, so it no longer writes one there. - **The fix names the package.** For a stored `form` row served invalid, the action is `PUT /api/v1/meta/form/NAME?package=PACKAGE`: the save door addresses a package's row only with `?package=`. `os migrate meta --stored` does the same: its fix line for any row saved in a package (every type) now reads `PUT /api/v1/meta/TYPE/NAME?package=PACKAGE`, where it printed a door that refused the save. -- **A form whose name cannot move says what can be done.** A container's form served as `OBJECT.CONTAINER.KEY` is refused rather than renamed; its action names deleting the container, or saving its forms again in a container named after the object, in the package that ships it or its customization package. +- **A form whose name cannot move says what can be done.** Such a form is refused rather than renamed. Its action names the remedy that exists on the release you are running: delete the container, re-create each of its forms as its own form named `OBJECT.KEY`, point anything that opened the old name at the new one, and run the upgrade again. A deployment that already switched on `19.0.0-next.4` and holds moved forms with `data`: run `os migrate stored-forms` to list them, and save each again without `data` through the door it names. diff --git a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts index 00eabd68119..81ca8c362f6 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-39393.test.ts @@ -164,10 +164,21 @@ describe('[ADR-0159 D3] a container stored under a name apart from its object', const refusals = storedFormBodyRefusals(census.forms, [place]); expect(refusals).toEqual([expect.objectContaining({ form: name, outcome: 'move', writes: true, path: 'name' })]); expect(storedFormBodyRefusalText(refusals)).toContain(`view "${OBJECT}_quick"`); - // The action names the remedies that exist: no correction of the body renames the form. - // Ablation: the generic action → neither door is named. - expect(refusals[0]!.action).toContain(`DELETE /api/v1/meta/view/${OBJECT}_quick`); - expect(refusals[0]!.action).toContain(`PUT /api/v1/meta/view/${OBJECT}?package=`); + // The action names the remedy that exists: no correction of the body renames the form. + // Ablation: the generic action → the delete door and the `OBJECT.KEY` name are not named. + expect(refusals[0]!.action).toContain(`DELETE /api/v1/meta/view/${OBJECT}_quick)`); + expect(refusals[0]!.action).toContain(`'${OBJECT}.KEY'`); + }); + + it('a container bound to a package that does not own its object is the same class: named, and its delete door names its package', () => { + const OTHER = 'com.other.app'; + const place = containerRow(`${OBJECT}_quick`, { object: OBJECT, form: { type: 'simple', sections: [{ fields: [{ field: 'name' }] }], ...sharing(true) } }, OTHER, ownNameHost); + const census = plan([place], {}); + const name = `${OBJECT}.${OBJECT}_quick.form`; + expect(census.forms.map((p) => [p.form, p.outcome])).toEqual([[name, 'move']]); + const refusals = storedFormBodyRefusals(census.forms, [place]); + expect(refusals).toEqual([expect.objectContaining({ form: name, writes: true, path: 'name' })]); + expect(refusals[0]!.action).toContain(`DELETE /api/v1/meta/view/${OBJECT}_quick?package=${OTHER})`); }); }); diff --git a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts index e08e5748c77..5961425ef5f 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-bodies.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-bodies.ts @@ -17,8 +17,13 @@ * ({@link withoutPlainObjectBinding}, the same test). Any other `data` is * kept, and the verdict below refuses it. * - **anything else the schema refuses**, such as a name whose prefix is not - * the form's `object` (D3): a container stored under a name apart from its - * object expands its forms under `OBJECT.CONTAINER.KEY`. + * the form's `object` (D3): a container whose package is not the package + * that owns its object (package-less, a customization pair, any other + * package) serves each form its object's package does not ship under + * `OBJECT.CONTAINER.KEY` (the runtime door's own-name arm). The upgrade + * renames no form (ruled question 2), so such a form refuses the run, and + * its action names the remedy that exists: delete the container and + * re-create each form as its own `OBJECT.KEY` item. * * ⛔ The ceremony never writes a row the `form` schema refuses: the runtime * would serve it `valid: false`, and the `form` save door refuses the same @@ -182,13 +187,15 @@ function actionFor(plan: StoredFormAddressPlan & { outcome: 'move' | 'keep' }, p + 'carrying the corrected body, then run this command again.'; } if (path === 'name' && row.type === 'view' && row.grain === 'expansion' && typeof object === 'string' && object !== '') { - // [ADR-0159 D3; ruled question 2] The name is the one the container's form is served under, - // and the upgrade renames no form: no correction of the body gives it a name the rule accepts. + // [ADR-0159 D3; ruled question 2] A container whose package is not the one that owns its + // object (package-less, a customization pair, any other package) serves a form its object's + // package does not ship as `OBJECT.CONTAINER.KEY`: the runtime door's own-name arm. The + // upgrade renames no form, and no correction of the body, nor a re-save of the container in + // another package that does not own the object, gives it a name the rule accepts. return `The upgrade writes nothing while this form stands, and it renames no form. On the release you are running, ` - + `either delete the container once nothing needs its forms (DELETE /api/v1/meta/view/${row.name}` - + `${row.packageId !== undefined ? `?package=${row.packageId}` : ''}), or save its forms again in a container named '${object}' ` - + `bound to the package that ships '${object}' or its customization package (PUT /api/v1/meta/view/${object}?package=PACKAGE), ` - + `where each is served as '${object}.KEY'; then run this command again.`; + + `delete the container (DELETE /api/v1/meta/view/${row.name}${row.packageId !== undefined ? `?package=${row.packageId}` : ''}), ` + + `re-create each of its forms as its own form named '${object}.KEY' (in Studio, a new form on '${object}'), ` + + `point anything that opened '${plan.form}' at the new name, then run this command again.`; } return 'The upgrade writes nothing while this body stands. On the release you are running, correct the form where it ' + `is stored and save it again, in Studio or with ${doorOf(row.type, row.name, row.packageId)} carrying the corrected ` diff --git a/packages/rest/src/stored-forms-switch-37112.test.ts b/packages/rest/src/stored-forms-switch-37112.test.ts index 1550cdf63c4..dd58888698d 100644 --- a/packages/rest/src/stored-forms-switch-37112.test.ts +++ b/packages/rest/src/stored-forms-switch-37112.test.ts @@ -448,5 +448,19 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(await allRows(b)).toBe(rows); expect((await runSwitch(b)).switched).toBe(false); }); + + it('⛔ a container bound to an installed package that does not own its object is the same class: named, and nothing is written', async () => { + const OTHER = 'com.example.other37112'; + const MEMBER = `${OBJECT}.other_quick.contact`; + const b = await boot({}); + await b.install(OTHER); + await b.seedRow('view', 'other_quick', OTHER, { name: 'other_quick', ...container(true) }); + const rows = await allRows(b); + const census = await listStoredFormsOf(b.protocol); + expect(census.bodyRefusals).toEqual([expect.objectContaining({ form: MEMBER, writes: true, path: 'name' })]); + expect(census.bodyRefusals![0]!.action).toContain(`DELETE /api/v1/meta/view/other_quick?package=${OTHER})`); + expect((await runSwitch(b)).switched).toBe(false); + expect(await allRows(b)).toBe(rows); + }); }); });