diff --git a/.changeset/37111-stored-forms-apply.md b/.changeset/37111-stored-forms-apply.md new file mode 100644 index 00000000000..05fe18ccb4f --- /dev/null +++ b/.changeset/37111-stored-forms-apply.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +feat(metadata-protocol): the stored-form ceremony's write half, the `--apply` the next major's upgrade command runs (ADR-0159 D7) + +Clause-②: yes (widening) +Metadata-protocol: none + +`applyStoredFormsOf(protocol, { actor })` runs the census `os migrate stored-forms` prints and acts on it, all or nothing with the switch: when the precheck counts any row, it writes nothing and every stored row stays byte-equal. Otherwise it ensures the `.custom` pairs the moves land in (they stay if the run fails; an empty pair changes no answer and the next run reuses it), then, in one transaction, writes each form that is kept with a carried withdrawal or moved as a `form` row at its destination, with its body as stored (a folded row's withdrawal switches the kept form off, its link kept; a declared override is written as its pair's own row), reads each one back, and only then deletes or re-saves the old rows: a view item row is deleted, a stored container is re-saved without the forms that left it (its lists and the forms it keeps byte-equal), and a container left with nothing is deleted. Internal record forms are removed the same way, with their bodies in the result. Forms left in place and drafts are not touched; a second run moves nothing. On a database whose default driver cannot roll a transaction back, a run that would write or take a row is refused before anything is written, naming the driver and what to do (run against a database whose driver supports transactions, or stay on the current release). It is exported for the major's upgrade command only; `os migrate stored-forms` stays read-only. + +The census gains three readings: a withdrawal in a `view` row a `form` row outranks at its place, and one in a second pair's declared override, are read today, so the fold does not name the form newly closed; a row bound to a package that ships no form of the name moves into the pair as its own item where the base records no version (that item declares no `basedOn`); and where no pair id can be derived from a base, the refusal names why in words. Two more keep the census and `--apply` in step: a move, or a kept row that carries a withdrawal, whose destination row the store seals (a managed package ships the form's name as a `form` item, and the destination is not a declared override) holds the upgrade, naming that package, instead of failing the run; and a form no door serves today is left in place by the upgrade, whatever package its row is bound to (`served_by_no_door`, a new member of the exported `StoredFormLeftReason`), which `os migrate stored-forms` prints; such a form does not hold the upgrade at the pair door or at a sealed destination either. On a database that cannot roll back, `os migrate stored-forms` says the upgrade's run will be refused (`runRefused` in `--json`). + +The operations page `content/docs/deployment/stored-forms-upgrade.mdx` says what the upgrade command writes. diff --git a/content/docs/deployment/stored-forms-upgrade.mdx b/content/docs/deployment/stored-forms-upgrade.mdx index 676dd87ddf7..4e3d63b6bd3 100644 --- a/content/docs/deployment/stored-forms-upgrade.mdx +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -14,7 +14,7 @@ switch, and the deployment stays on the release it is running. `os migrate stored-forms` shows you that outcome before you upgrade. It writes nothing, and it has no `--apply`: the move is reached only from the upgrade -command. +command ([below](#what-the-upgrade-command-writes)). ```bash os migrate stored-forms @@ -35,12 +35,21 @@ package of your own, or the environment itself when no package ships it. | Outcome | What the upgrade does | |---|---| -| **kept** | The form is already stored as a form. Older rows of the same form fold into it. | -| **moves** | The row moves to a form row, with its body as written: into the package's paired `.custom` package as a declared override for a read-only package, into the package itself for a writable one, or into the environment. An override already stored in a `.custom` package keeps its package and the version it is based on. A row bound to a read-only package that ships no form of that name, or an override of a package that ships none, moves into that package's `.custom` package as a form of its own, with no override declared; its public address answers as it does today. Where the server today serves such a row at one other package's address, it moves as a row of that package does, into that package's `.custom` package as a declared override. Older rows of the same form fold into it. | +| **kept** | The form is already stored as a form. The rows the server serves behind it at that package fold into it. | +| **moves** | The row moves to a form row, with its body as written: into the package's paired `.custom` package as a declared override for a read-only package, into the package itself for a writable one, or into the environment. An override already stored in a `.custom` package keeps its package and the version it is based on. A row bound to a read-only package that ships no form of that name, or an override of a package that ships none, moves into that package's `.custom` package as a form of its own, with no override declared; its public address answers as it does today. Where the server today serves such a row at one other package's address, it moves as a row of that package does, into that package's `.custom` package as a declared override. The rows the server serves behind the moved row at that package fold into it. | | **will be removed** | The row is an internal record form: a create or edit form with no public link that no action opens, over nothing that has a link. New and Edit follow the object's field groups instead, and the report says whether the object declares any. A row bound to no package is read at every package that ships its form: it is removed only when it is an internal record form at each of them, and moves at each of them otherwise. An older row behind the removed one goes with it, unless another package serves that row: the report then names it as not removed, with what happens to it there. | -| **left in place** | Nothing moves. The row served for the name carries no form (a list stored over it, alone or with older form rows behind it), or an internal record form is served ahead of a row with a public link and is not removed because of it. Every row of the name stays as stored, and the address keeps answering as it does today. Where another package serves that row with a public link and would move it, the row holds the upgrade at every one of those packages instead: both rows stay. Both rows stay as stored at every other package too: where either stands behind a row another package would move or remove, that move or removal holds the upgrade instead of folding or removing it. When the row served is one whose form content cannot be read, the form waits on that row, which holds the upgrade (below). | +| **left in place** | Nothing moves. The row served for the name carries no form (a list stored over it, alone or with older form rows behind it), or an internal record form is served ahead of a row with a public link and is not removed because of it. Every row of the name stays as stored, and the address keeps answering as it does today. Where another package serves that row with a public link and would move it, the row holds the upgrade at every one of those packages instead: both rows stay. Both rows stay as stored at every other package too: where either stands behind a row another package would move or remove, that move or removal holds the upgrade instead of folding or removing it. When the row served is one whose form content cannot be read, the form waits on that row, which holds the upgrade (below). A form no door serves today is left in place by the upgrade too, whatever package its row is bound to: the server serves no form of that name at the address the report names, so nothing of it moves, its rows stay as stored there, and the address keeps answering as it does today. A form that is switched off is not one of these: the server serves it closed, and it moves with its switch. | | **holds the upgrade** | The row cannot be moved. The report repeats the reason and the action. | +For each form, the report asks the server whether it serves a form of that +name today at the address the report names it at: a package, or the +environment. For a form stored with no package, the environment's address +covers every place the server serves it, under a package that ships only a +list of that name included. A form it does not serve there is **left in +place** where the table would move it, and also where the move would hold the +upgrade because its `.custom` package cannot be ensured or its destination is +sealed: the upgrade never moves a form into service. + A list stored behind the row served for a form is not part of it: the upgrade leaves it as stored, and the report says so. When a row is read at more than one package, the report names it at each. Where the server today serves one @@ -73,6 +82,44 @@ A row that declares a public link, or that stands over a form that declares one, is never offered for deletion. Deleting such a row would open a form that is closed today. +## What the upgrade command writes + +The major's upgrade command runs the same check first, and writes only when +no row holds the upgrade. If one row holds it, nothing is written: every +stored row stays byte for byte as it is, both public doors answer as they do +today, and the deployment stays on the release it is running. + +Otherwise, the `.custom` packages the moves land in are created first, +through the one path that creates them, before any row is written. They stay +if the run fails: an empty `.custom` package changes no answer, and the next +run reuses it. Then, in one transaction: + +1. Each form that moves is written as a form row at its destination, with its + body as stored. A form whose folded row switched it off is written switched + off, its link kept. Each written row is read back before anything else + changes. +2. Then the old rows go: a view item row is deleted; a stored view container + is saved again without the form it held, its lists and any form it still + keeps byte for byte as they were. A container left with nothing in it is + deleted. +3. Each internal record form listed as **will be removed** is deleted the same + way, and the report carries its body. + +If any step fails, the transaction rolls back and every stored row stays as +it was. + +The upgrade command writes only on a database that can roll a transaction +back. Where the database's driver cannot, the command refuses before it +changes anything (no `.custom` package is created either) and names the +driver. Run the upgrade against a database whose driver supports +transactions, or stay on the release you are running. `os migrate +stored-forms` still reports what the upgrade would move, and says on such a +database that the upgrade's run will be refused. A run with nothing +to move or remove is not refused. + +A form left in place is not touched, nor is a draft. Run the command again and +it finds nothing left to move. + ## Clearing a row that holds the upgrade | Cause | Who can clear it | What to do | @@ -82,6 +129,7 @@ that is closed today. | The app declares no namespace, or an invalid one; its version is not SemVer; or the package belongs to several apps and its namespace picks none | The app's author | The deployment stays on the release it is running until the app ships a version without the cause. The row keeps working as it does today meanwhile. | | The package is a kernel package, which has no `.custom` package in this version | The platform maintainers | Report it before upgrading. | | Two rows would land in one slot of an app's `.custom` package, or one row that several packages serve would not be treated alike by all of them | No one, on this release | No exit from it was measured: the deployment stays on the release it is running, and every address keeps answering as it does today. Where the row is read at two packages of one app that would both move it, the app shipping the form from one of those packages only lets it be read at that package alone. Where the row waits on another hold of its own, it takes that hold's row above. | +| Another package ships a `form` item under the form's name, so the row would be written over a managed package's item, which is sealed | The author of the package that ships it | No exit from it was measured: the deployment stays on the release it is running, and the row keeps working as it does today. | | The stored view's form content cannot be read | The administrator | Save the view again with its form content repaired (a `form` or `formViews` entry that is an object), then run the check again. On the release you are running, both public doors answer for the row as they do today. On the next major its links close, and that server's start-up log names each such row and points to this command. | ## Also listed diff --git a/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md b/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md index e628906788e..4a8863c68ee 100644 --- a/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md +++ b/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md @@ -285,7 +285,8 @@ Each pin asserts the refusal's status and `code` and that no record was written, - A stored `view` item with `viewKind: 'form'` becomes a `form` row at the same `(package, name)`; a stored container is split — its lists stay a `view` row, each form becomes a `form` row. - A **`.custom` override** of a form keeps its package, its name and its `overrides` declaration, `basedOn` unchanged: it is the same override in the type its base now has. This covers every switch Setup has written, and every override that differs from its base in any other way, a cleared link included: an override is never set aside as an internal record form on its own body (D7-b). - A **package-less overlay row** over a packaged form (ADR-0146 D11's unmigrated class) is moved to the destination D11 gives it: a declared `form` override in the base's pair, with its body as written — its switch when it has one, and no link when it has none (D7-b). -- A **form row bound to a read-only package that ships no form of its name**, and a pair's declared override of a base that ships none, is served today at the package it is bound to. It moves into that package's pair as the pair's own `form` item, declaring no `overrides`, with its body as written, so its public address answers byte-equal before the ceremony and after it (the precedent is ADR-0146's ceremony, which stores a member the base does not ship as the pair's own member). When that pair cannot be ensured, D7-c's hold applies. A package-less row of the same name behind it folds into it (D7-d), and the name has no environment address while such a row stands. An internal record form among these rows still takes ruling 3's deletion and needs no destination. Ruled by the maintainer on 2026-11-29: 「B 搬进定制包(推荐)」 (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204) on #37111). Where a row bound to the base stands beside a pair's declared override of that base, D7-d decides, and the ruling's words do not reach it: the read serves the override at the base's address and the bound row nowhere, so the override's body is the one kept, as the own `form` item of the pair it stands in, the bound row folds into it, and the ensure door is not asked. An override a second pair of the same base holds is not the one served there, and keeps its own pair's address, where it is served today: D7-d keeps the body the read serves today, so this follows from D7-d and goes past no ruling's words. The ruling holds on its stated premise, that the row is served today at the package it is bound to: a row the read serves at another address is classed by the base it stands over there (D7-b) and takes the destination D7 gives a row bound to a read-only base, with D7-c's hold where that pair cannot be ensured, D7-e is unchanged, and the ruling stands for every row its premise holds for (ruled by the maintainer on 2026-11-29, option A of four: ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842) on #37111). Where the read serves one row at two addresses, that destination cannot be given at both: a pair holds one row of a type and name, and a row declares one base (ADR-0146 D2). Ruled by the maintainer on 2026-11-30: 「A 拦住升级·同类全覆盖」 (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661). Such a row is moved at neither address and holds the upgrade, and both addresses answer as they do today. The same hold covers every slot of a pair that more than one plan claims, and no further decision is owed for that class. A plan is what D7 gives one form name at one address; a slot is the one row of a type and name a pair holds. No new hold cause, no new kind of plan, no new "not counted" kind and no protocol key come with the ruling. The ruling, against the rules it touches: +- A **form no door serves today is left in place by the upgrade**, whatever row holds it and whatever package that row is bound to; the upgrade never moves one into service. "No door serves" has one meaning here: the effective `form` read, the read both public doors take their candidates from, lists no form of the name at the address the plan is made at. At the environment's own address, which a name has only while no package ships its form and no stored row of it is bound to a package, that address is every slot the read seats the name's package-less row in, a package's slot included. A withdrawn form is not such a form: its switch is off, so both doors answer `404` for it today, but the read lists it, and it moves with its switch (D7-a, D7-d). Nor is an internal record form: no public door is meant to serve it, and it takes ruling 3's deletion. Left in place, the plan at that address moves and writes nothing, the form is not counted, and its served row and the rows behind it stay as stored there, unless the read also serves one of them at another address: that row takes what D7 gives it at that address, so it goes with a move made there, or folds into the form served there (D7-d). A plan of the form that holds at a slot, or for a row more than one address serves, still holds (ruling record `7265816895`). No other hold stands for it: where its move would hold at the pair door (D7-c) or at a destination the store seals, it is left in place instead. Ruled by the maintainer on 2026-11-30: 「本 PR 修,原地不动」 (ruling record [`7277149723`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7277149723) on #37111). +- A **form row bound to a read-only package that ships no form of its name**, and a pair's declared override of a base that ships none, is served today at the package it is bound to, unless no door serves it (the rule above). A row that is served today moves into that package's pair as the pair's own `form` item, declaring no `overrides`, with its body as written, so its public address answers byte-equal before the ceremony and after it (the precedent is ADR-0146's ceremony, which stores a member the base does not ship as the pair's own member). When that pair cannot be ensured, D7-c's hold applies. A package-less row of the same name behind it folds into it (D7-d), and the name has no environment address while such a row stands. An internal record form among these rows still takes ruling 3's deletion and needs no destination. Ruled by the maintainer on 2026-11-29: 「B 搬进定制包(推荐)」 (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204) on #37111). Where a row bound to the base stands beside a pair's declared override of that base, D7-d decides, and the ruling's words do not reach it: the read serves the override at the base's address and the bound row nowhere, so the override's body is the one kept, as the own `form` item of the pair it stands in, the bound row folds into it, and the ensure door is not asked. An override a second pair of the same base holds is not the one served there, and keeps its own pair's address, where it is served today: D7-d keeps the body the read serves today, so this follows from D7-d and goes past no ruling's words. The ruling holds on its stated premise, that the row is served today at the package it is bound to: a row the read serves at another address is classed by the base it stands over there (D7-b) and takes the destination D7 gives a row bound to a read-only base, with D7-c's hold where that pair cannot be ensured, D7-e is unchanged, and the ruling stands for every row its premise holds for (ruled by the maintainer on 2026-11-29, option A of four: ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842) on #37111). Where the read serves one row at two addresses, that destination cannot be given at both: a pair holds one row of a type and name, and a row declares one base (ADR-0146 D2). Ruled by the maintainer on 2026-11-30: 「A 拦住升级·同类全覆盖」 (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661). Such a row is moved at neither address and holds the upgrade, and both addresses answer as they do today. The same hold covers every slot of a pair that more than one plan claims, and no further decision is owed for that class. A plan is what D7 gives one form name at one address; a slot is the one row of a type and name a pair holds. No new hold cause, no new kind of plan, no new "not counted" kind and no protocol key come with the ruling. The ruling, against the rules it touches: - **What is held.** A plan claims a slot where it keeps or moves a row in a pair under the name, as the pair's declared override or as the pair's own `form` item; a `form` row already stored there claims the slot as a row that would move there does. The pair's own row of the name is such a claimant: a row the pair holds as its own item, declaring no `overrides`, is read at the pair's own address, where the plan keeps it if it is a `form` row and moves it into the pair's own `form` row if it is an old-shape `view` row, and either way it claims the pair's slot; beside a row another address plans into that pair, both are held. Two cases are held. The first is the slot: where more than one plan claims one slot, every claimant is held, be it one row the read serves at two addresses of one App, whose two plans claim the App's one pair, or two rows, each read at its own address, that would both land in one pair. The second is the row more than one address serves, and it is decided per stored row, over every address that serves it, whatever App each address is of. A move or a removal takes the row from every address that serves it, so the row is moved only where every one of them would move it, each into its own destination, and removed only where every one of them would remove it (ruling 3). Where one would move or remove it and another keeps it, or one would move it and another remove it, every plan of the row holds the upgrade and the row is moved or removed at none of them. An address keeps the row where it leaves it in place (D7-d: an internal record form ahead of a row that declares a link), where the row already stands at its destination, and where the row holds there; a base whose App cannot be read has no pair, so the row holds there (D7-c), and that address keeps it. An address also keeps a form row that stands behind an internal record form it leaves in place, though it does not serve that row: this is the seat's reading of the ruling of 2026-11-29 (`7249158572`), stated under "Against D7-d". No plan need claim a slot in the second case. It is the owning seat's step under the ruling, not the maintainer's words: the ruling leaves both addresses of its row answering as they do today, and the seat reads the same for every address that serves a row. A held row is folded into no other row, be it held at the pair door (D7-c) or under this ruling: D7-c has the ceremony write nothing for it. Where a row that holds the upgrade where it is served stands behind the row another address keeps or moves, that address's plan lists it apart from the rows that fold into its served row, and the fold there is read without it: its withdrawal is not carried, and no form is named newly closed on its account. The report says the row is not folded because it holds the upgrade where it is served. Where every address that serves a row would move it and the moves land in different pairs, no slot is claimed twice, and D7 gives each its destination as before. - **Against D7-b.** Each address still classes the row by the base it stands over there, and only a row this classing gives a destination in a pair claims a slot. The classing can differ between two addresses that serve one row, of one App or of two: one would move it, and the other gives it no destination or would remove it. The row is then held as above, and is moved or removed at neither. A row that every address that serves it would treat alike is not held for that: an internal record form takes ruling 3's removal where every one of them would remove it, and a row every one of them would move takes its destination at each, unless two of those moves claim one slot. - **Against D7-c.** The hold is the one D7-c gives a row whose pair cannot be ensured: the ceremony writes nothing for the row, it stays as stored on the pre-upgrade release, which reads it as it does today, the precheck counts it, and the upgrade does not switch. The precheck names each held row once, and a row more than one address serves with every one of them; a row one of whose plans already holds, under D7-c or at a slot, is named by that hold and not a second time. Where the second case holds such a row, its plans that would not hold by themselves wait on that hold only where every other address would move the row: each then takes its cause and its action, an administrator's where the hold is one an administrator removes, and its refusal names the address the hold stands at and repeats that hold's own refusal. Where some other address would not move the row, those plans do not wait: they hold as every other row of the second case does, with an action that names no exit, and neither their refusal nor their action says what clearing that hold alone would bring, which was not measured. Every other hold under the ruling takes the class of a cause only the App's author can remove. Neither the class nor the waiting is the maintainer's words: each is the seat's step under the ruling, and the class is read from the rule, because no exit of the administrator's own that leaves every address's answer as it is was measured. The action of a hold that does not wait says only what was measured. D7-c's sentence for the class, that the deployment stays on its release until the App ships a version without the cause, is therefore not said of these holds as a class; the precedent for an action that names no exit is D7-c's own, for the pair an earlier version created (ruling record `7250982640`). One exit was measured: for one row read at two or more addresses of one App and at no address besides, where every one of its plans claims the App's one pair and no other row claims that slot, or where one address would move the row and another would not, no address keeps it behind an internal record form and no plan of it already holds, the action names the App, says only its author can remove the cause, and says the deployment stays on the release it is running until the App ships the form from one of those packages only; the row is then read at that address alone and takes what D7 gives it there. For every other hold that does not wait, no exit was measured, and the action promises none: it says that no action on this release clears the hold, that no exit from it was measured, and that the deployment stays on the release it is running while every address answers as it does today. At a slot, and for a row of one App, it also says the cause is in the App and its author's to remove, and names the App. For a row more than one address serves, the App is named, in either way, only where every address that serves the row, or keeps it behind an internal record form, is of one App that can be read, as a base of that App or as the App's pair. Otherwise the action says where the row is served, naming each App that can be read, each base whose App cannot be read and each package this environment writes, and says that no one App's author can remove the cause alone. diff --git a/packages/cli/src/commands/migrate/stored-forms.test.ts b/packages/cli/src/commands/migrate/stored-forms.test.ts new file mode 100644 index 00000000000..ab79859ea88 --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.test.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import type { StoredFormAddressPlan, StoredFormCensus } from '@objectstack/metadata-protocol'; +import { 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). +vi.mock('@objectstack/metadata-protocol', () => ({})); +vi.mock('@objectstack/rest', () => ({})); +vi.mock('@objectstack/runtime', () => ({})); +vi.mock('@objectstack/plugin-security', () => ({})); +vi.mock('@objectstack/platform-objects/plugin', () => ({})); +vi.mock('@objectstack/driver-sql', () => ({})); +vi.mock('@objectstack/driver-turso', () => ({})); +vi.mock('@objectstack/service-datasource', () => ({})); + +const ROW = { type: 'view', name: 'crm_lead.intake', form: 'crm_lead.intake' } as const; +const plan = (outcome: StoredFormAddressPlan['outcome'], extra: Record = {}): StoredFormAddressPlan => ({ + form: 'crm_lead.intake', address: { kind: 'environment' }, served: ROW, behind: [], untouched: [], alsoReadAt: [], outcome, + ...(outcome === 'move' || outcome === 'keep' ? { destination: { kind: 'environment_form' } } : {}), + ...(outcome === 'left_in_place' ? { reason: 'served_by_no_door' } : {}), + ...extra, +} as unknown as StoredFormAddressPlan); +const census = (forms: StoredFormAddressPlan[], canSwitch = true): StoredFormCensus => ({ + forms, unreadable: [], drafts: [], sharedSlugs: [], + precheck: { canSwitch, holds: [], counts: { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 } }, +}); +const engine = (transactions: boolean) => ({ + transaction: async (fn: () => Promise) => fn(), + getDefaultDriverName: () => 'default', + getDriverByName: () => ({ beginTransaction: async () => ({}), supports: { transactionsUnsupported: !transactions } }), +}); + +describe('[ADR-0159 D7] the census report says where the upgrade\'s run will be refused (a database that cannot roll back)', () => { + it('a census that moves a row, on a driver that cannot roll back: the report names the driver and what to do (ablate: the report\'s read of the rollback)', () => { + const text = storedFormRunRefusal(census([plan('move')]), engine(false)); + expect(text).toContain("'default' cannot roll back"); + expect(text).toContain('supports transactions'); + expect(text).toContain('stay on the release'); + }); + + it('CONTROL: the same census on a driver that can roll back says nothing more', () => { + expect(storedFormRunRefusal(census([plan('move')]), engine(true))).toBeUndefined(); + }); + + it('CONTROL: a census that writes and takes nothing, or that holds the upgrade, says nothing more', () => { + expect(storedFormRunRefusal(census([plan('left_in_place'), plan('keep')]), engine(false))).toBeUndefined(); + expect(storedFormRunRefusal(census([plan('move')], false), engine(false))).toBeUndefined(); + }); +}); diff --git a/packages/cli/src/commands/migrate/stored-forms.ts b/packages/cli/src/commands/migrate/stored-forms.ts index 16c92dfd8a9..51a30db2db7 100644 --- a/packages/cli/src/commands/migrate/stored-forms.ts +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -2,7 +2,7 @@ import { Command, Flags } from '@oclif/core'; import chalk from 'chalk'; -import { STACK_TIER_PRESETS } from '@objectstack/core'; +import { STACK_TIER_PRESETS, engineCanRollBack } from '@objectstack/core'; import { printHeader, printSuccess, @@ -37,6 +37,21 @@ const EMPTY: StoredFormCensus = { precheck: { canSwitch: true, holds: [], counts: { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 } }, }; +/** + * [ADR-0159 D7] The sentence the report adds where the upgrade's run will be + * refused: it writes only on a database that can roll a transaction back, and + * this census plans a write or a removal. `undefined` otherwise. + */ +export function storedFormRunRefusal(census: StoredFormCensus, engine: unknown): string | undefined { + if (!census.precheck.canSwitch) return undefined; + const writes = census.forms.some((plan) => plan.outcome === 'move' || plan.outcome === 'remove' + || (plan.outcome === 'keep' && (plan.carries !== undefined || plan.behind.length > 0))); + if (!writes || engineCanRollBack(engine)) return undefined; + const driver = (engine as { getDefaultDriverName?: () => string | undefined } | null | undefined)?.getDefaultDriverName?.(); + return `The upgrade's run will be refused on this database: the default driver${driver !== undefined ? ` '${driver}'` : ''} cannot roll back a transaction, and the upgrade moves stored forms all or nothing. ` + + 'Run the upgrade against a database whose driver supports transactions, or stay on the release you are running.'; +} + /** One row as the report names it. */ export function storedFormRowText(row: StoredFormRowRef): string { const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; @@ -120,6 +135,8 @@ function storedFormPlanSentence(plan: StoredFormAddressPlan): string { return `left in place: ${storedFormRowText(plan.served)} is an internal record form, and it is not removed because ${plan.behind.filter((r) => r.link !== undefined).map(storedFormRowText).join('; ')}, which declares a public link, stands behind it; both rows stay as stored, and the address keeps answering 404`; case 'served_unreadable': return `waits: ${storedFormRowText(plan.served)} cannot be read (listed below)`; + case 'served_by_no_door': + return `left in place: ${storedFormRowText(plan.served)} is a form no door serves today, so the upgrade leaves it as stored and no row of it moves`; } } } @@ -266,6 +283,7 @@ export default class MigrateStoredForms extends Command { const reads = absentTableReads(stack); 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); if (json) { reads.notice(true); @@ -273,6 +291,7 @@ export default class MigrateStoredForms extends Command { database: stack.dbLabel, hostConfig: stack.composition.hostConfigPath, canSwitch: precheck.canSwitch, + ...(runRefused !== undefined ? { runRefused } : {}), counts: precheck.counts, holds: precheck.holds, forms: census.forms, @@ -312,7 +331,9 @@ export default class MigrateStoredForms extends Command { } const c = precheck.counts; 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 (precheck.canSwitch) { + if (runRefused !== undefined) { + printWarning(runRefused); + } else if (precheck.canSwitch) { printSuccess(`The upgrade can switch: no stored row holds it ${chalk.dim(`(${timer.display()})`)}`); } else { // Each hold prints the action for its own cause; not every cause can be removed on this release (ADR-0159 D7-c). diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index cd2b235af93..3d9fee13a40 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -364,6 +364,9 @@ export type { StoredFormPrecheck, StoredFormRowRef, } from './protocol-stored-form-migration.js'; +// [ADR-0159 D7, card ⑤a] The ceremony's write half (`--apply`): the major's upgrade command calls it, ⛔ nothing else. +export { applyStoredFormsOf } from './protocol-stored-form-apply.js'; +export type { StoredFormApplyResult, StoredFormRemoved, StoredFormRowKey, StoredFormWritten } from './protocol-stored-form-apply.js'; // [#28412, ADR-0146 D9 item 1] The `package_id` column of the stored row a // registry body was hydrated from, recorded by the protocol's hydration and diff --git a/packages/metadata-protocol/src/protocol-stored-form-apply.ts b/packages/metadata-protocol/src/protocol-stored-form-apply.ts new file mode 100644 index 00000000000..edc305d6542 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-apply.ts @@ -0,0 +1,456 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The stored-form ceremony, its write half (ADR-0159 D7, card ⑤a) + * + * `--apply` of the ceremony whose read-only half is + * `protocol-stored-form-migration.ts`: the move, the fold and the removal of + * every stored old-shape form row, as the census plans them. ⛔ Reached only + * from the major's upgrade command (the sequencing ruling, record + * `7142585849` on #36868: convert first, then switch): the standalone + * `os migrate stored-forms` stays read-only, so no administrator moves rows + * on a deployment that then stays on its pre-upgrade release. + * + * ## All or nothing with the switch + * + * The plan is computed whole first ({@link listStoredForms}). Where the + * precheck still counts a row (`canSwitch` false: a pair that cannot be + * ensured, a body the projection cannot read, a contested slot, a row served + * apart), {@link applyStoredForms} writes nothing: no row is moved, no + * internal record form is removed, no pair is ensured, every stored row stays + * byte-equal, and both public doors answer as before. A deployment that does + * not switch holds every stored row as it was (ruled question 4: no withdrawn + * public form may re-open), so a switch-off is never left in a `form` row the + * pre-upgrade release does not read. + * + * ## 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 + * 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 + * `form` row already at its destination that takes a carried withdrawal + * is written again with its switch off. + * 3. Every written row is read back at its address, and must be the row the + * write put there; one copy per address of a row read at several. + * 4. Only then are the old-shape rows taken away: a row whose every form + * goes (moved, folded or removed) and that holds no list is deleted; a + * container that also holds lists, or a form the ceremony leaves as + * stored, is re-saved without the members that go, the rest byte-equal + * (`oldShapeFormRowRemovals`, the `form` write door's own removal). + * + * Writes go through the repository beneath the doors: a move is not a save. + * ⛔ The `form` save door's address-clash refusal is not asked (ADR-0159 D7: + * a retired form and its successor on one address are both moved as written, + * and what the doors serve does not change). Steps 2 to 4 are one + * transaction, so a failure leaves every row as it was. The pairs of step 1 + * are ensured before it and stay after a rollback: an empty pair changes no + * door's answer, and the next run reuses it. On an engine that cannot roll + * back, a run that would write or take a row is refused before anything is + * written (the pairs included), naming the driver: a run cut short there + * could leave a deployment that does not switch without a row it reads. A + * second run finds nothing to move (idempotent): every moved row is then a + * stored `form` row at its destination (`keep`). + * + * `sys_metadata_history` rows are never rewritten: each write appends its own. + * The registry follows the store after the commit, as the doors heal it. + */ + +import { engineCanRollBack } from '@objectstack/core'; +import { isAggregatedViewContainer, PROJECTED_FORM_SOURCE_KEY } 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 { + listStoredForms, + type StoredFormAddressPlan, + type StoredFormCensus, + type StoredFormCensusHost, + type StoredFormDestination, + type StoredFormRowRef, +} from './protocol-stored-form-migration.js'; +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; +} + +/** One `form` row the ceremony wrote (a move, or a carried withdrawal on a row already in place). */ +export interface StoredFormWritten { + readonly form: string; + readonly row: StoredFormRowKey; + readonly destination: StoredFormDestination; + /** The stored row whose body it holds. */ + readonly from: StoredFormRowRef; + /** The slug switched off on it, carried from a folded row (D7-d). */ + readonly switchedOff?: string; +} + +/** One internal record form the ceremony removed (ruling record `7142585849`, item 3). */ +export interface StoredFormRemoved { + readonly form: string; + readonly row: StoredFormRowRef; + readonly object?: string; + /** Whether the object declares field groups: New and Edit of it follow them from now on. */ + readonly objectHasFieldGroups: boolean; + /** The removed form's body, as it was stored. */ + readonly body: Record; +} + +/** What {@link applyStoredForms} did. */ +export interface StoredFormApplyResult { + /** `false` when the precheck held the upgrade: nothing was written. */ + readonly applied: boolean; + /** The census the run computed before any write. */ + readonly census: StoredFormCensus; + /** The pairs the ensure door created for the moves. */ + readonly pairsEnsured: readonly string[]; + readonly written: readonly StoredFormWritten[]; + readonly removed: readonly StoredFormRemoved[]; + /** The old-shape rows taken away: deleted, or re-saved without the members that went. */ + readonly rowsChanged: readonly (StoredFormRowKey & { readonly change: 'deleted' | 'resaved' })[]; +} + +/** The host members the write half reads, beside the census's. */ +export type StoredFormApplyHost = StoredFormCensusHost + & Pick + & { + /** The ensure door ({@link ObjectStackProtocolImplementation.ensureCustomizationPackage}). */ + 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. + * + * @param request.actor recorded on every write (`null` for the upgrade command, which has no human actor). + */ +export async function applyStoredForms(host: StoredFormApplyHost, request: { actor: string | null }): Promise { + const census = await listStoredForms(host); + 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 }; + + const places = await storedFormPlaces(host); + const writes = new Map }>(); + /** The forms that go from each stored row, by the row's key. */ + const goes = new Map }>(); + const removed: StoredFormRemoved[] = []; + const take = (ref: StoredFormRowRef): void => { + const place = placeOf(places, ref); + const key = rowKeyOf(place.entry.type, place.entry.name, place.packageId); + const entry = goes.get(key) ?? { place, forms: new Set() }; + 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 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. + throw new Error(`Two plans write the ${row.key.type} row '${row.key.name}' in '${row.key.packageId ?? 'the environment'}'; nothing was written.`); + } + writes.set(key, { + write: { + form: plan.form, row: row.key, destination: plan.destination, from: plan.served, + ...(plan.carries !== undefined ? { switchedOff: plan.carries.slug } : {}), + }, + packageId: row.packageId, + body: row.body, + }); + }; + + for (const plan of census.forms) { + if (plan.outcome === 'move') { + write(plan, formBodyOf(placeOf(places, plan.served), plan.form)); + 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); + } + for (const row of plan.behind) take(row); + } else if (plan.outcome === 'remove') { + const body = formBodyOf(placeOf(places, plan.served), plan.form); + removed.push({ + form: plan.form, row: plan.served, + ...(plan.object !== undefined ? { object: plan.object } : {}), + objectHasFieldGroups: plan.objectHasFieldGroups, body, + }); + take(plan.served); + for (const row of plan.behind) take(row); + } + // `left_in_place` writes nothing; `hold` cannot be here (`canSwitch`). + } + + // A row a plan writes to is never one another plan takes away. + for (const key of writes.keys()) { + if (goes.has(key)) throw new Error(`A plan writes the row another plan takes away (${key.split('\u0000').join(' ')}); nothing was written.`); + } + + // All or nothing needs a database that can roll back: on one that cannot, + // a run cut short after an old row went would leave a deployment that + // does not switch without it. Refused before anything is written. + const engine = host.engine as unknown as { transaction?: (fn: () => Promise) => Promise; getDefaultDriverName?: () => string | undefined }; + if ((writes.size > 0 || goes.size > 0) && !engineCanRollBack(engine)) { + const driver = engine.getDefaultDriverName?.(); + throw new Error( + `The stored-form upgrade refuses --apply here: the default driver${driver !== undefined ? ` '${driver}'` : ''} cannot roll back a transaction, and the upgrade moves stored forms all or nothing. Nothing was written. ` + + 'Run the upgrade against a database whose driver supports transactions, or stay on the current release; `os migrate stored-forms` still reports what the upgrade would move.', + ); + } + + // Step 1: the pairs, through the ensure door, before any row is written. + const registry = (host.engine as { registry?: { getPackage?: (id: string) => unknown } } | undefined)?.registry; + const pairsEnsured: string[] = []; + for (const { write: w } of writes.values()) { + const d = w.destination; + if (d.kind !== 'pair_override' && d.kind !== 'pair_form') continue; + if (pairsEnsured.includes(d.pair) || registry?.getPackage?.(d.pair)) continue; + await host.ensurePair(d.base); + pairsEnsured.push(d.pair); + } + + type Changed = Awaited>; + let changed: Changed = []; + const run = async (): Promise => { + // Steps 2 and 3: the destination rows, each read back; step 4: the old rows, once every copy reads back. + await writeStoredFormCopies(host, [...writes.values()], request.actor); + changed = await takeStoredFormRows(host, [...goes.values()], request.actor); + }; + // Without a rollback nothing is written or taken here (refused above). + if (engineCanRollBack(engine)) await retireOverlayCacheOnRollback(engine, () => engine.transaction!(run)); + else await run(); + const rowsChanged = changed; + + // The registry follows the store, after the commit. + await healStoredFormRows(host, [ + ...[...writes.values()].map(({ write: w, packageId, body }) => ({ type: 'form', name: w.row.name, packageId, item: body })), + ...rowsChanged.flatMap((row) => (row.change === 'resaved' ? [{ type: row.type, name: row.name, packageId: row.packageId ?? null, item: row.body! }] : [])), + ], rowsChanged.filter((row) => row.change === 'deleted').map((row) => ({ type: row.type, name: row.name, packageId: row.packageId ?? null }))); + + return { + applied: true, + census, + pairsEnsured, + written: [...writes.values()].map(({ write: w }) => w), + removed, + rowsChanged: rowsChanged.map(({ body: _body, ...row }) => row), + }; +} + +const WRITE_SOURCE = 'stored-forms --apply'; +const WRITE_MESSAGE = 'Stored old-shape form moved, folded or removed by the upgrade (ADR-0159 D7)'; + +/** The store's judgement of a write: an edit of a shipped item, or a runtime write. */ +function intentOf(host: StoredFormApplyHost, type: string, name: string): 'override-artifact' | 'runtime-only' { + return host.isArtifactBacked(type, name) ? 'override-artifact' : 'runtime-only'; +} + +/** + * Steps 2 and 3: write each destination `form` row, and read it back at its + * own address. Called INSIDE {@link applyStoredForms}'s transaction; the + * caller heals the registry after the commit ({@link healStoredFormRows}). + * Throws on a row that does not read back as written. + */ +async function writeStoredFormCopies( + host: StoredFormApplyHost, + writes: ReadonlyArray<{ write: StoredFormWritten; packageId: string | null; body: Record }>, + actor: string | null, +): Promise { + const repo = host.getOverlayRepo(); + for (const { write: w, packageId, body } of writes) { + const ref = { type: 'form', name: w.row.name, org: 'env' } as Parameters[0]; + const { head } = await repo.headAt(ref, { state: 'active', packageId }); + const put = await repo.put(ref, body, { + parentVersion: head?.hash ?? null, actor, source: WRITE_SOURCE, message: WRITE_MESSAGE, + // [ADR-0146 D2] A declared override writes the pair's own row and edits no + // managed item: the store judges it a runtime write, as the save door does. + intent: body.overrides !== undefined ? 'runtime-only' : intentOf(host, 'form', w.row.name), state: 'active', packageId, + } as Parameters[2]); + const back = await repo.headAt(ref, { state: 'active', packageId }); + if (back.head === null || back.head.hash !== put.version || (back.packageId ?? null) !== packageId) { + throw new Error(`The form row '${w.row.name}' written into '${packageId ?? 'the environment'}' does not read back as written; nothing was moved.`); + } + } +} + +/** + * Step 4: delete or re-save each old-shape row the plans take ({@link remaining}), + * locked against the checksum it is stored at. Called INSIDE + * {@link applyStoredForms}'s transaction, after every copy reads back; returns + * the rows it changed, which the caller heals after the commit + * ({@link healStoredFormRows}). + */ +async function takeStoredFormRows( + host: StoredFormApplyHost, + goes: ReadonlyArray<{ place: StoredFormPlace; forms: ReadonlySet }>, + actor: string | null, +): Promise }>> { + const repo = host.getOverlayRepo(); + const changed: Array }> = []; + const stored = await rawActiveRows(host); + for (const { place, forms } of goes) { + const raw = stored.get(rowKeyOf(place.entry.type, place.entry.name, place.packageId)); + const ref = { type: place.entry.type, name: place.entry.name, org: 'env' } as Parameters[0]; + const options = { + parentVersion: typeof raw?.checksum === 'string' ? raw.checksum : null, + actor, source: WRITE_SOURCE, message: WRITE_MESSAGE, + intent: intentOf(host, place.entry.type, place.entry.name), state: 'active' as const, + packageId: place.packageId ?? null, + }; + const key = { type: place.entry.type, name: place.entry.name, ...(place.packageId !== undefined ? { packageId: place.packageId } : {}) }; + const next = remaining(host, place, forms); + if (next === undefined) { + await repo.delete(ref, options as Parameters[1]); + changed.push({ ...key, change: 'deleted' }); + } else { + await repo.put(ref, next, options as Parameters[2]); + changed.push({ ...key, change: 'resaved', body: next }); + } + } + return changed; +} + +/** + * The registry follows the store, after {@link applyStoredForms} commits: each + * live row it wrote is written through (`type` is the literal `'form'` for a + * copy, and the stored row's own type for a re-saved container), and each row + * it deleted is healed from what the store then serves. + */ +async function healStoredFormRows( + host: StoredFormApplyHost, + live: ReadonlyArray<{ type: string; name: string; packageId: string | null; item: Record }>, + deleted: ReadonlyArray<{ type: string; name: string; packageId: string | null }>, +): Promise { + for (const row of live) { + await host.applyRegistryWriteThrough({ type: row.type, name: row.name, item: row.item, packageId: row.packageId, organizationId: null } as never); + } + for (const row of deleted) await host.restoreArtifactRegistryView(row.type, row.name, null, row.packageId); +} + +/** The active stored rows of both types, raw, by key: the checksum each write locks against. */ +async function rawActiveRows(host: StoredFormApplyHost): Promise>> { + const out = new Map>(); + for (const type of ['form', 'view']) { + for (const row of await host.readActiveOverlayRows({ type })) { + const entry = host.storedOverlayEntries({ type }, [row])[0]; + if (entry === undefined) continue; + out.set(rowKeyOf(entry.type, entry.name, entry.packageId), row as Record); + } + } + return out; +} + +/** + * The body a stored row keeps once `forms` go from it, or `undefined` when + * nothing of it stays (the row is deleted). A `form` row and an item-shaped + * `view` row hold one form: it goes, and the row with it. A container is + * re-saved without each member that goes, through the `form` write door's own + * removal ({@link oldShapeFormRowRemovals}): its lists, and any form the + * ceremony leaves as stored, byte-equal. + */ +function remaining(host: StoredFormApplyHost, place: StoredFormPlace, forms: ReadonlySet): Record | undefined { + if (place.type === 'form' || place.grain === 'item') return undefined; + let body = place.entry.data as Record; + const holdingsOf = (entry: { data: unknown; packageId: string | undefined }) => storedViewRowHoldings(host, entry); + for (const form of forms) { + const [removal] = oldShapeFormRowRemovals([{ name: place.entry.name, data: body, packageId: place.packageId }], form, place.packageId ?? null, holdingsOf); + if (removal === undefined) { + throw new Error(`The member of the stored view '${place.entry.name}' that carries '${form}' could not be named; nothing was written.`); + } + if (removal.kind === 'delete') return undefined; + body = removal.body; + } + // A container every member of which went is no container any more: the + // re-saved remnant (`{ name, object }`) would read as an unreadable row + // that holds the next run's switch. It goes, as a row that holds nothing. + if (!isAggregatedViewContainer(body)) return undefined; + return storedViewRowHoldings(host, { data: body, packageId: place.packageId }).size === 0 ? undefined : body; +} + +/** + * [ADR-0159 D7, card ⑤a] {@link applyStoredForms} over a live protocol + * instance. ⛔ Called by the major's upgrade command only: the standalone + * `os migrate stored-forms` is read-only. + */ +export function applyStoredFormsOf(protocol: ObjectStackProtocolImplementation, request: { actor: string | null }): Promise { + // The host's own members, read at call time, and the ensure door beside them. + const host = Object.create(protocolHost(protocol), { + ensurePair: { value: async (base: string) => { await protocol.ensureCustomizationPackage({ basePackageId: base }); } }, + }) as StoredFormApplyHost; + return applyStoredForms(host, request); +} diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts index 5225067035e..ca55b0ed9b0 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts @@ -16,8 +16,10 @@ import { storedViewRowHoldings, type StoredFormPlace } from './protocol-form-rea import { INTERNAL_AHEAD_OF_LINKED_ROW, planStoredForms, + storedFormPairFix, type PairFixReading, type ShippedForm, + type StoredFormAddress, type StoredFormAddressPlan, type StoredFormCensus, type StoredFormPlanInput, @@ -99,6 +101,8 @@ function input(places: StoredFormPlace[], over: Partial & { isWritable: (pkg) => pkg === WORKSPACE || pkg === PAIR, actionTargets: new Set(), pairFix: () => PAIR_OK, + sealedFormShippers: () => [], + servedToday: () => true, objectHasFieldGroups: () => true, unreadable: [], ...over, @@ -296,6 +300,113 @@ describe('[ADR-0159 D7] planStoredForms — one outcome per form and address', ( expect(census.precheck.canSwitch).toBe(false); }); + it('a form no door serves today is left in place by the upgrade: a row bound to a read-only package that ships no form of the name, where the read serves no form of the name at that package, moves nothing and holds nothing (ablate: the census read of the form served today)', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + servedToday: (name, packageId) => !(name === NAME && packageId === OTHER), + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([ + [{ kind: 'base', packageId: OTHER }, 'left_in_place', 'served_by_no_door'], + ]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + for (const [hold, opts] of [ + ['the pair door refuses the pair (D7-c)', { pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }) }], + ['the store seals the destination', { pairFix: (base: string) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), sealedFormShippers: (name: string) => (name === NAME ? ['com.acme.shipper'] : []) }], + ] as const) { + it(`a form no door serves today is left in place before a hold its move would take: ${hold}, and nothing holds the upgrade (ablate: read the form served today before those holds)`, () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + ...(opts as Partial), + servedToday: (name, packageId) => !(name === NAME && packageId === OTHER), + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([ + [{ kind: 'base', packageId: OTHER }, 'left_in_place', 'served_by_no_door'], + ]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + } + + describe('a form no door serves today is left in place by the upgrade, whatever package its row is bound to (ablate: the census read of the form served today, at the address each plan is made at)', () => { + const unservedAt = (at: string | undefined) => (name: string, packageId: string | undefined) => !(name === NAME && packageId === at); + const shapes: readonly [string, StoredFormPlace, Parameters[1] & {}, StoredFormAddress][] = [ + ['a row bound to a writable package', viewFormRow(WORKSPACE, { enabled: true }), { ships: { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] } }, { kind: 'package', packageId: WORKSPACE }], + ['the pair\'s own item', viewFormRow(PAIR, { enabled: true }), { ships: {} }, { kind: 'package', packageId: PAIR }], + ['the pair\'s declared override of a base that ships none', viewFormRow(PAIR, { enabled: true, overrides: BASE }), { ships: {} }, { kind: 'package', packageId: PAIR }], + ['a package-less row', viewFormRow(undefined, { enabled: true }), { ships: {} }, { kind: 'environment' }], + ]; + for (const [shape, row, opts, address] of shapes) { + const at = address.kind === 'environment' ? undefined : address.packageId; + it(`${shape}: no row moves, nothing holds`, () => { + const census = planStoredForms(input([row], { ...opts, servedToday: unservedAt(at) })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([[address, 'left_in_place', 'served_by_no_door']]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + it(`CONTROL: ${shape}, where the read serves it today, moves`, () => { + const census = planStoredForms(input([row], opts)); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[address, 'move']]); + }); + } + }); + + describe('the store\'s seal (ADR-0131 D6): the census reads a destination the way the run\'s write meets it', () => { + const SHIPPER = 'com.example.shipper'; + const sealedBy = (name: string): readonly string[] => (name === NAME ? [SHIPPER] : []); + + it('the pair\'s own item, where another package ships the name as a `form` item: the row holds the upgrade, naming that package, and nothing moves', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + sealedFormShippers: sealedBy, + })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: OTHER }, 'hold']]); + expect(census.forms[0]).toMatchObject({ cause: 'app_author' }); + expect(census.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: OTHER, name: NAME }, cause: 'app_author' }] }); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + expect(census.precheck.holds[0]!.refusal).toContain('sealed'); + expect(census.precheck.holds[0]!.action).toContain(`'${SHIPPER}'`); + }); + + it('a kept `form` row the run writes, because it carries a withdrawal folded into it, reads the seal too: it holds the upgrade, naming that package, and nothing is written', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const rows = [formRow(WORKSPACE, { enabled: true }), viewFormRow(undefined, { enabled: false })]; + const census = planStoredForms(input(rows, { ships, sealedFormShippers: sealedBy })); + expect(census.forms.map((f) => [f.address, f.outcome, 'cause' in f ? f.cause : undefined])).toEqual([[{ kind: 'package', packageId: WORKSPACE }, 'hold', 'app_author']]); + expect(census.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: WORKSPACE, name: NAME }, cause: 'app_author' }] }); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + expect(census.precheck.holds[0]!.refusal).toContain('carry a withdrawal'); + }); + + it('CONTROL: the same kept row where no package ships a `form` item of the name is kept and carries the withdrawal', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const rows = [formRow(WORKSPACE, { enabled: true }), viewFormRow(undefined, { enabled: false })]; + const census = planStoredForms(input(rows, { ships, sealedFormShippers: () => [] })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'package', packageId: WORKSPACE }, 'keep']]); + expect(census.forms[0]).toMatchObject({ carries: { slug: SLUG } }); + }); + + it('CONTROL: a kept row that carries nothing is not written, so the seal does not hold it', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([formRow(WORKSPACE, { enabled: true })], { ships, sealedFormShippers: sealedBy })); + expect(census.forms.map((f) => [f.outcome, 'carries' in f ? f.carries : undefined])).toEqual([['keep', undefined]]); + }); + + it('CONTROL: the same row where no package ships a `form` item of the name moves into the pair', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + sealedFormShippers: () => [], + })); + expect(census.forms.map((f) => [f.outcome, destinationOf(f)])).toEqual([['move', { kind: 'pair_form', base: OTHER, pair: `${OTHER}.custom` }]]); + }); + + it('CONTROL: a declared override is written as the pair\'s own row and meets no seal, so the base shipping the name as a `form` item moves it', () => { + const census = planStoredForms(input([viewFormRow(PAIR, { enabled: false, overrides: BASE })], { + sealedFormShippers: (name) => (name === NAME ? [BASE] : []), + })); + expect(census.forms.map((f) => [f.outcome, (destinationOf(f) as { kind?: string } | undefined)?.kind])).toEqual([['move', 'pair_override']]); + expect(census.precheck.canSwitch).toBe(true); + }); + }); + it('move (ruling 7250977204): a pair\'s declared override of a base that ships no form of the name becomes the pair\'s own form — the door is not asked', () => { const census = planStoredForms(input([viewFormRow(PAIR, { enabled: true, overrides: BASE })], { ships: {}, @@ -618,6 +729,18 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr } }); + it('a hold stands where no door serves the row today: the pair\'s own item no door serves still claims the slot a row is planned into, and both hold the upgrade (ruling record 7265816895)', () => { + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: true }), viewFormRow(SUITE, { enabled: false })], { + ...over(), + servedToday: (name: string, packageId: string | undefined) => !(name === NAME && packageId === SUITE_PAIR), + })); + expect(census.forms.map((f) => [f.address, f.served.packageId, f.outcome]).sort()).toEqual([ + [{ kind: 'base', packageId: MODULE }, SUITE, 'hold'], + [{ kind: 'package', packageId: SUITE_PAIR }, SUITE_PAIR, 'hold'], + ].sort()); + expect(census.precheck.canSwitch).toBe(false); + }); + it('the pair\'s own row of the name, read at the pair\'s own address, claims the slot too: beside a row planned into that pair, both hold the upgrade (ruling record 7265816895)', () => { // The pair's own item, declaring no `overrides`: an old-shape `view` row, and a stored `form` row. for (const own of [viewFormRow(SUITE_PAIR, { enabled: true }), formRow(SUITE_PAIR, { enabled: true })]) { @@ -1060,3 +1183,79 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr expect(two.precheck.canSwitch).toBe(true); }); }); + +describe('[ADR-0159 D7-d] the fold\'s "closed today" reading, and the pair\'s own item with no `basedOn` (PR 2 of the card)', () => { + it('N4: a `view` row a `form` row outranks at its place is the row the `view` list serves: its withdrawal closes the form today, and the fold does not name it newly closed', () => { + const census = planStoredForms(input([formRow(undefined, { enabled: true }), viewFormRow(undefined, { enabled: false })])); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + served: expect.objectContaining({ type: 'form' }), + behind: [expect.objectContaining({ type: 'view', withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + newlyClosed: false, + })]); + }); + + it('N4 control: a second `view` row behind the first is read by no layer, and its withdrawal closes the form newly', () => { + const census = planStoredForms(input([formRow(undefined, { enabled: true }), viewFormRow(BASE, { enabled: true }), viewFormRow(undefined, { enabled: false })])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', newlyClosed: true }); + }); + + describe('N16, at a base that ships the form', () => { + const SUITE = 'com.acme.suite'; + const SUITE_PAIR = 'com.acme.suite.custom'; + const manifests: Record }> = { + [SUITE]: { type: 'app' }, + [BASE]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [PAIR]: {}, + }; + const over = { + installed: (id: string) => manifests[id], + isWritable: (pkg: string) => pkg === PAIR || pkg === SUITE_PAIR, + pairFix: (): PairFixReading => ({ ok: true, pair: SUITE_PAIR, basedOn: '1.0.0' }), + }; + + it('a second pair\'s override that withdraws the form is read today in that pair\'s own layer: carried, not newly closed', () => { + const census = planStoredForms(input([ + viewFormRow(SUITE_PAIR, { enabled: true, overrides: BASE }), + viewFormRow(PAIR, { enabled: false, overrides: BASE }), + ], over)); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + served: expect.objectContaining({ packageId: SUITE_PAIR }), + behind: [expect.objectContaining({ packageId: PAIR, withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + newlyClosed: false, + })]); + }); + }); + + it('N14: a row bound to a package that ships no form of the name moves into the pair as its own item where the base records no version (no `basedOn` is declared); a declared override still holds there', () => { + const noVersion: PairFixReading = { ok: false, cause: 'app_author', refusal: 'no version', app: BASE, pairWithoutBasedOn: PAIR }; + const own = planStoredForms(input([viewFormRow(BASE, { enabled: true })], { ships: {}, pairFix: () => noVersion })); + expect(own.forms).toEqual([expect.objectContaining({ outcome: 'move', destination: { kind: 'pair_form', base: BASE, pair: PAIR } })]); + expect(own.precheck.canSwitch).toBe(true); + const declared = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { pairFix: () => noVersion })); + expect(declared.forms).toEqual([expect.objectContaining({ outcome: 'hold', cause: 'app_author', refusal: 'no version' })]); + expect(declared.precheck.canSwitch).toBe(false); + }); +}); + +describe('[ADR-0159 D7-c] N5: where no pair id can be derived, the refusal is the planner\'s own sentence, with no raw reason code', () => { + const engineOf = (packages: Array<{ id: string; type?: string; dependencies?: Record }>) => ({ + registry: { getAllPackages: () => packages.map((m) => ({ manifest: { version: '1.0.0', ...m } })), getPackage: () => undefined }, + }); + for (const [base, words] of [ + ['com.example.forms.custom', 'is itself a paired customization package'], + ['Not A Package Id', 'is not a valid package id'], + ] as const) { + it(`base '${base}': the sentence names why, in words`, () => { + const fix = storedFormPairFix(engineOf([]) as never, base); + expect(fix.ok).toBe(false); + const refusal = (fix as Extract).refusal; + expect(refusal).toContain(words); + expect(refusal).not.toMatch(/base_[a-z_]+/); + }); + } +}); diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts index b43f1e14adc..b3b36c0a543 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -80,7 +80,12 @@ * D7-e: a row that stands over a linked base is never listed for removal). * Not counted. * - `hold` — the move needs the base's pair and the pair cannot be ensured - * (D7-c). Counted: the upgrade does not switch. The hold names the cause, + * (D7-c). Counted: the upgrade does not switch. So does a move whose + * destination row the store seals (ADR-0131 D6): every destination but a + * declared override is written as an edit of the item a package ships at + * the name, and a managed package that ships the name as a `form` item + * seals it, so the census holds the row the run could not write + * ({@link sealedDestinationHold}). The hold names the cause, * repeats the ensure door's refusal, and gives the action for its cause. * A slot of a pair that more than one plan claims holds too, at every * claimant's address, the row named once ({@link holdContestedPairSlots}; @@ -96,7 +101,11 @@ * the served row carries no form at the name (a list, D7-d: every row of * the name at the address stays as stored; a list alone over a base that * ships the form is reported too), or the served row is internal and a row - * behind it declares a link ({@link INTERNAL_AHEAD_OF_LINKED_ROW}). + * behind it declares a link ({@link INTERNAL_AHEAD_OF_LINKED_ROW}), or the + * plan would move a form no door serves today (`served_by_no_door`: the + * effective `form` read lists no form of the name at the address; the + * plan is made first, so a hold it takes part in stands, and its move is + * then left in place, whatever package the row is bound to). * * A body the projection cannot read (D6 rule 7) holds the upgrade wherever it * stands (D7-c, `unreadable`), and an address whose served row is one waits @@ -117,7 +126,7 @@ * input): no write, no registry mutation. */ -import { pairOf, pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; +import { pairOf, pairsOf, type InstalledManifestLookup, type PairOfRefusal } from '@objectstack/metadata-core'; import { deriveViewContainerObject } from '@objectstack/spec'; import { customizationBasePackageId, @@ -135,6 +144,7 @@ import { installedManifestsOfEngine } from './installed-manifests.js'; import { customizationPairEnsureRefusal, kernelPackageScope, type PairRegistry } from './protocol-customization-package.js'; import { orderedFormRowsAt, + readEffectiveForms, storedFormPlaces, type FormReadHost, type OrderedFormRow, @@ -204,7 +214,14 @@ export type StoredFormLeftReason = /** {@link INTERNAL_AHEAD_OF_LINKED_ROW}. */ | 'internal_ahead_of_linked_row' /** The served row is a body the projection cannot read: the address waits on its hold. */ - | 'served_unreadable'; + | 'served_unreadable' + /** + * A form no door serves today is left in place by the upgrade: the + * effective `form` read lists no form of the name at the address the plan + * is made at ({@link StoredFormPlanInput.servedToday}). Not a withdrawn + * form, which the read lists switched off and D7 moves with its switch. + */ + | 'served_by_no_door'; /** A folded row's withdrawal the destination carries (D7-d). */ export interface StoredFormCarriedWithdrawal { @@ -355,6 +372,13 @@ export type PairFixReading = readonly app?: string; /** The per-package pair an earlier version created that holds the namespace (ADR-0146 D3, merge question 12). */ readonly earlierPair?: boolean; + /** + * The pair the door would ensure, where the only refusal is the base + * recording no version: a declared override has no `basedOn` to + * declare, while the pair's own `form` item declares none and moves + * (N14). + */ + readonly pairWithoutBasedOn?: string; }; /** The hold causes the pair door's refusal can carry. */ @@ -370,6 +394,19 @@ export interface StoredFormPlanInput { /** Every name a `type: 'form'` action opens, anywhere it is declared. */ readonly actionTargets: ReadonlySet; readonly pairFix: (base: string) => PairFixReading; + /** + * [ADR-0131 D6] The managed packages that ship `name` as a `form` item, + * where the store seals a `form` row of the name against a write as that + * item's edit; `[]` where it does not. Read as the run's write meets it + * ({@link storedFormSealedShippers}). + */ + readonly sealedFormShippers: (name: string) => readonly string[]; + /** + * Whether the effective `form` read the doors take their candidates from + * ({@link readEffectiveForms}) lists a form of `name` at `packageId` today + * (`undefined`: the environment's own address). + */ + readonly servedToday: (name: string, packageId: string | undefined) => boolean; readonly objectHasFieldGroups: (object: string) => boolean; /** The stored `view` bodies the projection cannot read. */ readonly unreadable: readonly { readonly type: string; readonly name: string; readonly packageId?: string; readonly reason: string; readonly links: readonly string[] }[]; @@ -1207,6 +1244,8 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { addresses.some((other) => other !== here && rowsAt.get(addressKey(other))?.[0]?.place === place); const plansOfName: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[] = []; + /** The addresses (by their rows) whose served row no door serves today. */ + const unservedAt = new Set(); for (const address of addresses) { const rows = rowsAt.get(addressKey(address))!; // An address where no row holds a form at the name has nothing to @@ -1254,6 +1293,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { ? first!.place.packageId === address.packageId : first!.place.packageId === undefined)); + // A form no door serves today is left in place by the upgrade + // (ADR-0159 D7, ruling record 7277149723): every plan that would + // move a row asks the effective `form` read whether it + // lists a form of the name at the address the plan is made at. The + // plan is still made, so a hold it takes part in stands; a move of + // it is left in place once every hold is read. + if (!atDestination && !input.servedToday(name, address.kind === 'environment' ? undefined : address.packageId)) { + unservedAt.add(rows); + } + if (!atDestination) { const internal = isInternal(first!, name, address, input, shipped); if (INTERNAL_AHEAD_OF_LINKED_ROW.applies(internal, behind)) { @@ -1283,6 +1332,19 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { }); continue; } + // A form no door serves today is left in place before the pair + // door's hold (D7-c) or the store's seal is read: neither is a + // hold the rule keeps standing for it (ADR-0159 D7). + if (unservedAt.has(rows) && (destination.kind === 'hold' || sealedDestinationHold(name, served, destination, input) !== undefined)) { + push({ ...base, outcome: 'left_in_place', reason: 'served_by_no_door' }); + continue; + } + const sealedBy = sealedDestinationHold(name, served, destination, input); + if (sealedBy !== undefined) { + push({ ...base, outcome: 'hold', cause: sealedBy.cause, refusal: sealedBy.refusal, action: sealedBy.action }); + holds.push(sealedBy); + continue; + } if (destination.kind === 'hold') { const action = storedFormHoldAction(destination.cause, { base: (address as { packageId: string }).packageId, @@ -1299,7 +1361,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { push({ ...base, outcome: 'keep', destination: keptDestination(address, first!), ...foldOf(first!, rest, served, behind, address, folded) }); continue; } - push({ ...base, outcome: atDestination ? 'keep' : 'move', destination, ...foldOf(first!, rest, served, behind, address, folded) }); + const fold = foldOf(first!, rest, served, behind, address, folded); + // A kept row the run writes (it carries a withdrawal) meets the + // store's seal the same way a moved row does (ADR-0131 D6). + const sealedKeep = atDestination && fold.carries !== undefined ? sealedDestinationHold(name, served, destination, input, 'kept') : undefined; + if (sealedKeep !== undefined) { + push({ ...base, outcome: 'hold', cause: sealedKeep.cause, refusal: sealedKeep.refusal, action: sealedKeep.action }); + holds.push(sealedKeep); + continue; + } + push({ ...base, outcome: atDestination ? 'keep' : 'move', destination, ...fold }); } const kept = keptRowsOf(plansOfName); @@ -1325,6 +1396,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { }; }); + // A form no door serves today is left in place by the upgrade: a move + // of it writes nothing (a hold it takes part in stands; the removal of + // an internal record form, which no public door serves by design, is + // ruling 3's and stays). + plansOfName.forEach(({ plan, rows }, index) => { + if (!unservedAt.has(rows) || plan.outcome !== 'move') return; + const { form, address, served, behind, untouched, alsoReadAt } = plan; + plansOfName[index] = { plan: { form, address, served, behind, untouched, alsoReadAt, outcome: 'left_in_place', reason: 'served_by_no_door' }, rows }; + }); + // Each plan names the rows another address reads too, and what it does. for (const { plan, rows } of plansOfName) { const elsewhere: StoredFormElsewhere[] = []; @@ -1411,10 +1492,44 @@ function pairFormDestination( if (ownPair !== undefined) return { kind: 'pair_form', base, pair: ownPair }; if (address.kind === 'package') return { kind: 'pair_form', base, pair: address.packageId }; const fix = input.pairFix(base); - if (!fix.ok) return holdOf(fix); + // [N14] The pair's own item declares no `basedOn`: a base that records no version holds no such move. + if (!fix.ok) return fix.pairWithoutBasedOn !== undefined ? { kind: 'pair_form', base, pair: fix.pairWithoutBasedOn } : holdOf(fix); return { kind: 'pair_form', base, pair: fix.pair }; } +/** + * [ADR-0131 D6] The hold of a plan that writes a destination row the store + * seals: a move, or a kept row that carries a withdrawal. The run writes every + * destination but a declared override (ADR-0146 D2, a runtime write) as an + * edit of the item a package ships at the name, and the store refuses that + * write on a `form` a managed package ships: the census reads the same seal, + * so the row holds here instead of failing the run. The cause is in the + * shipping package, its author's to remove. + */ +function sealedDestinationHold( + name: string, + served: StoredFormRowRef, + destination: DestinationReading, + input: Pick, + plan: 'moved' | 'kept' = 'moved', +): StoredFormHold | undefined { + if (destination.kind === 'hold' || destination.kind === 'pair_override') return undefined; + const shippers = input.sealedFormShippers(name); + if (shippers.length === 0) return undefined; + const quoted = shippers.map((id) => `'${id}'`).join(' and '); + const into = destination.kind === 'pair_form' ? `'${destination.pair}'` : destination.kind === 'package_form' ? `'${destination.packageId}'` : 'the environment'; + return { + row: served, + cause: 'app_author', + refusal: (plan === 'moved' + ? `The ${rowWords(served)} would move into ${into} as a \`form\` row '${name}'` + : `The ${rowWords(served)} is a \`form\` row '${name}' kept in ${into} that would be written to carry a withdrawal`) + + `, and ${quoted} ${shippers.length > 1 ? 'ship' : 'ships'}` + + ` a \`form\` item of that name: a managed package's item is sealed against every write onto it (ADR-0131 D6), so the row cannot be written there.`, + action: `The cause is in ${quoted}, its author's to remove. ${NO_MEASURED_EXIT}`, + }; +} + /** The destination of a stored `form` override kept where it stands, when the pair door refuses an ensure now. */ function keptDestination(address: StoredFormAddress, served: OrderedFormRow): StoredFormDestination { const overrides = isRecord(served.place.entry.data) ? served.place.entry.data.overrides : undefined; @@ -1480,8 +1595,18 @@ function foldOf( const forms = rest.filter((row) => row.holding.kind === 'form'); let layer: StoredFormPlace | undefined; if (address.kind === 'base' && first.overrideOf !== undefined) layer = rest.find((row) => row.overrideOf === undefined && !folded.has(row.place))?.place; + // [N4] Behind a served `form` row, the first `view` row is the row the + // effective `view` list serves here, the `form` row being no row of that + // type: its withdrawal closes the form today. + const firstOfItsType = (row: OrderedFormRow): boolean => + first.place.type === 'form' && row.place.type === 'view' && rest.find((r) => r.place.type === 'view') === row; + // [N16] A declared override in another pair of the base than the served + // one's is read today in that pair's own per-package layer. + const ownPairLayer = (row: OrderedFormRow): boolean => + first.overrideOf !== undefined && row.overrideOf !== undefined && row.place.packageId !== first.place.packageId; const closesToday = behind.some((row, i) => row.withdraws !== undefined - && (forms[i]?.place === layer || forms[i]?.moved !== undefined || folded.get(forms[i]!.place) === true)); + && (forms[i]?.place === layer || forms[i]?.moved !== undefined || folded.get(forms[i]!.place) === true + || firstOfItsType(forms[i]!) || ownPairLayer(forms[i]!))); // The address that closes is the kept body's: it keeps its own link and switches it off. return { carries: { slug: served.link, from }, newlyClosed: !closesToday }; } @@ -1505,7 +1630,33 @@ function sharedSlugsOf(places: readonly StoredFormPlace[]): StoredFormCensus['sh // ── The host reading ──────────────────────────────────────────────────────── /** The host members the census reads. */ -export type StoredFormCensusHost = FormReadHost & Pick; +export type StoredFormCensusHost = FormReadHost & Pick; + +/** + * [ADR-0131 D6] The managed packages that ship `name` as a `form` item, where + * the store seals a `form` row of the name: the predicate the protocol's doors + * ask ({@link ProtocolHost.isSealedManagedItem}), read for the census as the + * run's write meets it at the store. `[]` where nothing seals it. + */ +function storedFormSealedShippers(host: Pick, name: string): string[] { + if (!host.isSealedManagedItem('form', name)) return []; + const ids = host.shippedArtifactsOf('form', name) + .map((a) => (a as { _packageId?: unknown } | null)?._packageId) + .filter((id): id is string => typeof id === 'string' && id !== ''); + const sorted = [...new Set(ids)].sort(); + return sorted.length > 0 ? sorted : ['a managed package']; +} + +/** + * [N5] Why no pair id can be derived from a base, in the planner's own words: + * one clause per reason `pairOf` gives, never the raw reason code. + */ +const PAIR_ID_REFUSAL_WORDS: Readonly> = { + no_single_app: 'declares several Apps and its namespace picks none', + base_id_missing: 'has no package id', + base_is_customization_package: 'is itself a paired customization package, and a pair has no pair of its own', + base_id_invalid: 'is not a valid package id, and the pair\'s id is derived from it', +}; /** * [ADR-0159 D7-c] Whether `base`'s pair can be ensured for the move, read @@ -1520,9 +1671,7 @@ export function storedFormPairFix(engine: ProtocolHost['engine'], base: string): return { ok: false, cause: 'app_author', - refusal: pairId.reason === 'no_single_app' - ? `Package '${base}' declares several Apps and its namespace picks none, so it has no paired customization package (ADR-0146 D3).` - : `Package '${base}' has no paired customization package: ${pairId.reason} (ADR-0146 D3).`, + refusal: `Package '${base}' ${PAIR_ID_REFUSAL_WORDS[pairId.reason]}, so it has no paired customization package (ADR-0146 D3).`, }; } const pair = pairId.value; @@ -1558,7 +1707,10 @@ export function storedFormPairFix(engine: ProtocolHost['engine'], base: string): } const basedOn = registry.getPackage(base)?.manifest?.version; if (typeof basedOn !== 'string' || basedOn === '') { - return { ok: false, cause: 'app_author', refusal: `Package '${base}' records no version, so an override of it has no \`basedOn\` to declare (ADR-0146 D2).`, app: appId }; + return { + ok: false, cause: 'app_author', app: appId, pairWithoutBasedOn: pair, + refusal: `Package '${base}' records no version, so an override of it has no \`basedOn\` to declare (ADR-0146 D2).`, + }; } return { ok: true, pair, basedOn }; } @@ -1585,6 +1737,15 @@ function collectFormActionTargets(value: unknown, out: Set, depth = 0): export async function listStoredForms(host: StoredFormCensusHost): Promise { const places = await storedFormPlaces(host); const installed = installedManifestsOfEngine(host.engine); + // The forms the read serves today, by package and name: the list the doors read. + const servedNow = new Set(); + const servedNames = new Set(); + for (const item of await readEffectiveForms(host, { type: 'form' }, 'served')) { + const { name, _packageId: packageId } = (item ?? {}) as { name?: unknown; _packageId?: unknown }; + if (typeof name !== 'string') continue; + servedNames.add(name); + if (typeof packageId === 'string') servedNow.add(`${packageId}\u0000${name}`); + } const registry = (host.engine as unknown as { registry?: { listItems?: (type: string) => unknown[] } }).registry; const list = (type: string): unknown[] => { try { @@ -1661,6 +1822,9 @@ export async function listStoredForms(host: StoredFormCensusHost): Promise host.isWritablePackage(packageId), actionTargets, pairFix: (base) => storedFormPairFix(host.engine, base), + sealedFormShippers: (name) => storedFormSealedShippers(host, name), + // The environment's own address: a package-less row the read seats in a package's slot is served there (#21817). + servedToday: (name, packageId) => (packageId === undefined ? servedNames.has(name) : servedNow.has(`${packageId}\u0000${name}`)), objectHasFieldGroups: (object) => { const groups = (objects.get(object) as { fieldGroups?: unknown } | undefined)?.fieldGroups; return Array.isArray(groups) ? groups.length > 0 : isRecord(groups) && Object.keys(groups).length > 0; diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index 82aa729b9d2..7eed9f46409 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -38,7 +38,7 @@ // The trace, measured on `origin/main` — all four routes fold at the producer // --------------------------------------------------------------------------- // `applyObjectRegistryMutation` has exactly ONE caller -// (`applyRegistryWriteThrough`), which has exactly NINE (the orphan +// (`applyRegistryWriteThrough`), which has exactly TEN (the orphan // adoption's, `reassignOrphanedMetadata`, retired with its door, #38150): // // 1. `saveMetaItem` passes `singularTypeForRepo`, and the method @@ -79,6 +79,11 @@ // 9. `undoLanded` (#38150) passes the same folded type: it writes back // through each loose row a refused move put // back with no transaction to cover it. +// 10. `healStoredFormRows` (ADR-0159 D7) passes the literal `'form'` for +// each copy the stored-form ceremony wrote, +// and for a container it re-saved the type of +// the stored row it read under the literal +// `'view'`, so no stored spelling reaches it. // // Both fold maps resolve the plural — `PLURAL_TO_SINGULAR.objects === 'object'` // and `canonicalMetaUrlType('objects') === 'object'` — so no route can deliver @@ -588,9 +593,9 @@ describe('[#8862] the `applyRegistryWriteThrough` caller set stays closed', () = const sources = [source, ...SPLIT_MODULES.map((file) => readFileSync(fileURLToPath(new URL(`./${file}`, import.meta.url)), 'utf8'))]; const sitesOf = (pattern: RegExp) => sources.flatMap((text) => text.match(pattern) ?? []); - it('has exactly nine call sites, all traced in this file’s header', () => { + it('has exactly ten call sites, all traced in this file’s header', () => { const callSites = sitesOf(/\b(?:this|host)\.applyRegistryWriteThrough\(/g); - expect(callSites).toHaveLength(9); + expect(callSites).toHaveLength(10); }); it('`applyObjectRegistryMutation` is reached only through the write-through', () => { diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index 4b9177762a5..536cca00b43 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -156,7 +156,7 @@ type Route = * transaction and hands the rows it wrote back: each caller calls `then` * after the commit, and `then` both writes through and heals. */ - | { readonly handedTo: 'module callers'; readonly then: 'healOldShapeFormRowRemovals' }; + | { readonly handedTo: 'module callers'; readonly then: 'healOldShapeFormRowRemovals' | 'healStoredFormRows' }; // [#28355] A door's write lives in its `…Unaudited` body; the public door of the same name // only wraps it with the refusal audit, so the member is the body's name. @@ -184,6 +184,11 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re { member: 'applyOldShapeFormRowRemovals', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, // [ADR-0159 D5] …and the undo of that write on a runtime that cannot roll back puts each row back, healed. { member: 'restoreOldShapeFormRowRemovals', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } }, + // [ADR-0159 D7] The stored-form ceremony's write half: the copies and the old rows it takes, in one + // transaction; its caller heals the registry from the rows handed back, after the commit. + { member: 'writeStoredFormCopies', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, + { member: 'takeStoredFormRows', verb: 'repo.delete(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, + { member: 'takeStoredFormRows', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, ]; /** The verb as `WRITES` spells it: no whitespace after its open paren, [#29985] the class as `this`. */ @@ -289,6 +294,9 @@ describe('[#29985] the census reads the modules the split moved bodies to', () = 'protocol-form-writes.ts: restoreOldShapeFormRowRemovals', 'protocol-package-move-in.ts: undoLanded', 'protocol-packageless-overlay-migration.ts: migratePackagelessOverlays', + 'protocol-stored-form-apply.ts: writeStoredFormCopies', + 'protocol-stored-form-apply.ts: takeStoredFormRows', + 'protocol-stored-form-apply.ts: takeStoredFormRows', ]); }); }); diff --git a/packages/objectql/src/protocol-stored-form-migration.test.ts b/packages/objectql/src/protocol-stored-form-migration.test.ts index d019a72bcc7..a19ea52383f 100644 --- a/packages/objectql/src/protocol-stored-form-migration.test.ts +++ b/packages/objectql/src/protocol-stored-form-migration.test.ts @@ -31,7 +31,7 @@ import './__fixtures__/lint-root-preload.testkit.js'; import { describe, expect, it } from 'vitest'; import type { ServiceObject } from '@objectstack/spec/data'; -import { ObjectStackProtocolImplementation, listStoredFormsOf } from '@objectstack/metadata-protocol'; +import { ObjectStackProtocolImplementation, applyStoredFormsOf, listStoredFormsOf } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; import { ObjectQL } from './engine.js'; @@ -171,7 +171,7 @@ async function boot() { } as any); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); const snapshot = () => JSON.stringify([...(stores.get('sys_metadata')?.values() ?? [])]); - return { engine, protocol, snapshot }; + return { engine, protocol, snapshot, stores }; } /** @@ -383,14 +383,16 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr newlyClosed: false, })]); }); - it('ruling record 7250977204 stands for every row its premise holds for: the read serves the row at the package it is bound to, and the census plans it there', async () => { + it('ruling record 7250977204 stands for every row its premise holds for: the read serves the row at the package it is bound to, and the census plans it there; the module ships the name as a `form` item, so the pair\'s own row is sealed (ADR-0131 D6) and the row holds there', async () => { const { engine, protocol } = await bootSuite({ moduleAs: 'form' }); await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Stored' }, SUITE); // The read today: the stored body under the App it is bound to, the module's own form at the module. expect((await servedForms(protocol)).sort()).toEqual([[SUITE, 'Stored'], [MODULE, 'Shipped form']]); - expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.outcome, f.destination])).toEqual([ - [SUITE, SUITE, 'move', { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }], + const plans = await plansOf(protocol); + expect(plans.map((f) => [f.address.packageId, f.served.packageId, f.outcome, 'cause' in f ? f.cause : undefined])).toEqual([ + [SUITE, SUITE, 'hold', 'app_author'], ]); + expect((plans[0] as { refusal?: string }).refusal).toContain(`'${MODULE}'`); }); it('a stored `form` row the read serves at the package it is bound to is planned there', async () => { @@ -412,15 +414,16 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr ]); expect(result.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: SUITE }, cause: 'app_author' }] }); }); - it('a member of a stored container is read at the package the container is bound to: the read serves the module\'s shipped form at the module, and the census plans the member at its own address', async () => { + it('a member of a stored container is read at the package the container is bound to: the read serves the module\'s shipped form at the module, and the census plans the member at its own address; a form no door serves today is left in place by the upgrade', async () => { const { engine, protocol } = await bootSuite({ appOwnsObject: true, moduleForm: {} }); await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, { layout: 'horizontal' }) } }, SUITE); // The read today: one form of the name, the module's own, under the module. const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items.filter((item: any) => item?.name === SUITE_NAME); expect(served.map((item: any) => [item._packageId, item.layout])).toEqual([[MODULE, undefined]]); expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.served.grain, f.outcome, f.destination])).toEqual([ - [SUITE, SUITE, 'expansion', 'move', { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }], + [SUITE, SUITE, 'expansion', 'left_in_place', undefined], ]); + expect((await plansOf(protocol))[0]).toMatchObject({ reason: 'served_by_no_door' }); }); it('the pair\'s own row of the name, beside a row the census plans into that pair: today the module serves the bound row and the pair\'s own per-package layer reads its own row, and the census holds the upgrade at both (ruling record 7265816895)', async () => { @@ -577,3 +580,285 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr }); } }); + +/** + * [ADR-0159 D7; ruling records 7142585849 (items 2 and 3) and 7250977204] The + * ceremony's write half over the real protocol: `applyStoredFormsOf`, the + * `--apply` the major's upgrade command calls. The move, the fold, the + * removal, all or nothing with the switch, and a second run that moves + * nothing. + */ +describe('[ADR-0159 D7] applyStoredForms over the real protocol', () => { + const LIST_BODY = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; + const stored = async (engine: ObjectQL, type: string, name: string): Promise> => + ((await engine.find('sys_metadata', { where: { type, name, state: 'active' } }, { context: { isSystem: true } })) as any[]) + .map((r) => ({ packageId: r.package_id ?? null, body: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata })); + const formsAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise> => + ((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === name) + .map((item: any) => [item._packageId, item.sharing?.enabled]); + const apply = (protocol: ObjectStackProtocolImplementation): Promise => applyStoredFormsOf(protocol, { actor: null }); + + it('moves a package-less old-shape row over the base\'s linked form into the pair as its declared override, deletes the old row once the copy reads back, and a second run moves nothing', async () => { + const { engine, protocol, snapshot } = await boot(); + await storeRow(engine, NAME, viewItem(NAME, OBJECT, sharing(false))); + // The read today: the base's linked form, switched off by the stored row. + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + const result = await apply(protocol); + expect(result).toMatchObject({ + applied: true, + pairsEnsured: [PAIR], + written: [{ form: NAME, row: { type: 'form', name: NAME, packageId: PAIR }, destination: { kind: 'pair_override', base: BASE, pair: PAIR, basedOn: '1.2.0' } }], + removed: [], + rowsChanged: [{ type: 'view', name: NAME, change: 'deleted' }], + }); + expect(await stored(engine, 'view', NAME)).toEqual([]); + const [moved] = await stored(engine, 'form', NAME); + expect(moved).toMatchObject({ packageId: PAIR, body: { name: NAME, overrides: { package: BASE, basedOn: '1.2.0' }, sharing: { publicLink: `/forms/${SLUG}`, enabled: false } } }); + // The address answers as before: the form, switched off. + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + // Idempotent: the second run finds the row at its destination and writes nothing. + const after = snapshot(); + const again = await apply(protocol); + expect(again).toMatchObject({ applied: true, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }); + expect(again.census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['keep']); + expect(snapshot()).toBe(after); + }); + + it('a container with lists and forms: the internal record form is removed, the public one moves, and the container is re-saved with its list byte-equal', async () => { + const { engine, protocol } = await boot(); + await storeRow(engine, OBJECT, { + name: OBJECT, object: OBJECT, list: LIST_BODY, + form: formBody(OBJECT, { label: 'Edited' }), formViews: { contact: formBody(OBJECT, sharing(false)) }, + }); + const result = await apply(protocol); + expect(result.applied).toBe(true); + expect(result.removed).toEqual([expect.objectContaining({ + form: `${OBJECT}.form`, object: OBJECT, objectHasFieldGroups: false, + body: expect.objectContaining({ label: 'Edited' }), + })]); + expect(result.written.map((w: any) => [w.form, w.row.packageId])).toEqual([[NAME, PAIR]]); + expect(result.rowsChanged).toEqual([{ type: 'view', name: OBJECT, change: 'resaved' }]); + const [container] = await stored(engine, 'view', OBJECT); + expect(container!.body).toEqual({ name: OBJECT, object: OBJECT, list: LIST_BODY }); + expect(JSON.stringify(container!.body.list)).toBe(JSON.stringify(LIST_BODY)); + expect((await apply(protocol))).toMatchObject({ written: [], removed: [], rowsChanged: [] }); + }); + + it('an item-shaped internal record form is deleted, its body in the report, and no history row is rewritten', async () => { + const { engine, protocol } = await boot(); + const name = `${OBJECT}.form`; + await storeRow(engine, name, { name, object: OBJECT, viewKind: 'form', isDefault: true, label: 'Internal', config: formBody(OBJECT, { label: 'Internal' }) }); + await engine.insert('sys_metadata_history', { + id: 'h_seed', type: 'view', name, organization_id: null, package_id: null, version: 1, + metadata: JSON.stringify({ name, label: 'Older' }), checksum: 'seed', operation_type: 'create', recorded_at: '2026-01-01T00:00:00.000Z', + }, { context: { isSystem: true } }).catch(() => undefined); + const historyBefore = JSON.stringify(((await engine.find('sys_metadata_history', {}, { context: { isSystem: true } })) as any[]).filter((r) => r.id === 'h_seed')); + const result = await apply(protocol); + expect(result.removed).toEqual([expect.objectContaining({ form: name, object: OBJECT, body: expect.objectContaining({ label: 'Internal' }) })]); + expect(result.rowsChanged).toEqual([{ type: 'view', name, change: 'deleted' }]); + expect(await stored(engine, 'view', name)).toEqual([]); + expect(await stored(engine, 'form', name)).toEqual([]); + expect(JSON.stringify(((await engine.find('sys_metadata_history', {}, { context: { isSystem: true } })) as any[]).filter((r) => r.id === 'h_seed'))).toBe(historyBefore); + }); + + it('all or nothing: beside a row that holds the upgrade, nothing is written and no pair is ensured; with the cause removed, every row moves (ablate: move what can be moved and report the rest)', async () => { + const { engine, protocol, snapshot } = await boot(); + await storeRow(engine, NAME, viewItem(NAME, OBJECT, sharing(false))); + const broken = `${OBJECT}.broken`; + await storeRow(engine, broken, { name: broken, viewKind: 'form', ...sharing(true) }); + const before = snapshot(); + const held = await apply(protocol); + expect(held).toMatchObject({ applied: false, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }); + expect(held.census.precheck.canSwitch).toBe(false); + expect(held.census.precheck.holds).toEqual([expect.objectContaining({ cause: 'unreadable', row: expect.objectContaining({ name: broken }) })]); + expect(snapshot()).toBe(before); + expect((engine.registry as any).getPackage(PAIR)).toBeUndefined(); + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + // The cause removed (the unreadable row gone), the run moves every row. + await protocol.deleteMetaItem({ type: 'view', name: broken } as any); + const moved = await apply(protocol); + expect(moved).toMatchObject({ applied: true, written: [{ form: NAME, row: { packageId: PAIR } }] }); + expect(await stored(engine, 'view', NAME)).toEqual([]); + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + }); +}); + +/** + * [ADR-0159 D7; ruling records 7265816895 (step 5), 7249158572] A row the + * census holds: `--apply` writes nothing, every stored row byte-equal, and + * every address of the name serves what it served before the refused run. + * Each shape is a held-row shape the census pins above name; the last two are + * the engine half of the planner's pins of a row kept as stored behind an + * internal form (S14), and the third-address shape. + */ +describe('[ADR-0159 D7] a held row: applyStoredForms writes nothing at any address', () => { + /** Every effective `form` item of `name`: the package it is served under, and its body. */ + const servedAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise => + JSON.stringify(((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === name) + .map((item: any) => [item._packageId, item]) + .sort((a: any, b: any) => String(a[0]).localeCompare(String(b[0])))); + const declaring = (base: string) => ({ overrides: { package: base, basedOn: '3.0.0' } }); + /** Run `--apply` over a held store: refused, nothing written, both the store and every address as before. */ + const refusedRun = async (protocol: ObjectStackProtocolImplementation, snapshot: () => string, name: string, holdsAt: number) => { + const before = snapshot(); + const served = await servedAt(protocol, name); + const plans = (await census(protocol)).forms.filter((f: any) => f.form === name); + expect(plans.filter((f: any) => f.outcome === 'hold')).toHaveLength(holdsAt); + const result = await applyStoredFormsOf(protocol, { actor: null }); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(result.census.precheck.canSwitch).toBe(false); + expect(snapshot()).toBe(before); + expect(await servedAt(protocol, name)).toBe(served); + return plans; + }; + + it('served at two modules (ruling record 7265816895, step 5)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ second: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + it('served at its own package and at the module (ruling record 7265816895, step 5)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + for (const type of ['view', 'form'] as const) { + it(`a pair slot two plans claim, the pair's own ${type} row beside a row planned into it (ruling record 7265816895, every contested slot)`, async () => { + const { engine, protocol, snapshot } = await bootSuite(); + const own = type === 'view' + ? { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Pair own' } + : { name: SUITE_NAME, object: SUITE_OBJECT, label: 'Pair own', type: 'simple', sections: [{ fields: ['name'] }], ...sharing(true) }; + await storeRow(engine, SUITE_NAME, own, SUITE_PAIR, type); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + } + + it('served at two modules, left in place at one and moved at the other', async () => { + const { engine, protocol, snapshot } = await bootSuite({ second: true, moduleForm: {} }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal override', isDefault: true, ...declaring(SUITE) }, SUITE_PAIR); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Linked' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + it('S14 over the real read: a package-less internal row ahead of a package-less container whose member is linked, kept as stored at one App\'s address, behind the row bound to another App that would move: that move holds, the kept rows listed apart (ruling record 7249158572)', async () => { + const { engine, protocol, snapshot } = await boot(); + registerOther(engine, 'com.example.other', formBody(OBJECT)); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT), label: 'Internal', isDefault: true }); + await storeRow(engine, OBJECT, { name: OBJECT, object: OBJECT, formViews: { contact: formBody(OBJECT, sharing(true)) } }); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT, sharing(true)), label: 'Linked' }, BASE); + const plans = await refusedRun(protocol, snapshot, NAME, 1); + const held = plans.find((f: any) => f.outcome === 'hold'); + expect(held).toMatchObject({ address: { kind: 'base', packageId: BASE }, cause: 'app_author', behind: [] }); + expect(held.heldApart.map((r: any) => [r.packageId, r.grain])).toEqual([[undefined, 'item'], [undefined, 'expansion']]); + expect(held.refusal).toContain('7249158572'); + }); + + it('the third-address shape: a row kept behind an internal form left in place at one address, served and moved at another, the internal row served apart at a third: every plan of the name holds and nothing is written', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true, appOwnsObject: true, moduleForm: {} }); + // A further App that ships the form linked: the package-less internal row is read there too, apart. + engine.registerApp({ + id: 'com.example.other', name: 'other', version: '2.0.0', type: 'app', namespace: 'other', + forms: [{ name: SUITE_NAME, object: SUITE_OBJECT, label: 'Other', type: 'simple', sections: [{ fields: ['name'] }], ...sharing(true) }], + } as any); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal', isDefault: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Linked' }, SUITE); + const plans = await refusedRun(protocol, snapshot, SUITE_NAME, 3); + expect(plans.map((f: any) => [f.address.packageId, f.outcome, f.served?.packageId]).sort()).toEqual([ + ['com.example.other', 'hold', undefined], + [MODULE, 'hold', undefined], + [SUITE, 'hold', SUITE], + ].sort()); + }); +}); + +describe('[ADR-0159 D7, ruling record 7249158572] N33: a container member kept as stored beside a sibling member that moves', () => { + it('the kept member reads back byte-equal after --apply, the moved sibling is gone from the container, and the container keeps nothing else', async () => { + const { engine, protocol } = await bootSuite({ moduleForm: {} }); + const INTAKE = `${SUITE_OBJECT}.intake`; + // At the module: a package-less internal form ahead of the container's linked member, both left in place. + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal', isDefault: true }); + const contact = formBody(SUITE_OBJECT, { label: 'Kept member', ...sharing(true) }); + const intake = formBody(SUITE_OBJECT, { label: 'Moved member', sharing: { publicLink: '/forms/intake-37111', enabled: true, allowAnonymous: true } }); + await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact, intake } }); + const before = (await census(protocol)).forms; + expect(before.filter((f: any) => f.form === SUITE_NAME).map((f: any) => f.outcome)).toEqual(['left_in_place']); + expect(before.filter((f: any) => f.form === INTAKE).map((f: any) => [f.outcome, f.destination])).toEqual([['move', { kind: 'environment_form' }]]); + const result = await applyStoredFormsOf(protocol, { actor: null }); + expect(result.applied).toBe(true); + expect(result.written.map((w: any) => w.form)).toEqual([INTAKE]); + const rows = ((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_OBJECT, state: 'active' } }, { context: { isSystem: true } })) as any[]); + expect(rows).toHaveLength(1); + const kept = JSON.parse(rows[0].metadata); + expect(JSON.stringify(kept.formViews.contact)).toBe(JSON.stringify(contact)); + expect(kept.formViews).not.toHaveProperty('intake'); + // The internal row ahead of it is left in place as well. + expect(((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_NAME, state: 'active' } }, { context: { isSystem: true } })) as any[])).toHaveLength(1); + }); +}); + +describe('[ADR-0159 D7-c, ADR-0146 D3] N13: the pair door\'s refusals and the draft read, through the real protocol', () => { + const switchedOff = { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }; + const planOf = async (protocol: ObjectStackProtocolImplementation) => (await census(protocol)).forms.filter((f: any) => f.form === SUITE_NAME); + + it('control: with the pair\'s namespace free, the row bound to the App moves into the pair', async () => { + const { engine, protocol } = await bootSuite(); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + expect((await planOf(protocol)).map((f: any) => [f.outcome, f.destination?.kind])).toEqual([['move', 'pair_override']]); + }); + + it('the per-package pair an earlier version created for a member of the App holds the namespace: the door\'s 409, read as that pair (administrator, no command on this release), and --apply writes nothing', async () => { + const { engine, protocol, snapshot } = await bootSuite(); + engine.registerApp({ + id: `${MODULE}.custom`, name: 'suite-service-custom', version: '0.1.0', type: 'app', namespace: 'suite_custom', + dependencies: { [MODULE]: '^3.1.0' }, + } as any); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + const [plan] = await planOf(protocol); + expect(plan).toMatchObject({ outcome: 'hold', cause: 'administrator' }); + expect(plan.refusal).toContain('re-identified as the App\'s pair'); + // Read as the earlier pair: the action names no command that clears it. + expect(plan.action).toContain('no command on this release does that'); + const before = snapshot(); + expect(await applyStoredFormsOf(protocol, { actor: null })).toMatchObject({ applied: false, written: [], pairsEnsured: [] }); + expect(snapshot()).toBe(before); + }); + + it('a package outside the App holds the namespace: the door\'s 422, read as the administrator\'s, not as an earlier pair', async () => { + const { engine, protocol } = await bootSuite(); + engine.registerApp({ id: 'com.example.squatter', name: 'squatter', version: '1.0.0', type: 'app', namespace: 'suite_custom' } as any); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + const [plan] = await planOf(protocol); + expect(plan).toMatchObject({ outcome: 'hold', cause: 'administrator' }); + expect(plan.refusal).toContain('already owned by package \'com.example.squatter\''); + expect(plan.action).not.toContain('no command on this release does that'); + expect(plan.action).toContain('Remove the cause the refusal names'); + }); + + it('an old-shape draft is listed, and --apply leaves it as stored (ruling record 7250982640)', async () => { + const { engine, protocol } = await bootSuite(); + await engine.insert('sys_metadata', { + type: 'view', name: SUITE_NAME, organization_id: null, package_id: SUITE, + metadata: JSON.stringify(switchedOff), state: 'draft', version: 1, + }, { context: { isSystem: true } }); + expect((await census(protocol)).drafts).toEqual([{ type: 'view', name: SUITE_NAME, packageId: SUITE }]); + const drafts = async () => ((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_NAME, state: 'draft' } }, { context: { isSystem: true } })) as any[]).map((r) => r.metadata); + const before = await drafts(); + expect((await applyStoredFormsOf(protocol, { actor: null })).applied).toBe(true); + expect(await drafts()).toEqual(before); + }); +}); + +/** A second App and its module, which ships `formViews.contact` on {@link OBJECT} with `contact` as given. */ +function registerOther(engine: ObjectQL, id: string, contact: Record) { + engine.registerApp({ id, name: id.split('.').pop(), version: '2.0.0', type: 'app', namespace: id.split('.').pop() } as any); + engine.registerApp({ + id: `${id}.desk`, name: `${id.split('.').pop()}-desk`, version: '2.1.0', type: 'module', namespace: id.split('.').pop(), + dependencies: { [id]: '^2.0.0' }, + views: [{ object: OBJECT, formViews: { contact } }], + } as any); +} diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 3b6652469e8..7ca5961761f 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -22,7 +22,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; +import { ObjectStackProtocolImplementation, applyStoredFormsOf, listStoredFormsOf, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, @@ -928,6 +928,17 @@ describe('[ADR-0159 card ② item 2, D5, ADR-0029 D9.2a] the `/meta/form` read: const CAP = 'ftt.legal_desk'; const holder = { systemPermissions: [CAP] }; const stranger = { systemPermissions: [] as string[] }; + // The first served `view` read in a worker loads `@objectstack/lint` cold + // (metadata-diagnostics.ts attaches its lint warnings lazily, the cause + // meta-qualified-item-route.test.ts records): ~1s of this file's first such + // read on an idle box, past 5s on a loaded CI runner. It is a one-off load of + // the worker, not part of the read a test below asserts on, so the load is + // taken here, once, and each test's budget is for its own reads. + beforeAll(async () => { + const b = await booted({}); + await b.seedRow('view', NAME, null, viewItem(true)); + expect((await b.meta('view', NAME, holder)).status).toBe(200); + }); it('a caller refused a form\'s document at `/api/v1/meta/view/NAME` is refused it at `/api/v1/meta/form/NAME`; its holder is served both', async () => { // A view item's own audience gate travels with the form it projects. On @@ -1333,3 +1344,453 @@ describe('[#38626] `409 FORM_ADDRESS_TAKEN` carries the holding form as data on expect(answer.details?.holder).toEqual({ name: NAME, packageId: BASE }); }); }); + +/** + * [ADR-0159 D7, card ⑤a "Done when"; ruling records 7142585849, 7250977204, + * 7249158572 and 7265816895] The stored-form ceremony's write half + * (`applyStoredFormsOf`, the `--apply` the major's upgrade command calls), + * through BOTH doors before and after the run: the move, the fold and the + * removal change what no door answers, except a form the report names newly + * closed. Each pin asserts status, `code` and that no record was written + * (`closedOnBothDoors`). The ablation each pin names was run by hand and is + * recorded on the PR. + */ +describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', () => { + const engines: ObjectQL[] = []; + const savedWritable = process.env.OS_METADATA_WRITABLE; + beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; }); + beforeEach(() => { + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + }); + afterAll(async () => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; + else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const apply = (b: Booted): Promise => applyStoredFormsOf(b.protocol, { actor: null }); + /** Every stored row, as the store holds it: the bytes a refused run must leave. */ + const allRows = async (b: Booted) => JSON.stringify(((await b.engine.find('sys_metadata', {}, { context: { isSystem: true } })) as any[]) + .map((r) => [r.type, r.name, r.package_id ?? null, r.state, typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), r.checksum]) + .sort((a, c) => JSON.stringify(a).localeCompare(JSON.stringify(c)))); + const activeBodies = async (b: Booted, type: string, name: string, packageId: string | null) => + (await rawRows(b, type, name, packageId)).map((r) => JSON.parse(r.metadata)); + + /** The record-form slot: a container's default `form`, served as `OBJECT.form`. */ + const DFORM = `${OBJECT}.form`; + const fields = { type: 'simple', sections: [{ fields: ['name', 'email'] }] }; + const switchedOff = { enabled: false, allowAnonymous: true, publicLink: `/forms/${SLUG}` }; + const baseDefaultForm = (sharingBlock: Record | null) => ({ object: OBJECT, form: { ...fields, ...(sharingBlock ? { sharing: sharingBlock } : {}) } }); + const slotItem = (sharingBlock: Record | null, extra: Record = {}) => ({ + name: DFORM, object: OBJECT, viewKind: 'form', isDefault: true, label: 'In the slot', + config: { ...fields, data: { provider: 'object', object: OBJECT }, ...(sharingBlock ? { sharing: sharingBlock } : {}) }, + ...extra, + }); + + for (const listers of [0, 1, 2] as const) { + it(`a package-less form at the environment's own address is served today where the read seats it: with ${listers} package(s) shipping a list of the name, both doors serve it before --apply, it moves into the environment, and both doors serve it after (ablate: read the environment's own address only at the environment)`, async () => { + const b = await booted({}); + for (let i = 0; i < listers; i++) { + b.engine.registerApp({ + id: `com.example.lister37111n${i}`, name: `lister37111n${i}`, version: '1.0.0', namespace: `lsn${i}`, + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + } + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, null, viewItem(true)); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + const answers = await doors(); + expect(answers[0]![0]).toBe(200); + expect(answers[1]![0]).not.toBe(404); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.destination?.kind])).toEqual([ + [{ kind: 'environment' }, 'move', 'environment_form'], + ]); + expect(result).toMatchObject({ applied: true }); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null])).toEqual([[NAME, 'form', null]]); + expect(await doors()).toEqual(answers); + }); + } + + describe('on a database that cannot roll back a transaction, --apply is refused before anything is written', () => { + const bootedNoRollBack = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships, { canRollBack: false }); + engines.push(b.engine); + expect((b.protocol as any).engine.getDriverByName((b.protocol as any).engine.getDefaultDriverName())?.supports?.transactionsUnsupported).toBe(true); + return b; + }; + + it('a row the census moves: the refusal names the driver and what to do, no pair is ensured, every stored row byte-equal, and both doors answer the same before and after (ablate: the refusal of --apply on an engine that cannot roll back)', async () => { + const b = await bootedNoRollBack({}); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const census = await listStoredFormsOf(b.protocol); + expect(census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['move']); + expect(census.precheck.canSwitch).toBe(true); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + const before = await allRows(b); + const answers = await doors(); + const driver = (b.protocol as any).engine.getDefaultDriverName(); + const refused = await apply(b).then(() => undefined, (error: unknown) => error as Error); + expect(refused).toBeInstanceOf(Error); + expect(refused!.message).toContain(`'${driver}' cannot roll back`); + expect(refused!.message).toContain('Nothing was written'); + expect(refused!.message).toContain('supports transactions'); + expect(refused!.message).toContain('os migrate stored-forms'); + expect((b.engine as any).registry?.getPackage?.(PAIR)).toBeFalsy(); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual(answers); + }); + + it('CONTROL: a run with nothing to write or take is not refused there', async () => { + const b = await bootedNoRollBack({ forms: [formItem(true)] }); + const result = await apply(b); + expect(result).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + }); + }); + + it('the switched-off form in a record-form slot, the stored twin: moved with its switch, not listed for removal, closed before and after (ablate: judge "public" by `sharing.enabled === true`)', async () => { + const b = await booted({ views: [baseDefaultForm(sharing(true))] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, slotItem(switchedOff, overrides), DFORM); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(result.removed).toEqual([]); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId])).toEqual([[DFORM, 'form', PAIR]]); + expect(await activeBodies(b, 'form', DFORM, PAIR)).toEqual([expect.objectContaining({ sharing: switchedOff, overrides: overrides.overrides })]); + await closedOnBothDoors(b); + }); + + for (const shape of ['a `.custom` override', 'a package-less row'] as const) { + it(`its twin, the link-less row over an open base, as ${shape}: a \`form\` row with no link, never listed for removal, closed before and after (ablate: class the row by its own body alone)`, async () => { + const b = await booted({ views: [baseDefaultForm(sharing(true))] }); + if (shape === 'a `.custom` override') { + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, slotItem(null, overrides), DFORM); + } else { + await b.seedRow('view', DFORM, null, slotItem(null)); + } + await closedOnBothDoors(b); + const census = (await apply(b)).census; + expect(census.forms.filter((f: any) => f.form === DFORM).map((f: any) => f.outcome)).toEqual(['move']); + const [moved] = await activeBodies(b, 'form', DFORM, PAIR); + expect(moved).toBeDefined(); + expect(moved.sharing).toBeUndefined(); + await closedOnBothDoors(b); + }); + } + + for (const shape of ['a `.custom` switch-only override', 'a member of a stored container'] as const) { + it(`the ceremony keeps a withdrawal closed: withdrawn by ${shape}, the form answers 404 after it, the moved row carries the stored body without the read's provenance, and a second run finds nothing (ablate: the provenance strip; the emptied container's deletion)`, async () => { + const b = await booted({ views: [container(true)] }); + if (shape === 'a `.custom` switch-only override') { + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + } else { + await b.seedRow('view', OBJECT, null, { name: OBJECT, ...container(false) }); + } + await closedOnBothDoors(b); + expect((await apply(b)).applied).toBe(true); + expect(await rawRows(b, 'view', shape === 'a member of a stored container' ? OBJECT : NAME, shape === 'a member of a stored container' ? null : PAIR)).toEqual([]); + // The moved row carries the withdrawal as stored, and none of the provenance the read's expansion wears from the base. + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toMatchObject({ sharing: sharing(false), overrides: overrides.overrides }); + for (const key of ['_packageId', '_packageVersion', '_provenance']) expect(moved).not.toHaveProperty(key); + await closedOnBothDoors(b); + // Idempotent: nothing of the emptied container is left to hold the next run. + expect(await apply(b)).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [] }); + await closedOnBothDoors(b); + }); + } + + it('a `.custom` view override that withdraws a form the base ships as a `form` item: moved into the pair as that form\'s declared override, written as the pair\'s own row and not as an edit of the shipped item, closed before and after (ablate: judge the declared override\'s write as an override of the shipped item)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId, w.destination.kind])).toEqual([[NAME, 'form', PAIR, 'pair_override']]); + expect(await activeBodies(b, 'form', NAME, PAIR)).toEqual([expect.objectContaining({ sharing: sharing(false), overrides: overrides.overrides })]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await closedOnBothDoors(b); + }); + + it('the fold keeps the served body and only narrows: an open override in the pair beside a package-less row that withdraws the form is closed before and after, and the destination keeps its link with the switch off (ablate: the carry of the folded row\'s switch)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(true, overrides)); + await b.seedRow('view', NAME, null, viewItem(false)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.written).toEqual([expect.objectContaining({ form: NAME, switchedOff: SLUG })]); + expect(await activeBodies(b, 'form', NAME, PAIR)).toEqual([expect.objectContaining({ sharing: expect.objectContaining({ publicLink: `/forms/${SLUG}`, enabled: false }) })]); + expect(await rawRows(b, 'view', NAME, null)).toEqual([]); + await closedOnBothDoors(b); + }); + + it('the fold: a link-less row bound to the read-only base, over its open form, beside an open package-less row, is closed before and after, and the pair\'s override has no link (ablate: take the package-less row first)', async () => { + const b = await booted({ views: [container(true)] }); + await b.seedRow('view', NAME, BASE, viewItem(null)); + await b.seedRow('view', NAME, null, viewItem(true)); + await closedOnBothDoors(b); + expect((await apply(b)).applied).toBe(true); + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toMatchObject({ overrides: overrides.overrides }); + expect(moved.sharing).toBeUndefined(); + await closedOnBothDoors(b); + }); + + it('the fold, the writable-base twin: a writable package\'s own open row beside a package-less row that withdraws the form is open before and closed after, and the report names it newly closed (ablate: the report\'s line for a newly closed form)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, viewItem(true)); + await b.seedRow('view', NAME, null, viewItem(false)); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME)).toEqual([expect.objectContaining({ + address: { kind: 'package', packageId: DEPENDENT }, outcome: 'move', newlyClosed: true, + })]); + await closedOnBothDoors(b); + }); + + it('the fold, a writable package\'s list ahead of a package-less form row: closed before and after, no `form` row of the name, the list byte-equal, the row left in place and not holding (ablate: fold the package-less row into the package\'s own `form` row)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + const list = await rawRows(b, 'view', NAME, DEPENDENT); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.census.precheck.canSwitch).toBe(true); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.outcome, f.reason])).toEqual([['left_in_place', 'served_no_form']]); + expect(await rawRows(b, 'form', NAME, DEPENDENT)).toEqual([]); + expect(await rawRows(b, 'view', NAME, DEPENDENT)).toEqual(list); + expect(await rawRows(b, 'view', NAME, null)).toHaveLength(1); + await closedOnBothDoors(b); + }); + + it('the fold, a no-form row ahead of a form row: a list bound to the base, over its open form, beside an open package-less form row, is closed before and after, the pair holds no row of the name (ablate: find the served row among form rows only)', async () => { + const b = await booted({ views: [container(true)] }); + await b.seedRow('view', NAME, BASE, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + const before = await allRows(b); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.census.precheck.canSwitch).toBe(true); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['left_in_place']); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await allRows(b)).toBe(before); + await closedOnBothDoors(b); + }); + + it('the retired form and its successor on one address: both rows are moved as written, not through the `form` save door, the successor answers before and after, and the report names the pair (ablate: move the rows through the `form` save door)', async () => { + const b = await booted({}); + const RETIRED = `${OBJECT}.retired`; + await b.seedRow('view', RETIRED, null, { ...viewItem(false), name: RETIRED, label: 'Retired' }); + await b.seedRow('view', NAME, null, viewItem(true)); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.census.sharedSlugs).toEqual([{ slug: SLUG, forms: [RETIRED, NAME].sort() }]); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null]).sort()).toEqual([[NAME, 'form', null], [RETIRED, 'form', null]].sort()); + expect(await rawRows(b, 'view', NAME, null)).toEqual([]); + expect(await rawRows(b, 'view', RETIRED, null)).toEqual([]); + await openOnBothDoors(b); + expect((await b.get()).body).toMatchObject({ slug: SLUG, label: 'Contact us' }); + }); + + it('all or nothing: with a row that holds the upgrade stored beside movable rows, --apply writes nothing, every stored row byte-equal, and both doors answer the same before and after (ablate: move what can be moved and report the rest)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + const BROKEN = `${OBJECT}.broken`; + await b.seedRow('view', BROKEN, null, { name: BROKEN, viewKind: 'form', sharing: sharing(true) }); + const before = await allRows(b); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(result.census.precheck.holds).toEqual([expect.objectContaining({ cause: 'unreadable' })]); + expect(await allRows(b)).toBe(before); + await closedOnBothDoors(b); + }); + + it('internal record forms are removed, and only those: an unlinked default form in a stored container with a list goes, the container is re-saved with its list byte-equal, the report carries its body (ablate: the base half of the internal test)', async () => { + const b = await booted({ views: [{ object: OBJECT, form: fields, formViews: { contact: { ...body(true), data: { provider: 'object', object: OBJECT } } } }] }); + const LIST_BODY = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; + await b.seedRow('view', OBJECT, null, { name: OBJECT, object: OBJECT, list: LIST_BODY, form: { ...fields, label: 'Edited' } }); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.removed).toEqual([expect.objectContaining({ form: DFORM, object: OBJECT, body: expect.objectContaining({ label: 'Edited' }) })]); + const [kept] = await activeBodies(b, 'view', OBJECT, null); + expect(kept).toEqual({ name: OBJECT, object: OBJECT, list: LIST_BODY }); + await openOnBothDoors(b); + }); + + it('the pair\'s own item (ruling 7250977204): a row bound to a read-only package that ships no form of the name moves into the pair declaring no `overrides`, and the public address answers byte-equal before and after', async () => { + const b = await booted({}); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const before = await b.get(); + expect(before.status).toBe(200); + const result = await apply(b); + expect(result.written).toEqual([expect.objectContaining({ destination: { kind: 'pair_form', base: BASE, pair: PAIR } })]); + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toBeDefined(); + expect(moved).not.toHaveProperty('overrides'); + expect(JSON.stringify(await b.get())).toBe(JSON.stringify(before)); + }); + + it('the census and the run agree where the store seals the destination: the pair\'s own item for a row bound to a read-only package that ships no form of the name, where another package ships the name as a `form` item, holds the upgrade in the census, and --apply writes nothing (ablate: the census read of the store\'s seal)', async () => { + const b = await booted({}); + const SHIPPER = 'com.example.shipper37111'; + b.engine.registerApp({ + id: SHIPPER, name: 'shipper37111', version: '1.0.0', type: 'app', namespace: 'fts', + dependencies: { [BASE]: '^1.0.0' }, + forms: [formItem(true, {}, OTHER_SLUG)], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const doors = async () => [answered(await b.get()), answered(await b.post()), answered(await b.get(OTHER_SLUG))]; + const before = await allRows(b); + const answers = await doors(); + const census = await listStoredFormsOf(b.protocol); + const plans = census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, (f as any).cause ?? null]); + expect(plans).toEqual([[{ kind: 'base', packageId: BASE }, 'hold', 'app_author']]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ name: NAME, packageId: BASE }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual(answers); + }); + + it('the census and the run agree where the store seals a kept row the run writes: a `form` row kept in a package the environment writes, carrying the withdrawal of an old-shape row folded into it, where another package ships the name as a `form` item, holds the upgrade in the census, and --apply writes nothing (ablate: the census read of the store\'s seal for a kept row)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + const SHIPPER = 'com.example.shipper37111'; + b.engine.registerApp({ + id: SHIPPER, name: 'shipper37111', version: '1.0.0', type: 'app', namespace: 'fts', + dependencies: { [BASE]: '^1.0.0' }, + forms: [formItem(true, {}, OTHER_SLUG)], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('form', NAME, DEPENDENT, formItem(true)); + await b.seedRow('view', NAME, DEPENDENT, viewItem(false)); + const before = await allRows(b); + const census = await listStoredFormsOf(b.protocol); + const plans = census.forms.filter((f: any) => f.form === NAME && f.address.packageId === DEPENDENT).map((f: any) => [f.outcome, (f as any).cause ?? null]); + expect(plans).toEqual([['hold', 'app_author']]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds.map((h: any) => h.refusal).join('\n')).toContain(`'${SHIPPER}'`); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(await allRows(b)).toBe(before); + }); + + it('a form no door serves today is left in place by the upgrade: the row stays as stored, nothing is written, and both doors answer 404 before --apply and after it (ablate: the census read of the form served today)', async () => { + const b = await booted({}); + b.engine.registerApp({ + id: 'com.example.lister37111', name: 'lister37111', version: '1.0.0', namespace: 'lst', + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const before = await allRows(b); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.reason])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'left_in_place', 'served_by_no_door'], + ]); + expect(result).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [] }); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + }); + + for (const [shape, pkg, extra] of [ + ['bound to a package the environment writes', DEPENDENT, {}], + ['the pair\'s own row', PAIR, {}], + ['the pair\'s declared override of a base that ships no form of the name', PAIR, overrides], + ] as const) { + it(`a form no door serves today is left in place by the upgrade, whatever package its row is bound to: ${shape} (ablate: the census read of the form served today, at the address each plan is made at)`, async () => { + const b = await booted({}); + await b.install(pkg); + b.engine.registerApp({ + id: 'com.example.lister37111', name: 'lister37111', version: '1.0.0', namespace: 'lst', + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, pkg, viewItem(true, extra)); + const before = await allRows(b); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + const result = await apply(b); + const plans = result.census.forms.filter((f: any) => f.form === NAME); + expect(plans.length).toBeGreaterThan(0); + expect(plans.map((f: any) => [f.outcome, f.reason])).toEqual(plans.map(() => ['left_in_place', 'served_by_no_door'])); + expect(result.written.filter((w: any) => w.form === NAME)).toEqual([]); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + }); + } + + for (const [shape, overrideOpen, boundOpen] of [ + ['the pair\'s override withdraws the form, the bound row is open', false, true], + ['the pair\'s override is open, the bound row withdraws the form (read today: closed, the withdrawal carried)', true, false], + ] as const) { + it(`M3 through both doors: no package ships the name, a row bound to the read-only base beside the pair's declared override of it; ${shape}: one \`form\` row in the pair, the override's body kept, and both doors answer as before (ablate: plan the pair's override at the pair's own address)`, async () => { + const b = await booted({}); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(overrideOpen, overrides)); + await b.seedRow('view', NAME, BASE, viewItem(boundOpen)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId])).toEqual([[NAME, 'form', PAIR]]); + const [kept] = await activeBodies(b, 'form', NAME, PAIR); + // The override's body is the one kept; a withdrawal the bound row carried narrows it to switched off. + expect(kept.sharing).toEqual(overrideOpen ? { ...sharing(true), enabled: false } : sharing(false)); + expect(await rawRows(b, 'view', NAME, BASE)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await closedOnBothDoors(b); + }); + } + + for (const open of [false, true]) { + it(`a row the read serves at another address than the package it is bound to (ruling record 7254350842): a module ships the form on its own object, the row bound to its App is ${open ? 'open' : 'switched off'}; it moves into the pair as the module's declared override, and both doors answer as before (ablate: plan the row at the package it is bound to)`, async () => { + const b = await booted({}); + const MODULE = `${BASE}.desk`; + const TICKET = 'ftt_ticket'; + const TICKET_FORM = `${TICKET}.contact`; + const TICKET_SLUG = 'ticket-37111'; + const data = { provider: 'object', object: TICKET }; + // The base as an App, as an installed App's manifest states it: its module's App. + b.engine.registerApp({ id: BASE, name: 'forms37086', version: '1.0.0', type: 'app', namespace: 'ftt', objects: [INQUIRY] } as any); + b.engine.registerApp({ + id: MODULE, name: 'forms37086-desk', version: '1.1.0', type: 'module', namespace: 'ftt', + dependencies: { [BASE]: '^1.0.0' }, + objects: [{ ...INQUIRY, name: TICKET, label: 'Ticket' }], + views: [{ object: TICKET, formViews: { contact: { ...body(true, TICKET_SLUG), data } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', TICKET_FORM, BASE, { name: TICKET_FORM, object: TICKET, viewKind: 'form', label: 'Stored', config: { ...body(open, TICKET_SLUG), data } }); + const doors = async () => [answered(await b.get(TICKET_SLUG)), (await b.get(TICKET_SLUG)).body?.label ?? null]; + const before = await doors(); + expect(before).toEqual(open ? [[200, undefined], 'Stored'] : [[404, 'FORM_NOT_FOUND'], null]); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === TICKET_FORM).map((f: any) => [f.address.packageId, f.outcome, f.destination?.kind])).toEqual([[MODULE, 'move', 'pair_override']]); + const [moved] = await activeBodies(b, 'form', TICKET_FORM, PAIR); + expect(moved).toMatchObject({ overrides: { package: MODULE } }); + expect(await rawRows(b, 'view', TICKET_FORM, BASE)).toEqual([]); + expect(await doors()).toEqual(before); + if (open) expect(answered(await b.post(TICKET_SLUG))).not.toEqual([404, 'FORM_NOT_FOUND']); + else expect(answered(await b.post(TICKET_SLUG))).toEqual([404, 'FORM_NOT_FOUND']); + }); + } +});