diff --git a/.changeset/37111-stored-forms-census.md b/.changeset/37111-stored-forms-census.md new file mode 100644 index 00000000000..4f80a2ae4e7 --- /dev/null +++ b/.changeset/37111-stored-forms-census.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +feat(cli): `os migrate stored-forms`, the read-only census and precheck of the stored-form ceremony (ADR-0159 D7) + +Clause-②: yes +Metadata-protocol: none + +The next protocol major stops reading the three old shapes of a form (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item). Its upgrade command moves the stored rows that still hold one, in the same run that switches to the major, all or nothing. `os migrate stored-forms` shows that outcome before the upgrade and writes nothing: for each form name at each package that can serve it, whether the row is kept, moved (into the base's paired `.custom` package as a declared override, into a writable package's own form row, or into the environment), folded into the served row, removed as an internal record form, or left in place; and whether the upgrade can switch, naming each row that holds it (its pair cannot be ensured, its form content cannot be read, or one slot of a paired `.custom` package is claimed by more than one move) with the action for its cause. A row bound to a read-only package that ships no form of its name moves into that package's paired `.custom` package as a form of its own. Old-shape drafts are listed: they are neither moved nor deleted, and cannot be published after the upgrade. A row read at several packages is named at each, and is removed only where it is an internal record form at every one of them; read at two packages of one App that would both move it, it holds the upgrade, since the App's `.custom` package holds one row of a form's name (as does a row that package already holds of the name, beside a row planned into it); read at several packages, of one App or several, that would not all move it or all remove it, it holds the upgrade at each of them; a row with a public link behind an internal form left in place holds the upgrade where another package would move it, and neither row is folded, moved or removed at any package (a plan that would do so holds); and a row that holds is folded into no other row. A withdrawal a folded row carries that no layer reads today is named newly closed. + +`listStoredFormsOf(protocol)` answers the census over a protocol instance; it and its types are exported (`StoredFormCensus` and the shapes it names). The start-up message for a stored view whose form content cannot be read now names the command. `orderedFormRowsAt` is the served-row order the effective `form` read already used, now read by the census too; the read serves what it served. + +The operations page is `content/docs/deployment/stored-forms-upgrade.mdx`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 115c5ca2e5c..a1f8a6c98c2 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1341,6 +1341,7 @@ written. | `os migrate security-catalog-overlays --apply` | **Refuses** likewise — it deletes `sys_metadata` rows, and a live process saving metadata is exactly the collision | | `os migrate packageless-overlays --apply` | **Refuses** likewise — it moves `sys_metadata` rows into each base's pair | | `os migrate stored-references bind` | **Refuses** likewise — it writes one row's package column | +| `os migrate stored-forms` | Warns and continues — it is read-only | The check applies to SQLite only: Postgres and MySQL take their own server-side locks. Only same-user processes are visible without elevated privileges, and a @@ -1564,6 +1565,7 @@ where the data lives. | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | | `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list`, `listViews`, `form`, `formViews`): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its views into the pair as a single view, then delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | +| `os migrate stored-forms` | Read-only: list what the upgrade to the next protocol major does with every stored row that still holds a form in an old shape (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item) — kept, moved, folded, removed as an internal record form, or left in place — and whether that upgrade can switch, naming each row that holds it (its `.custom` pair cannot be created, or its form content cannot be read) with the action for its cause, and listing the old-shape drafts that cannot be published after the upgrade. No `--apply`: the move runs only inside the upgrade command. Takes `serve`'s `--preset` and `--dev`. See [Check stored forms before the next major](/docs/deployment/stored-forms-upgrade) | | `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report), and refuses (`duplicate`) a bind the table's unique key refuses because a row bound to that package already holds the key, such as a connector connection the instance already has in that organization. Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` | | `os migrate duplicates` | Report business identifiers already minted twice across the organization partitions, and the rows blocking the boot-time NULL-safe index tightenings — a read-only inventory as JSON on stdout. Renumbers nothing and writes no row and no schema; run it before the boot-time tenancy repair, which overwrites part of the evidence | diff --git a/content/docs/deployment/meta.json b/content/docs/deployment/meta.json index a82e19a78ac..e9107b8075e 100644 --- a/content/docs/deployment/meta.json +++ b/content/docs/deployment/meta.json @@ -6,6 +6,7 @@ "backup-restore", "tenancy-modes", "seed-tenancy-repair", + "stored-forms-upgrade", "single-project-mode", "marketplace-handbook", "publish-and-preview", diff --git a/content/docs/deployment/stored-forms-upgrade.mdx b/content/docs/deployment/stored-forms-upgrade.mdx new file mode 100644 index 00000000000..676dd87ddf7 --- /dev/null +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -0,0 +1,94 @@ +--- +title: Check stored forms before the next major +navTitle: Stored Forms Check +description: What `os migrate stored-forms` reports about the forms your database still stores as views, what the upgrade to the next protocol major will do with each, and how to clear a row that holds the upgrade. +--- + +A form used to be stored as a view: a view container's `form`, a `formViews` +entry, or a view item with `viewKind: 'form'`. Forms are now their own +metadata type, and the next protocol major stops reading those three shapes. +Whatever your database still stores in them is moved by the major's upgrade +command, in the same run that switches to the major. The move and the switch +are all or nothing: if one stored row cannot be moved, the upgrade does not +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. + +```bash +os migrate stored-forms +os migrate stored-forms --json +``` + +It composes the deployment the way `os serve` does, so pass the `--preset` +and `--dev` flags the deployment boots with, and `--database-url` (or +`$OS_DATABASE_URL`) for the database. The boot is read-only. The command exits +`0` whenever the check ran; `canSwitch` in the `--json` output says whether +the upgrade would switch. + +## What it reports, per form + +A form is reported at each package that can serve it: a read-only package +that ships it (an installed app, or a package your code provides), a writable +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. | +| **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). | +| **holds the upgrade** | The row cannot be moved. The report repeats the reason and the action. | + +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 +row at two packages' addresses of one app that would both move it, or two +rows would move into one slot of the app's `.custom` package (a row the +`.custom` package already holds of that name among them), each such row +holds the upgrade: a +`.custom` package holds one row of a form's name, so neither address can be +given a destination. Where the server serves one row at several packages, +of one app or of several, and those packages would not all move it or all +remove it (one moves or removes it, another leaves it in place or holds), +the row holds the upgrade at each of them too: moving or removing a row +takes it from every package that serves it. Nothing moves, and every +address keeps answering as it does today. The row is named once, with every +address it is read at. A row every package that serves it would remove is +removed, and one every package leaves in place is left in place. A row that +holds the upgrade is not folded into another row: where it stands behind a +row that moves, the report names it apart. + +When several rows of one form are stored (an override in the `.custom` +package, a row bound to the package, a row bound to no package), the body +kept is the one served today. A folded row carries one thing: if it switched +the form off (its link kept, `enabled` or `allowAnonymous` set to `false`), the +kept form keeps its link and is switched off too. When the folded row was one +that nothing reads today, that closes a form that is open today. The report +marks it **NEWLY CLOSED**, with the kept form's address. Switch it on again in Setup after +the upgrade if it should stay open. + +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. + +## Clearing a row that holds the upgrade + +| Cause | Who can clear it | What to do | +|---|---|---| +| The paired `.custom` package cannot be created: another package sits under its id or holds its namespace, or the app that carries the package is not installed | The administrator | Make the fix the quoted refusal names on the release you are running, then run the check again. | +| A `.custom` package an earlier version created for one package of the app holds the namespace | No one, on this release | The row holds the upgrade until that package is re-identified as the app's `.custom` package (ADR-0146 D3, merge question 12), and no command on this release does that. The row keeps working as it does today meanwhile. | +| 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. | +| 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 + +- **Drafts**: a draft view with form content in an old shape is neither moved + nor deleted. After the upgrade it cannot be published, so publish the drafts + you want to keep before upgrading. A form that moves names its draft, which + stays behind as stored. +- **Shared addresses**: a public address that two form names declare, such as + a retired form and the one that replaced it. 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 8e335e5d959..e628906788e 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 @@ -1,6 +1,6 @@ # ADR-0159: Forms are their own metadata type — a `form` item is a named form with a consumer, public forms are `form` items, and `view` is lists only -**Status**: Proposed — 2026-11-24, written for objectstack#36868 on the maintainer's ruling of that day (ruling records [`7123091354`](https://github.com/objectstack-ai/objectstack/issues/36444#issuecomment-7123091354) on #36444 and [`7123091586`](https://github.com/objectstack-ai/objectstack/issues/36505#issuecomment-7123091586) on #36505). **The five merge questions are ruled, all option A** (ruling record [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7131569242) on #36868, 2026-11-24; [the questions](#the-five-merge-questions-as-ruled)): the record now carries no open default. `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset; every mechanism below is cut as a card after the merge ([Execution plan](#execution-plan-after-acceptance)). It **amends** [ADR-0017](./0017-object-has-many-view.md) (`viewKind` becomes list-only; the form arm is tombstoned on [D7](#d7)'s schedule) and [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D2 (`form` joins the overridable types) — each record's Status line carries the dated pointer. **Revised 2026-11-25** to record five maintainer rulings and two seat decisions made after PR #36957 merged (ruling record [`7142585849`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142585849) on #36868, 2026-11-24T19:46Z, and its addendum [`7142658348`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142658348), 19:49Z; the words are under "Decided by"): the type is added in major 19 and no release carries the dual-read; the major's upgrade command runs the stored-row ceremony and then switches, all or nothing; that upgrade removes stored internal record forms; the major's release notes lead with #36425's effect; HotCRM moves its sources with its own bump to the major. Each revised sentence carries the record's id and the ruling's number, and nothing else in this record is re-opened. +**Status**: Proposed — 2026-11-24, written for objectstack#36868 on the maintainer's ruling of that day (ruling records [`7123091354`](https://github.com/objectstack-ai/objectstack/issues/36444#issuecomment-7123091354) on #36444 and [`7123091586`](https://github.com/objectstack-ai/objectstack/issues/36505#issuecomment-7123091586) on #36505). **The five merge questions are ruled, all option A** (ruling record [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7131569242) on #36868, 2026-11-24; [the questions](#the-five-merge-questions-as-ruled)): the record now carries no open default. `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset; every mechanism below is cut as a card after the merge ([Execution plan](#execution-plan-after-acceptance)). It **amends** [ADR-0017](./0017-object-has-many-view.md) (`viewKind` becomes list-only; the form arm is tombstoned on [D7](#d7)'s schedule) and [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D2 (`form` joins the overridable types) — each record's Status line carries the dated pointer. **Revised 2026-11-25** to record five maintainer rulings and two seat decisions made after PR #36957 merged (ruling record [`7142585849`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142585849) on #36868, 2026-11-24T19:46Z, and its addendum [`7142658348`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142658348), 19:49Z; the words are under "Decided by"): the type is added in major 19 and no release carries the dual-read; the major's upgrade command runs the stored-row ceremony and then switches, all or nothing; that upgrade removes stored internal record forms; the major's release notes lead with #36425's effect; HotCRM moves its sources with its own bump to the major. Each revised sentence carries the record's id and the ruling's number, and nothing else in this record is re-opened. **Revised 2026-11-29** by card ⑤a, to record five maintainer rulings on #37111, each in [D7](#d7) where it applies: an internal record form served ahead of a package-less row that carries a public link (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572), D7-d); the destination of a form row bound to a package that ships no form of its name (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204)); stored drafts, and the per-package pair of an earlier version that holds the namespace (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640), D7-c); the reach of the second ruling, a row the read serves at another address than the package it is bound to (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842), D7). One reading of this record stands beside them, marked where it stands and named in TL;DR 10: the first ruling's answer for any other linked row behind such a form (D7-d). **Revised 2026-11-30** by card ⑤a, to record one maintainer ruling on #38661 and the seat steps under it, in [D7](#d7): a stored form row the read serves at two addresses of one App is moved at neither and holds the upgrade, and the same hold covers every slot of a pair that more than one plan claims (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895)); the class of the hold's cause, and the same hold for a row more than one address serves where those addresses would not all move it or all remove it, are the owning seat's steps, not the maintainer's words. So is one reading of the ruling of 2026-11-29 (`7249158572`) together with the ruling of 2026-11-30: a form row kept behind an internal record form that an address leaves in place holds the upgrade, at that address too, where another address serves it and would move it or remove it; and, by the same reading, the row a further address serves holds the upgrade where its plan would fold, move or remove a row so kept or that internal form, or write a folded row's withdrawal into either. Each is an exception to that ruling record's "The upgrade is not blocked", and each is the owning seat's step, for the approver to accept with the record or strike ([D7](#d7), D7-d). - **Date**: 2026-11-24 - **Decided by**: the maintainer, 2026-11-24, verbatim and untranslated, as the card and the two ruling records carry them: @@ -16,6 +16,12 @@ 4. 「要在发版说明里重点提示」 5. On HotCRM: 「HotCRM 的迁移跟着它升级到大版本那次一起做」「卡⑤ 不再等 HotCRM 卡,否则两边会互相等待。」 - Two seat decisions stand under those rulings. They are the owning seat's, not the maintainer's words, and are in his veto window: the upgrade's move is all-or-nothing with the switch (`7142585849`); the ceremony's `--apply` is reached only from the upgrade command, and the standalone command is read-only (`7142658348`). + - 2026-11-29, on card ⑤a (#37111), each by decision tap after an independent analysis; entered here by the revision of 2026-11-29: + 1. An internal record form served ahead of a same-named package-less row that carries a public link: 「两行都不动,写进报告」 (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572); [D7](#d7), D7-d). + 2. A stored form row bound to a read-only package that ships no form of the name: 「B 搬进定制包(推荐)」 (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204); [D7](#d7)). + 3. Draft rows with form content: 「A 留下并提醒(推荐)」; and the per-package pair of an earlier version that holds the namespace: 「B 只改文字,不开卡」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640); [D7](#d7), D7-c). + 4. The reach of the second ruling, a row the read serves at another address than the package it is bound to: option A of four (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842); [D7](#d7)). + - 2026-11-30, on decision card #38661, put for card ⑤a (#37111), by decision tap after an independent analysis; entered here by the revision of 2026-11-30. What the upgrade does with a stored form row the read serves at two package addresses of one App, and the reach of the answer: 「A 拦住升级·同类全覆盖」 (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661, recorded 2026-11-30T01:03Z; [D7](#d7)). The option as the card worded it: 「升级前检查点名该行,升级不切换、两个地址照常应答;同一定制位置被多份表单争用的情形也一律这样拦住,不必再开决策卡。」 Not taken: A for the two-address row alone; B, leave the row as stored, report it and do not count it; C, decide by what the row does today. The steps that carry it out are the owning seat's, not the maintainer's words: the cause class of the hold is one of them, and the same hold for a row more than one address serves, where those addresses would not all move it or all remove it, is another ([D7](#d7)). A third reads this ruling together with the ruling of 2026-11-29 (`7249158572`, item 1 above): 「两行都不动」 keeps the form rows behind the internal record form at that address, so a row kept there holds the upgrade, at that address too, where another address serves it and would move it or remove it, and the row a further address serves holds the upgrade where its plan would fold, move or remove a row kept there or the internal form itself, or write a folded row's withdrawal into either. That ruling's record says "The upgrade is not blocked"; each is an exception to it, the owning seat's reading and not the maintainer's words, for the approver to accept with the record or strike ([D7](#d7), D7-d). - **The ruling, as the card records it** (this record executes it; ⛔ none of it is re-opened here): 1. A new metadata type **`form`**, addressed by name, bound to one object (it carries `object` itself), body = today's form view schema. Its content is named forms that have a consumer: **public forms** (the main content, `sharing` included) and forms an action of `type: 'form'` opens. 2. **Public forms are not a separate feature**: they are `form` items. Their list, detail and edit come from the `form` type, not from a separate Studio page. @@ -37,12 +43,13 @@ 7. **Translations get a `forms` family**; the form tails under `objects.OBJECT._views` are read as a fallback until the major ([D8](#d8)). 8. **Shipped work is kept and re-pointed**: Setup's page reads `form`, the paused designer becomes the `form` editor, the Studio Developer page and the Form-tab switch retire ([D9](#d9)). 9. **Five cards, in order**; ② adds the type and narrows one write, ③ and ④ are additive, ⑤ is the major ([Execution plan](#execution-plan-after-acceptance)). -10. **Five points the first ruling is silent on were put to the maintainer and are ruled, all option A**: `defineForm` is the type's factory, the name stays `OBJECT.KEY`, a taken public address is refused, the reader of old withdrawals is exempt from the age-out, and the body is at the top level ([The five merge questions, as ruled](#the-five-merge-questions-as-ruled)). **Five points go past the ruling's words. Each is marked where it stands, outside every ruled block, for the approver to accept with the record or strike**: +10. **Five points the first ruling is silent on were put to the maintainer and are ruled, all option A**: `defineForm` is the type's factory, the name stays `OBJECT.KEY`, a taken public address is refused, the reader of old withdrawals is exempt from the age-out, and the body is at the top level ([The five merge questions, as ruled](#the-five-merge-questions-as-ruled)). **Six points go past the ruling's words. Each is marked where it stands, outside every ruled block, for the approver to accept with the record or strike**: - the `*.form.ts` file suffix follows the factory name, by the owning seat's routing on question 1 ([D2](#d2)); - a switched-off form that keeps its link still holds its address ([question 3](#q3), this record's reading of "holds"); - this record keeps the withdrawal reader through major 19, although the ruling would let it leave there ([question 4](#q4)); - the source conversion moves an item that declares `overrides` to `forms[]` whatever its body, which for a time puts a record form's override among the `form` items, past ruling item 3; `os validate` refuses the one whose base ships no form of that name ([D7](#d7), D7-b); - rule 11's replacement check is kept after major 19 on the withdrawal reader's lifetime, past the "this one reader" that question 4 exempts ([D7](#d7), "After the major"; [question 4](#q4)). Striking this returns the later ruling on the two kinds of row, named below, to the maintainer. + - the ruling of 2026-11-29 answers an internal record form served ahead of a package-less row that carries a public link; this record gives the same answer wherever the row behind declares a link, whatever it is bound to ([D7](#d7), D7-d). Striking it sends those shapes back to the maintainer before card ⑤b's `--apply`. Four more things are named here so they are read with them. The first three touch no ruled word; the fourth is a later ruling: - the fold of several stored rows closes a form that is open today, where a row no layer reads withdraws it ([D7](#d7), D7-d); @@ -278,25 +285,33 @@ 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: + - **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. + - **Against D7-d.** The fold comes first, and is unchanged for every row that does not hold: the rows of a form at one address reduce to the body the read serves there, and an address has one plan at most. A row that holds the upgrade where it is served is folded into no other row, as above. D7-d gives no order between the plans of two addresses, and ⛔ the ceremony never decides by the order it moves rows in or by which row reached the destination first. So no claimant is chosen for the slot, and nothing is written. D7-d's "left in place" is asked per address and is unchanged, with two exceptions under the ruling. The first: where another address that serves the same row, of the same App or of another, would move it or remove it, the row is held at each of those addresses and the precheck counts it, so that it is neither moved nor removed from under the address that leaves it. The second is the owning seat's reading of the ruling of 2026-11-29 (`7249158572`) together with this one, not the maintainer's words. 「两行都不动」 keeps the form rows behind the internal record form at that address as it keeps the form, so the address that leaves the form in place keeps each of them, though it does not serve them. Where another address serves such a row and would move it or remove it, the row holds the upgrade at every address that serves it or keeps it, the address that leaves the form in place among them: it is moved or removed at none of them, both rows stay as stored, the precheck names the row once, and the action names no exit. The seat reads that keeping row-wide: the internal record form an address leaves in place under the ruling of 2026-11-29, and each form row behind it there, stay as stored at every address under that name, so a plan at another address that would fold one of them into the row it serves, remove it with that row, or write a folded row's withdrawal into it holds the upgrade instead (the precheck names the row that plan serves; its action names no exit, and says the cause is one App's author's to remove only where that address and each address that keeps the row are of one App that can be read), a kept row behind the served row of any plan that holds is listed apart there and not among the rows that fold into it, and the address that keeps the row stays left in place unless a row it keeps would also be moved or removed at an address that serves it. That ruling's record says "The upgrade is not blocked", written for one address; this is an exception to it, for the approver to accept with the record or strike. + - **Against D7-e.** D7-e is unchanged: the hold's action offers no deletion and no reset, and names no act of the administrator's that changes what an address answers. - A **row bound to a read-only base** — a customization saved under the base's own id before that door closed, the class ADR-0146 D11's ceremony carries beside the package-less one (`packages/metadata-protocol/src/protocol-packageless-overlay-migration.ts`) — has the same destination: a declared `form` override in the base's pair, with its body as written (D7-b). - **(D7-d) Several stored rows of one form fold into one: the body kept is the one served today, and the fold only narrows.** More than one stored row of a form can head for one destination. Over a read-only base there are three, all bound for the pair's declared override: the pair's own override, a row bound to the base, and a package-less row. For a writable package there are two, bound for the package's own row: that row and a package-less row (the ensure door refuses a writable base with "customize it directly"). - **The body kept is the one the served-row order serves today** (`servedOverlayRowCandidates`: the pair's override, then the row bound to the package, then the package-less row), whichever binding and whichever type it is stored in. It lands on the destination as written: a body with no link stays without one. ⛔ The ceremony never decides this by the order it moves rows in, and never by which row reached the destination first. - **The served row is found among every stored row at the address, whether it carries a form or not, in either type.** Where the row the order picks carries no form at the name (D7-b's row with nothing to move), nothing is served for the name today ([D5](#d5)), and the ceremony moves **no** row of that name. A form row behind it, bound to the base or package-less, stays where it is, and every stored row of the name stays as stored with the no-form row. The no-form row is one of the two kinds the ruling recorded beside [question 4](#q4) names; by this record's reading of that answer, a form row left behind a no-form row is not held either. None of them holds the upgrade; the report names each as left in place. Moved alone, the form row would become the pair's override, first in the served-row order and ahead of the row that keeps the address closed. The same holds where the row picked is a declared `view` override that carries no form, if card ② finds a door for one: no form row behind it is moved into the pair, where a stored `form` row would win over it ([D5](#d5)). - **A writable package's own list ahead of a package-less form row.** The same rule decides it, and the record says it by name because the list is not D7-b's row. The served row at the address is the package's own `view` row, which carries a list; the package-less row behind it carries a form no layer reads ([D5](#d5), "served rows only"). The ceremony moves **no** row of the name: moved to the package's own `form` row, the package-less body would be a `form` item of that package and would be served. The list is the package's own item: it is not an old-shape form row, it holds nothing, and neither the report nor the precheck names an action for it. The package-less form row stays as stored: by the ruling recorded beside [question 4](#q4) it gets no disposition of its own and does not hold the upgrade. The report names it as left in place, with the list that is served ahead of it, and offers no deletion for it (D7-e) and no save that would serve it. No layer reads it before the major or after it. **This is the rule at the writable package's address, and only there.** A package-less row that is also the served row at a read-only base's address, standing over that base's form, keeps at that address what [D7](#d7) gives it: its destination in the base's pair, or D7-c's hold where the pair cannot be ensured. - - **Every other row of the form is folded into it and carries over one thing only**: if it explicitly withdraws the form, the destination keeps its link and takes that switch off. Nothing else of a folded row is kept — not its link, not a switch that is on — so a body the read does not serve today is never served by the ceremony. The report names every row of the form, the one whose body was kept, and which one closes the form. + - **An internal record form served ahead of a row that declares a link.** The served row is an internal record form (the three-part set above), and another stored row of the same name at the same address declares a `sharing.publicLink`, switched on or off: a writable package's own row ahead of a package-less row, say. The ceremony moves **no** row of the name and deletes none, and the internal form is not removed in this shape: removed, it would leave the linked row behind it, which no layer reads today, as the row the order serves next. Both rows stay as stored, and the report names both as left in place, saying the internal form was not removed because a row with a public link stands behind it. The precheck does not hold the upgrade for them: this is a "not counted" kind beside the two the ruling recorded beside [question 4](#q4) names and the one this record adds. The maintainer ruled the package-less case on 2026-11-29: an internal record form served ahead of a same-named package-less row that carries a public link gets 「两行都不动,写进报告」 (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572) on #37111); the ruling record's reading carries the same answer to the twin, where that link's switch is off. By this record's reading of that answer, the same answer holds wherever the row behind the internal served row declares a link, whatever it is bound to: an internal pair override ahead of a linked row bound to the base, say, where removing the internal row would likewise serve a linked row the read does not serve today. Only that reading is still open to correction. Both doors answer `404` at the address before the ceremony and after it, and on major 19. One exception to "does not hold the upgrade" stands beside this bullet, and it is the owning seat's step, not the maintainer's words: where another address serves a form row that stands behind the internal form here, and would move it or remove it, the row holds the upgrade at every address that serves it or keeps it, this one among them, so that both rows stay as stored (the seat's reading of this ruling with the ruling of 2026-11-30, `7265816895`; it and the exception for the internal form itself are stated under "Against D7-d" in [D7](#d7)), and a further exception, the same seat's step and not the maintainer's words, is stated there too: where a plan at a further address would fold, move or remove a row kept here, the internal form or a form row behind it, or write a folded row's withdrawal into it, the row that address serves holds the upgrade. + - **Every other row of the form is folded into it and carries over one thing only**: if it explicitly withdraws the form, the destination keeps its link and takes that switch off. Nothing else of a folded row is kept — not its link, not a switch that is on — so a body the read does not serve today is never served by the ceremony. The report names every row of the form, the one whose body was kept, and which one closes the form. A row that holds the upgrade where it is served is not one of them: it is folded into no other row, it carries nothing over, and the report names it apart ([D7](#d7), under the ruling of 2026-11-30, `7265816895`). - **Why the served order decides: a row bound to the base beside a package-less row.** The read serves the bound row today, in the effective list and in the base's per-package layer alike; the package-less row behind it is read by neither. Where the bound row has no link over a linked base, it closes the address by replacing the base's body (rule 11 of [D6](#d6)), and the package-less row may hold an open body. Both rows have the pair as destination, and the pair's override is first in the served-row order. Kept by the served order, the bound row's body is the pair's override and the address stays closed after `--apply`; the package-less body is folded and its open switch is not carried. - **A folded row's withdrawal that a layer reads today must keep closing.** The base's per-package layer reads the first of the bound row and the package-less row, under an open override of the pair. A withdrawal there closes the form today, and the fold carries it. - **A folded row's withdrawal that no layer reads today closes the form newly.** A package-less row behind a row bound to the base, or behind a writable package's own row, is read by no layer, so its withdrawal closes nothing today. The fold carries it all the same: the form is open before the ceremony and answers `404` after it. That is the direction a layer may take. The report names the form as newly closed, and the administrator switches it on again in Setup. - Every statement about today in this bullet is read from the served-row order and the per-package layer's contract (`servedOverlayRowCandidates`, `getMetaItemsPerPackage`) and was not run for this record; card ⑤'s fold pin runs each "before" half before the ceremony relies on it. - **(D7-c) Where the pair cannot be ensured, the row is not moved, and it holds the upgrade to major 19 until it is.** The ceremony writes nothing for it. It stays a `view` row on the pre-upgrade release, which reads it as it does today — that release has no [D6](#d6) (`7142585849`, ruling 2, and the seat's all-or-nothing decision below) — so a withdrawal it holds keeps closing and a base form it replaces stays replaced. ⛔ It is not moved to a package-less `form` row: `form` takes no environment-overlay tier ([D2](#d2)), and the read path honours an unmigrated package-less row only for a type that has one (ADR-0146 D11). The ceremony's report and the upgrade precheck both name the row (type, name, base) and repeat the ensure door's own refusal (`packages/metadata-protocol/src/protocol-customization-package.ts#customizationPairEnsureRefusal`), with the administrator's action for its cause: - - **A cause the administrator can remove in the deployment**: a package installed under the pair's id is not the pair; another package owns the pair's namespace; the App that carries the base is not installed; a per-package pair an earlier version created holds the namespace (ADR-0146 D11's own ceremony re-identifies it, so that ceremony runs first). The door's text names the fix for each. The administrator makes it on the pre-upgrade release and runs the upgrade command again (`7142585849`, ruling 2); the row moves to the pair with its body as written. - - **A cause only the App's author can remove**: the App declares no namespace, or one too long or not valid for a pair namespace; the App's version is not SemVer; the base declares several Apps and its namespace picks none. An administrator who authors the App fixes it as above. One who does not cannot: the deployment stays on major 18 until the App ships a version without the cause, or is uninstalled, which takes the base's form and its address with it. "Stays on major 18" stands: it is the state of a deployment whose upgrade does not switch (`7142585849`, ruling 2). The row keeps closing meanwhile, as the `view` row it is. The precheck names the App and the cause, says the fix is its author's, and offers no other action. + - **A cause the administrator can remove in the deployment**: a package installed under the pair's id is not the pair; another package owns the pair's namespace; the App that carries the base is not installed. The door's text names the fix for each. The administrator makes it on the pre-upgrade release and runs the upgrade command again (`7142585849`, ruling 2); the row moves to the pair with its body as written. A per-package pair an earlier version created that holds the namespace is classed here too, and is not removable on this release: the row holds the upgrade until that pair is re-identified as the App's pair (ADR-0146 D3, merge question 12), and no command on this release does that; the precheck's action says so and offers no other. Ruled by the maintainer on 2026-11-29: 「B 只改文字,不开卡」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640) on #37111): the text changes, the class does not, and no card is filed. + - **A cause only the App's author can remove**: the App declares no namespace, or one too long or not valid for a pair namespace; the App's version is not SemVer; the base declares several Apps and its namespace picks none. An administrator who authors the App fixes it as above. One who does not cannot: the deployment stays on major 18 until the App ships a version without the cause, or is uninstalled, which takes the base's form and its address with it. "Stays on major 18" stands: it is the state of a deployment whose upgrade does not switch (`7142585849`, ruling 2). The row keeps closing meanwhile, as the `view` row it is. The precheck names the App and the cause, says the fix is its author's, and offers no other action. A hold under the ruling of 2026-11-30 (`7265816895`, [D7](#d7)) that waits on another hold of its row takes that hold's class and its action. Every other one is of this class, and its action is the one stated there: it names the App where the cause is in one App that can be read, and otherwise 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 that no one App's author can remove the cause alone. It names the exit of this class, a version of the App without the cause, only where that was measured, for one row read at two or more addresses of one App; elsewhere it says that no action on this release clears the hold. - **A base that has no pair in this version**: a kernel package, until the kernel whitelist of ADR-0146 D3 admits it. Measured at `689e5695b98`, this case is empty: no package that ships metadata to a deployment authors a form in any of the three shapes (`git grep -lE "formViews|viewKind: 'form'|viewKind === 'form'" -- packages/platform-objects packages/plugins packages/services packages/triggers packages/drivers packages/connectors packages/apps` finds one `CHANGELOG.md` and no source), so no package-less row overlays a kernel package's form. Card ⑤ takes the reading again before it is cut. If a kernel package ships a named form by then, this record has no way out for the row without a new mechanism, and the case goes to the maintainer as a decision before major 19 opens. - **A body the projection cannot read** (rule 7 of [D6](#d6)) is in the same class: the ceremony cannot move it, it holds the upgrade, and on the pre-upgrade release both doors answer for it as they do today: rule 7 runs on `main` and on the major, not there. It leaves the class by an old-shape save that repairs the body, made on the pre-upgrade release; the upgrade command, run again, then moves it (`7142585849`, ruling 2). - **(D7-e)** ⛔ In none of these cases does the precheck or the ceremony's report offer deletion or a reset for a row that declares a `sharing.publicLink`, or for a row that stands over a base form that declares one (D7-b), and card ⑤ does not let such a row through. Deleting a switched-off form's row switches the form back on; deleting a link-less row over a linked base serves the base's form again. - History rows stay verbatim under the type they were written as (ADR-0087: the version layer is not converted); the new row's history starts with the move. -- Internal record forms in stored rows are removed by the upgrade, in the run that switches (`7142585849`, ruling 3): an item-shaped row is deleted, a container that also holds lists is re-saved without that member, its lists byte-equal. The report names each removed form, writes out its body, and says per object that New and Edit now follow the object's field groups and whether it has any. History rows stay verbatim. A deployment that does not switch keeps every one. The set is the one defined above, all three parts: no `sharing.publicLink`, no action target, and not standing over a base form that declares a link. Ruling 3 widens nothing: a row that declares a `sharing.publicLink`, or stands over a linked base, is never removed, and D7-e and the three-part test are unchanged. Removing a row of that set changes no door's answer: it steers nothing, it holds no switch because it has no link, and it replaces no linked body because its base has none. ⛔ That holds for this set only. A row with no link of its own that stands over a linked base is not in it (D7-b), and the report never lists one for removal. The precheck does not count the internal ones as holding the upgrade; the read-only run lists them as "will be removed" (`7142585849`, ruling 3). -- The major's upgrade command runs the ceremony and then the precheck (`7142585849`, ruling 2). It switches when the precheck counts no row. It refuses to switch when the precheck counts one, naming each row and its action, and the deployment stays on the release it is running. What refuses is a row that holds the upgrade (D7-c: its pair cannot be ensured, or its body cannot be read). A row the ceremony can move does not refuse, and neither does an internal record form: the upgrade moves the one and removes the other (ruling 3). Not counted are the two kinds of row the ruling recorded beside [question 4](#q4) names — a row that carries no form over a linked base, and a package-less form row no layer reads behind a writable package's own list — and, by this record's reading of that answer, a form row left behind a no-form row. They stay as stored and the upgrade proceeds with them. "Not counted" is asked per package address, as [D5](#d5) asks "served": a package-less row passed over at a writable package's address still holds the upgrade at a read-only base's address whose pair cannot be ensured. +- **Draft rows are neither moved nor deleted**, and no door's answer changes: no read serves a draft. The report lists each draft `view` row that carries form content in an old shape, and says that after the upgrade such a draft cannot be published, so an administrator who wants one kept publishes it first; it also names a draft left behind by a published row that moves. A `form` draft is in the new shape and is not listed. Ruled by the maintainer on 2026-11-29: 「A 留下并提醒(推荐)」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640) on #37111). +- Internal record forms in stored rows are removed by the upgrade, in the run that switches (`7142585849`, ruling 3): an item-shaped row is deleted, a container that also holds lists is re-saved without that member, its lists byte-equal. The report names each removed form, writes out its body, and says per object that New and Edit now follow the object's field groups and whether it has any. History rows stay verbatim. A deployment that does not switch keeps every one. The set is the one defined above, all three parts: no `sharing.publicLink`, no action target, and not standing over a base form that declares a link. Ruling 3 widens nothing: a row that declares a `sharing.publicLink`, or stands over a linked base, is never removed, and D7-e and the three-part test are unchanged. Removing a row of that set changes no door's answer: it steers nothing, it holds no switch because it has no link, and it replaces no linked body because its base has none. ⛔ That holds for this set only. A row with no link of its own that stands over a linked base is not in it (D7-b), and the report never lists one for removal. The precheck does not count the internal ones as holding the upgrade; the read-only run lists them as "will be removed" (`7142585849`, ruling 3). A deletion is per row, and so is a move: each asks every address that serves the row, whatever App the address is of. A package-less row is read at every address of its name, so it is in the set only when it is internal at each of them, and a row over a linked base at any one of them moves at each instead, into each address's own destination; where two of those moves claim one slot of a pair, it holds the upgrade and is moved at neither (the ruling of 2026-11-30, `7265816895`). A row is moved only where every address that serves it would move it, and removed only where every address that serves it would remove it. Where one would move or remove it and another keeps it, as D7-d does where it leaves an internal record form in place ahead of a row that declares a link, or one would move it and another remove it, the row is moved or removed at none of them and holds the upgrade at each; the precheck names it once, with every address, or by the hold one of its plans already has. That is the owning seat's step under the same ruling, not the maintainer's words: a move or a removal takes the row from every address that serves it, and the ruling leaves both addresses of its row answering as they do today. A list row behind a removed form is not part of it, and stays byte-equal. +- The major's upgrade command runs the ceremony and then the precheck (`7142585849`, ruling 2). It switches when the precheck counts no row. It refuses to switch when the precheck counts one, naming each row and its action, and the deployment stays on the release it is running. What refuses is a row that holds the upgrade (D7-c: its pair cannot be ensured, or its body cannot be read; or, by the ruling of 2026-11-30, `7265816895`, it claims a slot of a pair and another plan claims that slot too, or more than one address serves it, one of them would move or remove it, and another would not do the same). A row the ceremony can move does not refuse, and neither does an internal record form: the upgrade moves the one and removes the other (ruling 3). Not counted are the two kinds of row the ruling recorded beside [question 4](#q4) names — a row that carries no form over a linked base, and a package-less form row no layer reads behind a writable package's own list — and, by this record's reading of that answer, a form row left behind a no-form row, and, by the ruling of 2026-11-29 (D7-d, `7249158572`), an internal record form served ahead of a package-less row that declares a link, with that row, and, by this record's reading of that ruling, an internal record form served ahead of any other row that declares a link, with that row. They stay as stored and the upgrade proceeds with them, with the three exceptions the ruling of 2026-11-30 brings ("Against D7-d" under [D7](#d7)), each the owning seat's step: an internal record form left in place at one address holds the upgrade where another address that serves it would move it or remove it; a form row kept behind such a form holds the upgrade, at that address too, where another address serves that row and would move it or remove it; and the row a further address serves holds the upgrade, and is the row the precheck names, where its plan would fold, move or remove such a form or a row kept behind it, or write a folded row's withdrawal into either. "Not counted" is asked per package address, as [D5](#d5) asks "served": a package-less row passed over at a writable package's address still holds the upgrade at a read-only base's address whose pair cannot be ensured. - **A seat decision, not the maintainer's words (`7142585849`; in his veto window): the upgrade's move is all-or-nothing with the switch.** A deployment that does not switch holds every stored row as it was. The pre-upgrade release has no `form` type and reads `view` rows only, so a switch-off moved to a `form` row there is read by nothing and the base's form answers. The decision rests on [ruled question 4](#q4). **What keeps a public address closed today, and the rule that carries it.** The break was tried once more for this record across the four stages, for every way a stored row can be the thing that keeps an address closed. Each cell names the rule that holds; "D6-n" is rule n of [D6](#d6). @@ -319,14 +334,16 @@ One path the table does not close, by design: an administrator who resets an ove - **the switched-off form in a record-form slot**: a public form in the container's default `form` slot, link kept and `enabled: false`, whose name is open in another layer. After the source conversion, and after the ceremony on the stored twin (Setup's switch-off override of that form), it is a `form` item with its switch, the internal-forms report does not list it, and both doors still answer `404` (ablate: the `publicLink` test of the internal set — judge "public" by `sharing.enabled === true` — and the form is deleted or left behind with its withdrawal); - **its twin, the link-less row over an open base**: a `.custom` override in the default `form` slot whose body has no `publicLink`, over a base whose default-slot form is open; and the same body as a package-less row. After the source conversion of the pair's own source, and after the ceremony, it is a `form` override with no link, the internal-forms report does not list it, the precheck names no removal for it, and both doors still answer `404` at the base's address (ablate: the base half of the internal test — class the row by its own body alone — and the pin turns red: the report lists the row for removal, and removing it as the report says serves the base's form); - **the ceremony keeps a withdrawal closed**: a form withdrawn before the ceremony — by a `.custom` switch-only override, and by a member of a stored container — answers `404` after it (ablate: the carry of the `sharing` block in the move); -- **the fold keeps the served body and only narrows** (D7-d), five fixtures: +- **the fold keeps the served body and only narrows** (D7-d), six fixtures: - an open override in the pair beside a package-less row that withdraws the form answers `404` before the ceremony and after it, and the destination row keeps its link with the switch off (ablate: the fold's carry of the folded row's switch); - **the row bound to a read-only base**: a row bound to the base whose body has no `publicLink`, over the base's open form, beside a package-less row whose body is open. Both doors answer `404` at the base's address before the ceremony and after it, and the pair's override has no link (ablate: the choice of the kept body — take the package-less row first, as the row that reaches the pair first — and the address answers); - **the writable-base twin**: a writable package's own open row beside a package-less row that withdraws the form. The form is open before the ceremony and answers `404` after it, and the report names it as newly closed (ablate: the report's line for a newly closed form); - **the writable package's list ahead of a form row**: a writable package's own `view` row that carries a list, beside a package-less `view` row of the same name that carries an open form. Both doors answer `404` at the form's address before `--apply` and after it, the package holds no `form` row of the name, the list row is byte-equal, the report names the package-less row as left in place, and the precheck does not hold the upgrade for it (ablate: fold the package-less form row into the package's own `form` row, as a row of that form, and the address answers); - **the no-form row ahead of a form row**: a row bound to the base that carries no form at the name, over the base's open form, beside a package-less row that holds an open form of that name. Both doors answer `404` at the base's address before `--apply` and after it, the pair holds no row of the name, the report names both rows as left in place, and the precheck does not hold the upgrade for them (ablate: leave the no-form row out of the fold — find the served row among form rows only — and the address answers); + - **the internal form ahead of a linked row** (the ruling of 2026-11-29, `7249158572`, D7-d): a writable package's own internal record form (a record-form slot, no link, no action target), beside a package-less row of the same name with a public link, and its twin with that link switched off. Both doors answer `404` at the address before `--apply` and after it, and on major 19; neither row is moved or deleted, the report names both as left in place, and the precheck does not hold the upgrade for them (ablate: the case's predicate, so the internal row is removed and the linked row behind it is served); - each "before" half proves one of this record's readings of today's layers. If one is not as stated here, the card stops and reports; -- **the precheck refuses**: a deployment that holds a stored old-shape form row of each stopping class (pair not ensurable, body not readable) does not reach major 19, and the refusal names the row and its action (`7142585849`, rulings 2 and 3: a movable row is moved and an internal one is removed, so neither is a stopping class); for a row that declares a link or stands over a linked base, the action it names is never a deletion or a reset (ablate: the precheck's read of each class in turn). A list in a package at a form's name is not named by the precheck (ablate: [D5](#d5)'s bound); +- **the row bound to a package that ships no form of its name** (ruling `7250977204`): a row bound to a read-only package that ships no form of the name, with an open link, and a pair's declared override of a base that ships none. Each, alone at its name, moves into the pair as the pair's own `form` item with no `overrides`, and both doors answer byte-equal at its address before `--apply` and after it; together at one name, the override's body is the one kept, the bound row folds into it, and the bound row's body is served neither before nor after (ablate, for the half alone at its name: the destination, as the declared override the other moves take; for the half together at one name: the read of the override at the base's address, so that each row is planned at its own address). The byte-equal claim holds within the ruling's premise; a row the read serves at one other address answers there byte-equal before `--apply` and after it, as the declared override in that base's pair (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842); ablate: the read of the row at the address that serves it, so that it is planned at the package it is bound to). A row the read serves at two addresses is outside this pin's move: it has no destination and holds the upgrade, and so does every row that claims a slot of a pair more than one plan claims, the pair's own row of the name among them: read at the pair's own address, as an old-shape `view` row and as a stored `form` row, it holds beside a row another address plans into that pair, and alone it is planned there and nothing holds (D7; ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661). What holds instead, for each held row: the precheck counts the row and names it once, and a row read at two addresses with both addresses; `--apply` writes nothing while it is stored, every stored row is byte-equal, and both doors answer the same at each address that serves it before the refused run and after it (ablate: the hold's predicate, so that each claimant is planned as a move again). The same is pinned for a row more than one address serves where those addresses would not all move it or all remove it, whatever App each is of: moved at one and left in place at the other, an internal record form ahead of a row that declares a link, at two packages of one App and at packages of two Apps; removed at one and left in place at the other, at two packages of one App and at an App's base beside a package this environment writes; moved at one and held at the other at the pair door, for a cause an administrator removes and for a base whose App cannot be read, where the plan that would move waits on that hold and takes its cause and its action. The precheck counts the row and names it once, nothing is moved or removed, and the action names the App or says where the row is served, and names an exit only where one was measured: a slot two rows claim is told of none (ablate: the predicate that asks every address that serves the row, so that each address is planned by itself again). A held row that stands behind the row a third address moves is listed apart there, and that fold is read without it: its withdrawal is not carried. The control: a row every address would move, each into its own pair, moves at each. Where the package that ships the name ships only a list of it, the plan stops short of that package and keeps the row at the package it is bound to, with no outcome differing; +- **the precheck refuses**: a deployment that holds a stored old-shape form row of each stopping class (pair not ensurable, body not readable), or one held under the ruling of 2026-11-30 (`7265816895`: a slot of a pair more than one plan claims, or a row more than one address serves where those addresses would not all move it or all remove it), or one held under the owning seat's reading of the ruling of 2026-11-29 (`7249158572`) with that one, an exception to that ruling record's "The upgrade is not blocked" (the row an address serves where its plan would fold, move or remove a row another address keeps as stored under that ruling, or write a folded row's withdrawal into it), does not reach major 19, and the refusal names the row and its action (`7142585849`, rulings 2 and 3: a movable row is moved and an internal one is removed, so neither is a stopping class); for a row that declares a link or stands over a linked base, the action it names is never a deletion or a reset (ablate: the precheck's read of each class in turn). A list in a package at a form's name is not named by the precheck (ablate: [D5](#d5)'s bound); - **internal record forms are removed, and only those** (`7142585849`, ruling 3): after the run that switches, a stored internal record form is gone and the report names it with its body; a row with a link, or over a linked base, in the same slot is not removed, and both doors answer at its address as before (ablate: the link test of the internal set, then its base half, and the row is removed); - **the precheck does not hold the two ruled kinds, and their addresses stay closed**: a deployment whose only such rows are a row that carries no form over a linked base, in a binding [D5](#d5) bounds, and a package-less form row behind a writable package's list reaches major 19 with every one of those rows byte-equal, and both doors answer `404` at each address before the upgrade and on the major-19 build (ablate: the kept replacement check's read of a row that carries no form, and the base's address answers on the major-19 build); - **the kept reader still closes after the tombstone**: on a major-19 build, a stored old-shape body that withdraws a form still closes it, a stored old-shape row with no link over a package's open form still keeps that address closed, and so does a stored row that carries no form over it, in a binding [D5](#d5) bounds (ablate: the exempt reader, then its replacement half); @@ -526,8 +543,8 @@ Ruling-ref: [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/ - **The reading, as the first record carries it and the second confirms it.** These rows need no disposition of their own. The ceremony does not move them, the upgrade precheck does not hold major 19 for them, and they stay as stored. - **No form that is closed today opens by it.** The first kind keeps its base's address closed through rule 11's replacement check, which this record keeps after the major ([D7](#d7), "After the major"). The second kind is read by no layer, before the major or after it ([D5](#d5), "served rows only"). -- **What follows in this record, and is this record's own.** [D5](#d5)'s bounded reading and card ②'s refusal last as long as the replacement check, past major 19. The ruling record names two kinds of row; by this record's reading of that answer, a form row left behind a no-form row over a read-only base stays as stored with it and is not held either ([D7](#d7), D7-d). And the answer rests on the replacement check being kept, which is the fifth point of TL;DR 10: striking that point puts this question back. Only this bullet is still open to correction. -- **What a later release owes.** The ruling narrows which rows major 19's precheck counts, and two of the uncounted kinds are old-shape form rows. So the release that one day removes the withdrawal reader, or the replacement check, owes its own answer for these rows: major 19's precheck no longer refuses a deployment that holds them. Nothing opens meanwhile: this record keeps the reader through major 19, and the uncounted form rows are read by no layer or stand behind a row the check keeps closed. +- **What follows in this record, and is this record's own.** [D5](#d5)'s bounded reading and card ②'s refusal last as long as the replacement check, past major 19. The ruling record names two kinds of row; by this record's reading of that answer, a form row left behind a no-form row over a read-only base stays as stored with it and is not held either ([D7](#d7), D7-d). A later ruling (2026-11-29, `7249158572`) adds an uncounted kind beside the two ruled ones and this record's own: an internal record form served ahead of a package-less row that declares a link, with that row; where the linked row behind is any other row, the same answer is this record's reading of that ruling ([D7](#d7), D7-d). And the answer rests on the replacement check being kept, which is the fifth point of TL;DR 10: striking that point puts this question back. Only this bullet is still open to correction. +- **What a later release owes.** The ruling narrows which rows major 19's precheck counts, and two of the uncounted kinds are old-shape form rows. So the release that one day removes the withdrawal reader, or the replacement check, owes its own answer for these rows: major 19's precheck no longer refuses a deployment that holds them. Nothing opens meanwhile: this record keeps the reader through major 19, and the uncounted form rows are read by no layer, stand behind a row the check keeps closed, or (the kind the ruling of 2026-11-29 adds for a package-less row, and this record's reading of it for any other row that declares a link, [D7](#d7), D7-d) stand behind a served internal record form that is not removed. ### 5. The document shape: body at the top level, or under `config` {#q5} @@ -561,7 +578,7 @@ Ruling-ref: [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/ - **A stored row that keeps a public address closed is never set aside as an internal record form**, whether it closes by a switch or by replacing its base's form. The migration moves it, or by the later ruling leaves it as stored, and no report or precheck offers its removal ([D6](#d6) rule 11, [D7](#d7)). Where a form row stands behind a no-form row, removing the row in front before the major serves the row behind it and not the base's form; the report names both. The price is one more read rule for the dual-read period, and a `.custom` source's overrides being moved by the conversion without a look at the base. `os validate` then refuses the one whose base ships no form of that name, so a record form's override does not stay among the `form` items (this record's reading of ruling item 3, [D7](#d7)). - **The ceremony can switch off a public form that is open today.** Where a stored row no layer reads today withdraws a form — a package-less row behind a writable package's own row, or behind a row bound to the base — the fold carries the withdrawal, and the form answers `404` after `--apply`. The report names it as newly closed, and the administrator switches it on again in Setup ([D7](#d7), D7-d). Where several stored rows of one form exist, the one whose body the read serves today is the one kept. - **From card ②, and for as long as rule 11's replacement check is kept, a package-less list is not saved at a name a read-only package authors as a form**, as an item or through a container's expansion. It is a refusal card ② adds and an exception to [D3](#d3) that outlasts major 19. **Some of these saves are admitted today**: where several packages ship the name, where the base has no pair, a re-save of a row its pair already holds, and a container that overlays the package's own container. An administrator who holds such a list can no longer edit it in place once the package authors the form. The door that remains: another key, or the list saved into an app of the environment's own. Card ② is `narrowed` for it. -- **Two kinds of stored row get no disposition of their own** (ruled; [question 4](#q4), the last paragraph after it). A package-less form that no layer reads today, behind a writable package's own list of the same name, stays unread: it is not served from card ②'s release and the ceremony does not move it. A row that carries no form over a linked base — a package-less list that held the name before the package shipped a form under it, say — keeps that form unserved in that deployment for as long as rule 11's replacement check is kept. Both stay as stored, and major 19 is not held for them. Serving the base's form in such a deployment is the administrator's own act on the row; no report prescribes it ([D5](#d5), [D7](#d7)). +- **Two kinds of stored row get no disposition of their own** (ruled; [question 4](#q4), the last paragraph after it; beside them and this record's own kind, an internal record form served ahead of a package-less row that declares a link, with that row, by the ruling of 2026-11-29, and ahead of any other row that declares one, by this record's reading of that ruling; [D7](#d7), D7-d). A package-less form that no layer reads today, behind a writable package's own list of the same name, stays unread: it is not served from card ②'s release and the ceremony does not move it. A row that carries no form over a linked base — a package-less list that held the name before the package shipped a form under it, say — keeps that form unserved in that deployment for as long as rule 11's replacement check is kept. Both stay as stored, and major 19 is not held for them. Serving the base's form in such a deployment is the administrator's own act on the row; no report prescribes it ([D5](#d5), [D7](#d7)). - **One arrangement served today is refused once it is in the new type**: a retired form that keeps its link beside its successor on the same address. The author clears the retired form's link ([question 3](#q3), this record's reading of "holds"). - **`defineForm` changes meaning** in card ② ([ruled question 1](#q1)): a declared, compiler-carried export break, on the premise that its outside use is platform-internal. The 17 Studio form modules change file suffix in the same card ([D2](#d2), the seat's routing). - **First-party work**: about 100 non-test source files and about 160 test files name the old shapes; they move in ②, ③ and ④ and the remainder falls to ⑤. diff --git a/docs/qa/platform-checklist/areas/cli.json b/docs/qa/platform-checklist/areas/cli.json index a96c86d011c..374934e4074 100644 --- a/docs/qa/platform-checklist/areas/cli.json +++ b/docs/qa/platform-checklist/areas/cli.json @@ -2776,6 +2776,87 @@ } ] }, + { + "id": "cli.stored-forms-census-and-precheck", + "title": "`os migrate stored-forms` lists, read-only, what the upgrade to the next protocol major does with each stored old-shape form row — kept, moved, folded, removed as an internal record form, left in place, or holding the upgrade — and whether the upgrade can switch", + "since": "v18", + "status": "active", + "revision": 1, + "priority": "P1", + "surface": "cli", + "personas": [ + "operator (runs the CLI against the deployment's database before upgrading)" + ], + "fixtures": { + "app": "showcase", + "requires": [ + "a showcase database of the run's own (dogfood §0); the CLI from this tree (`os` / `node packages/cli/bin/run.js`)", + "the stock read-only base com.example.showcase (examples/app-showcase/objectstack.config.ts) and a form it ships in an old shape or as a `form` item, named FORM" + ], + "knownGaps": [ + "The rows the census classifies are rows an older release left: a run stages them with the server stopped, as the command's integration test does (packages/cli/src/commands/migrate/stored-forms.integration.test.ts): insert into sys_metadata a row with type 'view', state 'active', version 1 and an old-shape form body (a `viewKind: 'form'` item named FORM, or a container with a `form` or `formViews` entry) bound to no package or to com.example.showcase. Without one, only acceptance[0] runs" + ] + }, + "steps": [ + "empty census: on a fresh showcase DB, run `os migrate stored-forms --json`; record the exit code, canSwitch and that nothing was written", + "stage a package-less `viewKind: 'form'` row named FORM with a sharing.publicLink (fixtures.knownGaps[0]); run `os migrate stored-forms --json` again and read the plan for FORM at com.example.showcase", + "stage a second row whose form content cannot be read (a `viewKind: 'form'` item with no `config`); run the census again; boot the server and read its start-up log", + "run `os migrate stored-forms` (text) and read the summary line and each row's sentence" + ], + "acceptance": [ + { + "clause": "the census is read-only: with nothing stored it lists nothing, says the upgrade can switch, and exits 0", + "oracle": "build", + "verify": "step 1: exit 0, canSwitch true, forms []; the sys_metadata and sys_packages contents are unchanged", + "evidence": "the JSON output + exit code + the before/after store reads" + }, + { + "clause": "a linked package-less form row over a shipped form is listed as moving into the base's .custom pair as a declared override, and nothing is written", + "oracle": "build", + "verify": "step 2: FORM at base com.example.showcase reads outcome move, destination pair_override com.example.showcase.custom with basedOn the base's version; canSwitch true; the store is unchanged", + "evidence": "the census JSON + the store read" + }, + { + "clause": "a body the projection cannot read holds the upgrade, and the start-up message names this command", + "oracle": "build", + "verify": "step 3: unreadable lists the row with cause unreadable and the repair action; canSwitch false; the boot log's error line for the row names `os migrate stored-forms`", + "evidence": "the census JSON + the boot log line" + }, + { + "clause": "the text report names each row with its outcome and ends with the counts and the switch verdict", + "oracle": "build", + "verify": "step 4: one line per form and address; the last lines read the counts and 'The upgrade would not switch: 1 row(s) hold it'", + "evidence": "the text output" + } + ], + "negative": [ + "a census that writes a row, creates a .custom package or offers deletion for a row that declares a public link is the FAIL: the command is read-only, and deleting a switched-off form's row switches it back on (ADR-0159 D7-e)" + ], + "traps": [ + "destructive-in-place", + "silent-coercion" + ], + "automated": { + "kind": "unit", + "ref": "packages/metadata-protocol/src/protocol-stored-form-migration.test.ts (the planner: each outcome and hold cause on its seed fixture) + packages/objectql/src/protocol-stored-form-migration.test.ts (the census over the real protocol: acceptance[1]–[2]) + packages/cli/src/commands/migrate/stored-forms.integration.test.ts (the CLI over a seeded database: acceptance[0]–[2]; integration tier) + packages/rest/src/public-form-two-type-withdrawal.test.ts pin 6 (the start-up message names the command)" + }, + "source": [ + "packages/cli/src/commands/migrate/stored-forms.ts#storedFormPlanText (the command; --json, --database-url, --preset, --dev)", + "packages/metadata-protocol/src/protocol-stored-form-migration.ts#planStoredForms (keep, move, remove, hold, left_in_place)", + "packages/metadata-protocol/src/protocol-stored-form-migration.ts#INTERNAL_AHEAD_OF_LINKED_ROW (the one place the internal-ahead-of-linked case is decided)", + "packages/metadata-protocol/src/protocol-form-reads.ts#readUnreadableFormBodies (the start-up message)", + "docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md D7 (the ceremony, D7-a to D7-e)", + "#37111 (ADR-0159 card ⑤a)" + ], + "history": [ + { + "revision": 1, + "date": "2026-11-29", + "change": "new item (ADR-0159 card ⑤a #37111, PR 1): the read-only census and precheck of the stored-form ceremony. Read from source at base 5df10ecc", + "ref": "#37111" + } + ] + }, { "id": "cli.address-grammar-reserved-names", "title": "The address grammar reserves its segments: a bucket 2/3 name led by _ is refused at defineStack and os validate; a namespace that spells a grammar literal is refused by os validate and os build (exit 1, no artifact) and at the running install door, while a package the boot registers keeps booting with a warning; and lint's namespace-prefix rule judges only capabilities and positions", diff --git a/packages/cli/src/commands/migrate/stored-forms.integration.test.ts b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts new file mode 100644 index 00000000000..39648eaec7d --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts @@ -0,0 +1,242 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os migrate stored-forms` against a real SQLite database: the read-only run + * of the stored-form ceremony (ADR-0159 D7, card ⑤a). + * + * ## The fixture + * + * A compiled artifact (`dist/objectstack.json`) whose package ships an object + * and a linked public form in an old shape (`formViews.contact`), over a + * database an older release left behind with, bound to no package: + * + * - a `viewKind: 'form'` row of the package's form that switches it off + * (moves into the package's pair as a declared override); + * - a `viewKind: 'form'` row whose form content cannot be read (holds the + * upgrade). + * + * The command runs in-process through oclif, as the binary runs it. The + * census writes nothing: the stored rows and `sys_packages` read the same + * after it, and no pair is created. + */ + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { isExitSignal } from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import MigrateStoredForms from './stored-forms.js'; + +// [#10126] Pay the first transform of these dist-resolved workspace deps at +// MODULE LOAD: the command reaches them through dynamic `import()`s inside +// `run()`, which vitest clocks (`scripts/check-test-source-alias.mjs`). +import '@objectstack/runtime'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/rest'; +import '@objectstack/plugin-security'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 180_000; + +const PKG = 'com.example.m37111'; +const PAIR = `${PKG}.custom`; +const OBJECT = 'm37111_inquiry'; +const FORM = `${OBJECT}.contact`; +const BROKEN = `${OBJECT}.broken`; +const SLUG = 'contact-m37111'; +const formBody = (enabled: boolean) => ({ + type: 'simple', + sections: [{ fields: ['name'] }], + data: { provider: 'object', object: OBJECT }, + sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true }, +}); +const ARTIFACT = { + manifest: { id: PKG, name: 'm37111', version: '2.3.0', type: 'app', namespace: 'm37111' }, + objects: [{ + name: OBJECT, + label: 'Inquiry', + sharingModel: 'private', + fields: { name: { name: 'name', label: 'Name', type: 'text' } }, + }], + views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: formBody(true) } }], +}; + +interface SeedRow { type: string; name: string; state: string; body: Record; packageId?: string } +const SEED: SeedRow[] = [ + { type: 'view', name: FORM, state: 'active', body: { name: FORM, object: OBJECT, viewKind: 'form', label: 'Switched off', config: formBody(false) } }, +]; +const BROKEN_SEED: SeedRow = { + type: 'view', name: BROKEN, state: 'active', + body: { name: BROKEN, object: OBJECT, viewKind: 'form', sharing: { publicLink: `/forms/${SLUG}`, enabled: true } }, +}; + +let dir: string; +let emptyDb: string; +let templateDb: string; +let brokenTemplateDb: string; +const savedCwd = process.cwd(); +const ENV_KEYS = ['OS_ARTIFACT_PATH', 'OS_DATABASE_URL', 'DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'NODE_ENV', + 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ENVIRONMENT_ID'] as const; +const savedEnv: Record = {}; + +let caseSeq = 0; +function caseDb(template: string): string { + caseSeq += 1; + const file = join(dir, 'cases', `${caseSeq}.db`); + mkdirSync(dirname(file), { recursive: true }); + copyFileSync(template, file); + return file; +} + +/** The rows an older release left, written at the driver the way that release stored them. */ +async function insertRows(dbFile: string, rows: readonly SeedRow[]): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + try { + const k = (driver as any).knex; + const now = new Date().toISOString(); + let n = 0; + for (const row of rows) { + n += 1; + await k('sys_metadata').insert({ + id: `seed_${n}`, type: row.type, name: row.name, package_id: row.packageId ?? null, state: row.state, + version: 1, checksum: null, created_at: now, updated_at: now, metadata: JSON.stringify(row.body), + }); + } + } finally { + await driver.disconnect(); + } +} + +/** Every `sys_metadata` row and every `sys_packages` id, read on a connection of our own. */ +async function storeSnapshot(dbFile: string): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + try { + const k = (driver as any).knex; + const rows = await k('sys_metadata').select('type', 'name', 'package_id', 'state', 'metadata'); + const packages = await k('sys_packages').select('id').catch(() => []); + return JSON.stringify([ + rows.map((r: any) => `${r.type}/${r.name}@${r.package_id ?? '-'}/${r.state} ${r.metadata}`).sort(), + packages.map((r: any) => String(r.id)).sort(), + ]); + } finally { + await driver.disconnect(); + } +} + +interface RunResult { payload: any; exitCode: number } + +/** Run the command through oclif and capture its one JSON document. */ +async function runJson(argv: string[]): Promise { + const savedExit = process.exitCode; + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + let thrownExit: number | undefined; + try { + try { + await MigrateStoredForms.run(argv, { root: CLI_ROOT }); + } catch (error) { + if (!isExitSignal(error)) throw error; + thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; + } + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); + let payload: any; + try { payload = JSON.parse(out); } catch { payload = { unparsed: out.slice(-400) }; } + return { payload, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; + } finally { + process.exitCode = savedExit; + vi.restoreAllMocks(); + } +} + +beforeAll(async () => { + for (const key of ENV_KEYS) savedEnv[key] = process.env[key]; + for (const key of ENV_KEYS) delete process.env[key]; + process.env.NODE_ENV = 'production'; + dir = mkdtempSync(join(tmpdir(), 'os-37111-')); + mkdirSync(join(dir, 'dist'), { recursive: true }); + process.env.OS_HOME = join(dir, 'home'); + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + writeFileSync(process.env.OS_ARTIFACT_PATH, JSON.stringify(ARTIFACT)); + + emptyDb = join(dir, 'empty.db'); + const seed = await bootSchemaStack({ jsonOutput: false, databaseUrl: `file:${emptyDb}`, projectRoot: dir, hydrateMetadata: false }); + await seed.shutdown(); + templateDb = join(dir, 'template.db'); + copyFileSync(emptyDb, templateDb); + await insertRows(templateDb, SEED); + brokenTemplateDb = join(dir, 'broken-template.db'); + copyFileSync(emptyDb, brokenTemplateDb); + await insertRows(brokenTemplateDb, [...SEED, BROKEN_SEED]); +}, CASE_TIMEOUT_MS); + +afterAll(() => { + process.chdir(savedCwd); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ } +}); + +// The command takes `process.cwd()` as the project root, as a real invocation does. +beforeEach(() => { process.chdir(dir); }); +afterEach(() => { process.chdir(savedCwd); }); + +describe('os migrate stored-forms', () => { + it('on a database with no stored form lists nothing, says the upgrade can switch, and exits 0', async () => { + const db = caseDb(emptyDb); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload.canSwitch).toBe(true); + expect(payload.forms).toEqual([]); + expect(payload.holds).toEqual([]); + }, CASE_TIMEOUT_MS); + + it('lists the package-less switch-off row as moving into the pair as a declared override, and writes nothing', async () => { + const db = caseDb(templateDb); + const before = await storeSnapshot(db); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + const plan = payload.forms.find((f: any) => f.form === FORM); + expect(plan).toMatchObject({ + address: { kind: 'base', packageId: PKG }, + outcome: 'move', + destination: { kind: 'pair_override', base: PKG, pair: PAIR, basedOn: '2.3.0' }, + served: { type: 'view', name: FORM, withdraws: SLUG }, + }); + expect(payload.canSwitch).toBe(true); + expect(await storeSnapshot(db)).toBe(before); + }, CASE_TIMEOUT_MS); + + it('a body the projection cannot read holds the upgrade: canSwitch false, the row named with its action, still exit 0', async () => { + const db = caseDb(brokenTemplateDb); + const before = await storeSnapshot(db); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload.canSwitch).toBe(false); + expect(payload.holds).toEqual([expect.objectContaining({ + cause: 'unreadable', + row: expect.objectContaining({ name: BROKEN }), + action: expect.stringContaining('Save the view again'), + })]); + expect(await storeSnapshot(db)).toBe(before); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/stored-forms.ts b/packages/cli/src/commands/migrate/stored-forms.ts new file mode 100644 index 00000000000..16c92dfd8a9 --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -0,0 +1,323 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Command, Flags } from '@oclif/core'; +import chalk from 'chalk'; +import { STACK_TIER_PRESETS } from '@objectstack/core'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + createTimer, + emitJson, + errorCodeFields, + isExitSignal, +} from '../../utils/format.js'; +import type { + StoredFormAddress, + StoredFormAddressPlan, + StoredFormCensus, + StoredFormHold, + StoredFormRowRef, +} from '@objectstack/metadata-protocol'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { describeUnloadableHostConfig } from '../../utils/schema-migration-plugins.js'; +import { absentTableReads } from '../../utils/absent-table-reads.js'; +import { probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; +import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; + + +const EMPTY: StoredFormCensus = { + forms: [], + unreadable: [], + drafts: [], + sharedSlugs: [], + precheck: { canSwitch: true, holds: [], counts: { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 } }, +}; + +/** One row as the report names it. */ +export function storedFormRowText(row: StoredFormRowRef): string { + const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; + const member = row.name !== row.form ? ` (member '${row.form}')` : ''; + return `${row.type} "${row.name}"${member}, ${where}`; +} + +/** An address as the report names it. */ +export function storedFormAddressText(address: StoredFormAddress): string { + switch (address.kind) { + case 'base': return `at read-only package '${address.packageId}'`; + case 'package': return `at package '${address.packageId}'`; + case 'environment': return 'in the environment (no package ships it)'; + } +} + +/** What the ceremony does at one address, in one sentence. */ +export function storedFormPlanText(plan: StoredFormAddressPlan): string { + return storedFormPlanSentence(plan) + + (plan.untouched.length > 0 ? `; ${plan.untouched.length} row(s) behind it that hold no form at the name stay as stored` : '') + + plan.alsoReadAt.map((e) => `; ${storedFormRowText(e.row)} is also read ${storedFormAddressText(e.address)}, where it ${e.served ? 'is served and ' : 'stands behind, and the address '}${OUTCOME_WORD[e.outcome]}`).join(''); +} + +const OUTCOME_WORD: Record = { + keep: 'is kept', + move: 'moves', + remove: 'is removed', + hold: 'holds the upgrade', + left_in_place: 'is left in place', +}; + +/** A held row is folded into no other row (ADR-0159 D7): the report names it apart. */ +function heldApartText(rows: readonly StoredFormRowRef[] | undefined): string { + return rows !== undefined && rows.length > 0 + ? `; not folded into it while it holds the upgrade where it is served, and this line stands only while that hold does: ${rows.map(storedFormRowText).join('; ')}` + : ''; +} + +function storedFormPlanSentence(plan: StoredFormAddressPlan): string { + const folded = plan.behind.length > 0 ? `; ${plan.behind.length} form row(s) behind it fold into it` : ''; + switch (plan.outcome) { + case 'keep': + return `kept: ${storedFormRowText(plan.served)} is already the form row${folded}${heldApartText(plan.heldApart)}` + + (plan.carries ? `; it takes the withdrawal of ${storedFormRowText(plan.carries.from)}` : '') + + (plan.newlyClosed ? ` — NEWLY CLOSED: /forms/${plan.carries?.slug} is open today and answers 404 after the upgrade; switch it on again in Setup if it should stay open` : ''); + case 'move': { + const to = plan.destination.kind === 'pair_override' + ? `the declared override in '${plan.destination.pair}' (overrides '${plan.destination.base}', basedOn ${plan.destination.basedOn})` + : plan.destination.kind === 'pair_form' + ? `a form of '${plan.destination.pair}' of its own, declaring no override ('${plan.destination.base}' ships no form of the name)` + : plan.destination.kind === 'package_form' + ? `a form row of package '${plan.destination.packageId}'` + : 'a form row of the environment'; + return `moves: ${storedFormRowText(plan.served)} → ${to}, its body as written${folded}${heldApartText(plan.heldApart)}` + + (plan.carries ? `; it takes the withdrawal of ${storedFormRowText(plan.carries.from)}` : '') + + (plan.draftsLeftBehind && plan.draftsLeftBehind.length > 0 ? `; its draft is left behind as stored, and cannot be published after the upgrade` : '') + + (plan.newlyClosed ? ` — NEWLY CLOSED: /forms/${plan.carries?.slug} is open today and answers 404 after the upgrade; switch it on again in Setup if it should stay open` : ''); + } + case 'remove': + return `will be removed: ${storedFormRowText(plan.served)} is an internal record form (no public link, no action opens it)` + + (plan.behind.length > 0 ? `, with the ${plan.behind.length} form row(s) behind it` : '') + // A row behind that another address serves is not part of the removal (ADR-0159 D7-e). + + (plan.servedElsewhere !== undefined && plan.servedElsewhere.length > 0 + ? `; not removed with it, because another address serves it: ${plan.servedElsewhere.map(storedFormRowText).join('; ')}` + : '') + + (plan.object !== undefined + ? `. New and Edit of '${plan.object}' follow its field groups, ${plan.objectHasFieldGroups ? 'which it declares' : 'and it declares none'}` + : ''); + case 'hold': + return `HOLDS THE UPGRADE: ${storedFormRowText(plan.served)} — ${plan.refusal} ${plan.action}` + // A row kept as stored at another address under ruling 7249158572 is listed apart, whatever this plan holds for. + + (plan.heldApart !== undefined && plan.heldApart.length > 0 + ? ` Listed apart, kept as stored at another address under ruling 7249158572: ${plan.heldApart.map(storedFormRowText).join('; ')}.` + : ''); + case 'left_in_place': + switch (plan.reason) { + case 'served_no_form': + return `left in place: ${storedFormRowText(plan.served)} carries no form at the name and is the row served for it, so nothing is served for the name today and no row of it moves` + + (plan.behind.length > 0 ? ` (${plan.behind.map(storedFormRowText).join('; ')})` : ''); + case 'internal_ahead_of_linked_row': + 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)`; + } + } +} + +function holdText(hold: StoredFormHold): string { + return `${storedFormRowText(hold.row)}${hold.base !== undefined ? ` over '${hold.base}'` : ''} — ${hold.refusal} ${hold.action}`; +} + +/** + * `os migrate stored-forms` — the read-only run of the stored-form ceremony + * (ADR-0159 D7, card ⑤a): what the upgrade to the next protocol major does with + * every stored row that holds a form in an old shape (a `view` container's + * `form`, a `formViews` entry, a `viewKind: 'form'` item), and the precheck — + * whether that upgrade may switch. + * + * ## Why read-only + * + * The ceremony moves rows between two types, so it is all or nothing with the + * switch to the major: its write is reached only from the major's upgrade + * command, which runs the ceremony and then the precheck, and switches only + * when no row holds it (ruling `7142585849` 2, addendum `7142658348`). This + * command is the administrator's look before upgrading. ⛔ It has no + * `--apply`. + * + * ## What it says + * + * Per form name and package address (the census of `listStoredFormsOf`, + * `@objectstack/metadata-protocol`, whose module header holds the rules): + * kept, moved (and where), removed (an internal record form), left in place, + * or holding the upgrade — a row whose base's pair cannot be ensured, a body + * the projection cannot read, a slot of a pair more than one plan claims, or + * a row several addresses serve that would not all move it or all remove it, + * each with its cause and the action for it. The rows behind the served one + * fold into it, except a row that holds the upgrade, which the report lists + * apart; a withdrawal a folded row + * carries that no layer reads today closes a form that is open today, and the + * report names it newly closed. + * + * The deployment is composed as `os serve` composes it — the host config's + * plugins and the application or the compiled artifact — so the packages that + * ship a form are the ones the server serves. `--preset` and `--dev` are + * `serve`'s two flags that move that composition, with its meaning. The boot + * is read-only (deferred DDL, no seed, no file brought into existence). + * + * Exit status: 0 when the census ran, whatever it found (`precheck.canSwitch` + * in `--json` says whether the upgrade would switch); 1 when the composition + * could not be read or booted. + */ +export default class MigrateStoredForms extends Command { + static override description = + 'List what the upgrade to the next protocol major does with the stored rows that hold a form in an old shape ' + + '(a view container\'s form, a formViews entry, a viewKind: \'form\' item), and whether it can switch: the rows ' + + 'it moves, folds and removes, and the rows that hold it, with the action for each (ADR-0159 D7). Read-only.'; + + static override examples = [ + '$ os migrate stored-forms', + '$ os migrate stored-forms --json', + ]; + + static override flags = { + 'database-url': Flags.string({ + description: 'Database to examine (defaults to $OS_DATABASE_URL / the project DB)', + env: 'OS_DATABASE_URL', + }), + json: Flags.boolean({ description: 'Output the machine-readable result as JSON.' }), + preset: Flags.string({ + description: 'Compose as `os serve --preset` does: the tier preset the stack falls back to when it declares ' + + 'no tiers. Pass what the deployment boots with.', + options: Object.keys(STACK_TIER_PRESETS), + }), + dev: Flags.boolean({ + description: 'Compose as `os serve --dev` does: the config\'s devPlugins and the development .env files. ' + + 'Pass it when the deployment boots with --dev (`os dev`).', + }), + }; + + async run(): Promise { + const { flags } = await this.parse(MigrateStoredForms); + const timer = createTimer(); + if (!flags.json) printHeader('Migrate · stored-forms'); + + const occupancy = await probeMigrationTarget(flags['database-url'], { dev: flags.dev === true }); + if (occupancy.status === 'busy' && !flags.json) { + printWarning(`${describeOccupancy(occupancy)} The census below writes no row or table. ${JOURNAL_MODE_SWITCH_NOTE}`); + } + if (occupancy.status === 'unknown' && !flags.json) { + printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); + } + if (!flags.json) printStep('Composing the deployment (read-only)…'); + + let stack; + try { + stack = await bootSchemaStack({ + jsonOutput: flags.json, + ...(flags['database-url'] ? { databaseUrl: flags['database-url'] } : {}), + composeHostStack: true, + composeAuthGatedSecurity: true, + serveFlags: { dev: flags.dev === true, ...(flags.preset ? { preset: flags.preset } : {}) }, + deferSchemaDdl: true, + readOnlyProbe: true, + }); + } catch (error: any) { + if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); return; } + printError(error.message || String(error)); + this.exit(1); + return; + } + + let exitCode = 0; + try { + exitCode = await this.report(stack, flags.json === true, timer); + } catch (error: any) { + if (isExitSignal(error)) throw error; + exitCode = 1; + if (flags.json) await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); + else printError(error.message || String(error)); + } finally { + await stack.shutdown(); + } + if (exitCode !== 0) this.exit(exitCode); + } + + private async report( + stack: Awaited>, + json: boolean, + timer: { elapsed: () => number; display: () => string }, + ): Promise { + const unloadable = describeUnloadableHostConfig(stack.composition); + if (unloadable !== null) { + if (json) await emitJson({ error: 'host_config_unloadable', message: unloadable }, 0, { compact: true }); + else printError(unloadable); + return 1; + } + const protocol = stack.kernel.getService('protocol') as object | undefined; + // The census reads the protocol instance through its host (`listStoredFormsOf`, + // `@objectstack/metadata-protocol`): a function beside the facade, not a method on it. + const { listStoredFormsOf } = await import('@objectstack/metadata-protocol'); + if (typeof (protocol as { getMetaItems?: unknown } | undefined)?.getMetaItems !== 'function') { + throw new Error( + 'No metadata protocol on this stack, so sys_metadata cannot be read. ' + + 'Run this from the project root whose stack registers the ObjectQL engine.', + ); + } + const reads = absentTableReads(stack); + const census = reads.absent('sys_metadata') ? EMPTY : await listStoredFormsOf(protocol as Parameters[0]); + const { precheck } = census; + + if (json) { + reads.notice(true); + await emitJson({ + database: stack.dbLabel, + hostConfig: stack.composition.hostConfigPath, + canSwitch: precheck.canSwitch, + counts: precheck.counts, + holds: precheck.holds, + forms: census.forms, + unreadable: census.unreadable, + drafts: census.drafts, + sharedSlugs: census.sharedSlugs, + duration: timer.elapsed(), + }); + return 0; + } + + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + if (stack.composition.hostConfigPath) printInfo(`Host config: ${chalk.white(stack.composition.hostConfigPath)}`); + reads.notice(false); + console.log(''); + if (census.forms.length === 0 && census.unreadable.length === 0 && census.drafts.length === 0) { + printSuccess(`No stored row holds a form in an old shape — nothing for the upgrade to move ${chalk.dim(`(${timer.display()})`)}`); + return 0; + } + if (census.forms.length > 0) { + console.log(chalk.bold(`${census.forms.length} form(s) in stored rows:`)); + for (const plan of census.forms) console.log(` • '${plan.form}' ${storedFormAddressText(plan.address)}: ${storedFormPlanText(plan)}`); + console.log(''); + } + if (census.unreadable.length > 0) { + console.log(chalk.bold(`${census.unreadable.length} stored view(s) whose form content cannot be read (each holds the upgrade):`)); + for (const hold of census.unreadable) console.log(` • ${holdText(hold)}`); + console.log(''); + } + if (census.drafts.length > 0) { + console.log(chalk.bold(`${census.drafts.length} draft view row(s) with form content in an old shape, neither moved nor deleted. After the upgrade an old-shape draft cannot be published: publish the ones you want to keep first.`)); + for (const d of census.drafts) console.log(` • ${d.type} "${d.name}", ${d.packageId !== undefined ? `package '${d.packageId}'` : 'no package'}`); + console.log(''); + } + for (const shared of census.sharedSlugs) { + printInfo(`/forms/${shared.slug} is declared by ${shared.forms.map((f) => `'${f}'`).join(' and ')}.`); + } + 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) { + 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). + printWarning(`The upgrade would not switch: ${precheck.holds.length} row(s) hold it. Each is listed above with the action for its cause.`); + } + return 0; + } +} diff --git a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts index 3906676160a..81eb863461d 100644 --- a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts +++ b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts @@ -99,6 +99,7 @@ import MigrateRecordedBy from '../commands/migrate/recorded-by.js'; import MigrateResume from '../commands/migrate/resume.js'; import MigrateSecurityCatalogOverlays from '../commands/migrate/security-catalog-overlays.js'; import MigrateStoredExpressions from '../commands/migrate/stored-expressions.js'; +import MigrateStoredForms from '../commands/migrate/stored-forms.js'; import MigrateStoredReferences from '../commands/migrate/stored-references/index.js'; import MigrateStoredReferencesBind from '../commands/migrate/stored-references/bind.js'; import MigrateSummaryNulls from '../commands/migrate/summary-nulls.js'; @@ -396,6 +397,12 @@ const CALLERS: Record = { noWrite: [{ label: 'migrate stored-expressions', argv: ['--database-url', '@DB@', '--json'] }], write: [{ label: 'migrate stored-expressions --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], }, + 'commands/migrate/stored-forms.ts': { + run: invoke(MigrateStoredForms), + noWrite: [{ label: 'migrate stored-forms', argv: ['--database-url', '@DB@', '--json'] }], + write: [], + note: 'report-only: it has no writing mode', + }, 'commands/migrate/stored-references/index.ts': { run: invoke(MigrateStoredReferences), noWrite: [{ label: 'migrate stored-references', argv: ['--database-url', '@DB@', '--json'] }], diff --git a/packages/cli/test/json-stdout-purity.e2e.test.ts b/packages/cli/test/json-stdout-purity.e2e.test.ts index 72e7eace391..a7c0e16a683 100644 --- a/packages/cli/test/json-stdout-purity.e2e.test.ts +++ b/packages/cli/test/json-stdout-purity.e2e.test.ts @@ -188,6 +188,10 @@ const FAMILY: Record = { 'migrate security-catalog-overlays': [], // Its dry run takes the `summary-nulls` shape: a read-only boot, no row written. 'migrate stored-expressions': [], + // [ADR-0159 D7] Read-only, its only form: it boots as `os serve` composes + // (`deferSchemaDdl` + `readOnlyProbe`) and reports. No table exists in the + // fixture, so the face driven here is its empty census. + 'migrate stored-forms': [], // [ADR-0150 D10] Read-only, its only form: it boots as `os serve` composes // (`deferSchemaDdl` + `readOnlyProbe`) and reports. Its `bind` declares no // `json:` literal of its own (it spreads the report's flags), so this diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 09b8f0a7af8..cd2b235af93 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -348,6 +348,22 @@ export { isServedOverrideRowOf } from './served-override.js'; export type { ServedOverrideRow } from './served-override.js'; export type { ServedOverrideEntry } from './protocol-served-overrides.js'; export type { PackagelessOverlayCensus, PackagelessOverlayMigration } from './protocol-packageless-overlay-migration.js'; +// [ADR-0159 D7, card ⑤a] The stored-form ceremony's census and precheck: `os migrate stored-forms` prints them. +export { listStoredFormsOf } from './protocol-stored-form-migration.js'; +export type { + StoredFormAddress, + StoredFormAddressPlan, + StoredFormCarriedWithdrawal, + StoredFormCensus, + StoredFormDestination, + StoredFormDraft, + StoredFormElsewhere, + StoredFormHold, + StoredFormHoldCause, + StoredFormLeftReason, + StoredFormPrecheck, + StoredFormRowRef, +} from './protocol-stored-form-migration.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-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 84a0d368da7..816cf86d0ec 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -48,6 +48,7 @@ import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, projectViewForms, import { installedManifestsOfEngine } from './installed-manifests.js'; import type { ProtocolHost } from './protocol-host.js'; import { holdsServedOverlayCandidate, servedOverlayRowCandidates } from './protocol-overlay-merge.js'; +import type { ShipsName } from './suite-moved-overlay.js'; import type { StoredOverlayEntry } from './protocol-stored-overlay-types.js'; /** What one stored row holds at a form's name, as the `form` read reads it. */ @@ -56,7 +57,7 @@ export type StoredHolding = | { readonly kind: 'closed'; readonly reason: 'list' | 'unreadable' }; /** One stored row of either type, with its binding and what it holds per name. */ -interface StoredFormPlace { +export interface StoredFormPlace { readonly type: 'form' | 'view'; readonly packageId: string | undefined; readonly entry: StoredOverlayEntry; @@ -240,8 +241,12 @@ export function storedViewRowHoldings( return holds; } -/** Every stored row of both types as a {@link StoredFormPlace}. */ -async function storedFormPlaces(host: FormReadHost): Promise { +/** + * Every stored row of both types as a {@link StoredFormPlace}: the rows the + * `form` read resolves over, and the population of the stored-form ceremony + * (`protocol-stored-form-migration.ts`), so the two read one set. + */ +export async function storedFormPlaces(host: FormReadHost): Promise { const places: StoredFormPlace[] = []; for (const entry of await storedEntries(host, 'form')) { const name = typeof entry.data?.name === 'string' && entry.data.name !== '' ? entry.data.name : entry.name; @@ -265,36 +270,94 @@ async function storedFormPlaces(host: FormReadHost): Promise return places; } +/** One stored row in a served-row order: the place, what it holds at the name, and the base it overrides. */ +export interface OrderedFormRow { + readonly holding: StoredHolding; + readonly place: StoredFormPlace; + readonly overrideOf?: string; + /** + * [ADR-0159 D7, ruling record 7254350842] The row is one the read serves + * at this address although it is stored against another package of the + * App (`suite-moved-overlay.ts`): `'override'`, a declared override of + * that package in the App's pair; `'base'`, a row bound to it. Set only + * when the order is asked with `ships`. + */ + readonly moved?: 'override' | 'base'; +} + /** - * [ADR-0159 D5, rule 11] The stored row the served-row order picks for `name` - * at `packageId`'s address, over both types: `undefined` when no place holds a - * row of the name (the package's source item is served). + * [ADR-0159 D5, D7-d] Every stored row of `name` at `packageId`'s address, in + * the served-row order, over both types: the pair's override, then the row + * bound to the package, then the package-less row + * ({@link servedOverlayRowCandidates}); at one place a stored `form` row + * before a stored `view` row, an item row before a container's expansion. The + * first is the served row ({@link servedFormHolding}); the rest are the rows + * the stored-form ceremony folds behind it. `packageId` `null` is the + * environment's own address: the package-less rows alone. + * + * `admits`, when given, narrows the places the order is asked over (the + * ceremony keeps each row to the addresses its binding names). `ships`, when + * given, asks the order the served `view` list takes with it + * ({@link servedOverlayRowCandidates}): a stored `view` item row stored + * against another package of `packageId`'s App is a candidate too, each + * marked `moved`; a row bound to such a package only when it is the one such + * row among `places`, as the list's merge serves it. Only an item row of the + * `view` type is such a candidate: the list serves a container's expansion + * in its own package's slot, or as a package-less stand-in. The `form` read + * asks without it, as before. */ -export function servedFormHolding( +export function orderedFormRowsAt( places: readonly StoredFormPlace[], name: string, - packageId: string, + packageId: string | null, installed: InstalledManifestLookup, -): { holding: StoredHolding; place: StoredFormPlace; overrideOf?: string } | undefined { - for (const candidate of servedOverlayRowCandidates({ packageId, servedOverride: true, installed })) { + admits?: (place: StoredFormPlace) => boolean, + ships?: ShipsName, +): OrderedFormRow[] { + const out: OrderedFormRow[] = []; + const seen = new Set(); + const address = ships === undefined ? { packageId, servedOverride: true, installed } : { packageId, servedOverride: true, installed, ships }; + for (const candidate of servedOverlayRowCandidates(address)) { // Both spellings are read as one: the `form` read parses rows of // either spelling of its type, and the spelling decides nothing here. if (candidate.spelling === 'other') continue; - const at = places.filter((place) => place.holds.has(name) + const at = places.filter((place) => !seen.has(place) && place.holds.has(name) + && (admits === undefined || admits(place)) + && (candidate.moved === undefined || (place.type !== 'form' && place.grain === 'item')) && (candidate.packageId === undefined || (place.packageId ?? null) === candidate.packageId) && holdsServedOverlayCandidate(candidate, - { type: place.entry.type, package_id: place.packageId ?? null, metadata: place.entry.data }, installed, undefined)); + { type: place.entry.type, package_id: place.packageId ?? null, metadata: place.entry.data }, installed, ships)); + // Two rows that could each follow the item here: the read serves + // neither (`mergePackageAwareOverlay`), so neither is a row of this address. + if (candidate.moved === 'base' && at.length > 1) continue; // A stored `form` row wins over a stored `view` row at the same place; // an item row over a container's expansion. const rank = (place: StoredFormPlace): number => (place.type === 'form' ? 0 : place.grain === 'item' ? 1 : 2); - const hit = [...at].sort((a, b) => rank(a) - rank(b))[0]; - if (hit !== undefined) { - return candidate.overrideOf === undefined + for (const hit of [...at].sort((a, b) => rank(a) - rank(b))) { + seen.add(hit); + const row: OrderedFormRow = candidate.overrideOf === undefined || candidate.moved === 'base' ? { holding: hit.holds.get(name)!, place: hit } : { holding: hit.holds.get(name)!, place: hit, overrideOf: candidate.overrideOf }; + out.push(candidate.moved === undefined ? row : { ...row, moved: candidate.moved }); } } - return undefined; + return out; +} + +/** + * [ADR-0159 D5, rule 11] The stored row the served-row order picks for `name` + * at `packageId`'s address, over both types: `undefined` when no place holds a + * row of the name (the package's source item is served). The first row of + * {@link orderedFormRowsAt}: one order, read by the `form` read and the + * stored-form ceremony alike. + */ +export function servedFormHolding( + places: readonly StoredFormPlace[], + name: string, + packageId: string, + installed: InstalledManifestLookup, +): OrderedFormRow | undefined { + return orderedFormRowsAt(places, name, packageId, installed)[0]; } /** A projected item, marked and served under `packageId`'s envelope. */ @@ -501,9 +564,10 @@ const REPORTED_UNREADABLE = new Set(); * [ADR-0159 D6 rule 7] Every stored `view` body the projection cannot turn * into `form` items, with the `sharing.publicLink` slugs it names: the doors * close each of those links. Each such row is said ONCE at `error`, naming the - * row (type, name, package), the links it closed, and the way out this release - * ships: an old-shape save that repairs the body. ⛔ No command that does not - * ship is named (the ceremony card, ⑤a, adds its name). + * row (type, name, package), the links it closed, the way out this release + * ships (an old-shape save that repairs the body), and the read-only ceremony + * command that lists every stored row holding the upgrade to major 19 + * (`os migrate stored-forms`, ADR-0159 D7-c: such a body holds it). */ export async function readUnreadableFormBodies( host: Pick, @@ -529,7 +593,8 @@ export async function readUnreadableFormBodies( report( `[Protocol] The stored view '${body.name}' (${where}) carries form content that cannot be read: ` + `${body.reason}. The public forms it names are closed: ${closed}. ` - + `Save the view again with its form content repaired (a \`form\` or \`formViews\` entry that is an object) to re-open them (ADR-0159 D6 rule 7).`, + + `Save the view again with its form content repaired (a \`form\` or \`formViews\` entry that is an object) to re-open them (ADR-0159 D6 rule 7). ` + + `Until it is repaired the row holds the upgrade to the next protocol major: \`os migrate stored-forms\` lists it with every other stored row that does (ADR-0159 D7-c).`, ); } return out; diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts new file mode 100644 index 00000000000..5225067035e --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts @@ -0,0 +1,1062 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7, card ⑤a] The stored-form ceremony's planner, pure over its + * input: each outcome and each hold cause on its own seed fixture. The rows + * are built as the `form` read builds them (`storedViewRowHoldings`, the one + * naming of a stored row's forms), so the planner reads the order the read + * serves. The census over a live protocol is pinned in + * `packages/objectql/src/protocol-stored-form-migration.test.ts`. + */ +import { describe, expect, it } from 'vitest'; +import { installedManifestsOf } from '@objectstack/metadata-core'; +import { expandViewContainer } from '@objectstack/spec'; +import { deriveViewContainerObject } from '@objectstack/spec'; +import { storedViewRowHoldings, type StoredFormPlace } from './protocol-form-reads.js'; +import { + INTERNAL_AHEAD_OF_LINKED_ROW, + planStoredForms, + type PairFixReading, + type ShippedForm, + type StoredFormAddressPlan, + type StoredFormCensus, + type StoredFormPlanInput, +} from './protocol-stored-form-migration.js'; + +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const WORKSPACE = 'com.acme.workspace'; +const OTHER = 'com.acme.other'; +const OBJECT = 'crm_lead'; +const NAME = `${OBJECT}.intake`; +const SLUG = 'lead-intake'; + +const NOTHING_INSTALLED = installedManifestsOf(undefined); + +const expandHost = { + expandStoredViewContainers: (_type: string, entries: readonly { data: unknown; packageId: string | undefined }[]) => + entries.flatMap((container) => { + const object = deriveViewContainerObject(container.data) ?? ''; + return expandViewContainer(object, container.data).map((item) => ({ item: item as unknown as Record, container })); + }), +} as never; + +function sharing(enabled: boolean | null): Record { + return enabled === null ? {} : { sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true } }; +} + +/** A stored `viewKind: 'form'` row. */ +function viewFormRow(packageId: string | undefined, opts: { enabled?: boolean | null; overrides?: string; isDefault?: boolean; name?: string } = {}): StoredFormPlace { + const name = opts.name ?? NAME; + const data = { + name, + object: OBJECT, + viewKind: 'form', + ...(opts.isDefault ? { isDefault: true } : {}), + ...(opts.overrides ? { overrides: { package: opts.overrides, basedOn: '1.0.0' } } : {}), + config: { object: OBJECT, sections: [{ fields: ['name'] }], ...sharing(opts.enabled ?? null) }, + }; + const entry = { name, data, packageId, organizationId: null, type: 'view' }; + return { type: 'view', packageId, entry, grain: 'item', holds: storedViewRowHoldings(expandHost, entry) }; +} + +/** A stored list `view` row at the name. */ +function listRow(packageId: string | undefined, name = NAME): StoredFormPlace { + const data = { name, object: OBJECT, viewKind: 'list', columns: ['name'] }; + const entry = { name, data, packageId, organizationId: null, type: 'view' }; + return { type: 'view', packageId, entry, grain: 'item', holds: storedViewRowHoldings(expandHost, entry) }; +} + +/** A stored container whose default `form` expands to `OBJECT.form`. */ +function containerRow(packageId: string | undefined, enabled: boolean | null): StoredFormPlace { + const data = { object: OBJECT, list: { columns: ['name'] }, form: { sections: [{ fields: ['name'] }], ...sharing(enabled) } }; + const entry = { name: `${OBJECT}`, data, packageId, organizationId: null, type: 'view' }; + return { type: 'view', packageId, entry, grain: 'expansion', holds: storedViewRowHoldings(expandHost, entry) }; +} + +/** A stored `form` row: a pair's declared override when `overrides` names a base. */ +function formRow(packageId: string | undefined, opts: { enabled?: boolean | null; overrides?: string } = {}): StoredFormPlace { + const data = { + name: NAME, + object: OBJECT, + ...(opts.overrides ? { overrides: { package: opts.overrides, basedOn: '1.0.0' } } : {}), + ...sharing(opts.enabled ?? null), + }; + const entry = { name: NAME, data, packageId, organizationId: null, type: 'form' }; + return { type: 'form', packageId, entry, grain: 'item', holds: new Map([[NAME, { kind: 'form', item: data }]]) }; +} + +const PAIR_OK: PairFixReading = { ok: true, pair: PAIR, basedOn: '1.0.0' }; + +function input(places: StoredFormPlace[], over: Partial & { ships?: Record } = {}): StoredFormPlanInput { + const ships = over.ships ?? { [NAME]: [{ packageId: BASE, writable: false, form: { name: NAME, object: OBJECT, ...sharing(true) } }] }; + return { + places, + installed: NOTHING_INSTALLED, + shippedForms: (name) => ships[name] ?? [], + // Every shipped form here is in the old shape, a `view`, unless a test says otherwise. + shipsView: (name) => (ships[name] ?? []).map((s) => s.packageId), + isWritable: (pkg) => pkg === WORKSPACE || pkg === PAIR, + actionTargets: new Set(), + pairFix: () => PAIR_OK, + objectHasFieldGroups: () => true, + unreadable: [], + ...over, + }; +} + +/** A plan's destination, where its outcome names one (a kept or moved form). */ +const destinationOf = (plan: StoredFormAddressPlan): unknown => ('destination' in plan ? plan.destination : undefined); + +const unlinkedBase = { [NAME]: [{ packageId: BASE, writable: false, form: { name: NAME, object: OBJECT } }] }; +const unlinkedContainerBase = { [`${OBJECT}.form`]: [{ packageId: BASE, writable: false, form: { name: `${OBJECT}.form`, object: OBJECT } }] }; + +describe('[ADR-0159 D7] planStoredForms — one outcome per form and address', () => { + it('move: a package-less old-shape row over a read-only base moves to the pair as a declared override (D7-a, D7-b)', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true })])); + expect(census.forms).toHaveLength(1); + const [plan] = census.forms; + expect(plan).toMatchObject({ + form: NAME, + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + destination: { kind: 'pair_override', base: BASE, pair: PAIR, basedOn: '1.0.0' }, + served: { type: 'view', holds: 'form', link: SLUG }, + newlyClosed: false, + }); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + it('move: a row bound to the read-only base takes the same destination; a link-less body over a linked base is never internal (D7-b)', () => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: null, isDefault: true })])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', destination: { kind: 'pair_override', pair: PAIR } }); + }); + + it('move: at a writable package the destination is that package\'s own form row', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([viewFormRow(WORKSPACE, { enabled: true })], { ships })); + expect(census.forms[0]).toMatchObject({ address: { kind: 'package', packageId: WORKSPACE }, outcome: 'move', destination: { kind: 'package_form', packageId: WORKSPACE } }); + }); + + it('move: a form no package ships is the environment\'s own: a package-less form row', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { ships: {} })); + expect(census.forms[0]).toMatchObject({ address: { kind: 'environment' }, outcome: 'move', destination: { kind: 'environment_form' } }); + }); + + it('keep: a declared `form` override already in the pair is kept, and an old-shape row behind it folds into it', () => { + const census = planStoredForms(input([formRow(PAIR, { enabled: true, overrides: BASE }), viewFormRow(undefined, { enabled: true })])); + expect(census.forms[0]).toMatchObject({ outcome: 'keep', served: { type: 'form', overrideOf: BASE }, behind: [{ type: 'view' }] }); + }); + + it('keep: a stored override in the pair stays kept when the pair door refuses an ensure now (nothing to create)', () => { + const census = planStoredForms(input([formRow(PAIR, { enabled: true, overrides: BASE })], { + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + expect(census.forms[0]).toMatchObject({ outcome: 'keep' }); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('remove: an internal record form (record-form slot, no link, no action target, over an unlinked base) will be removed, and is not counted', () => { + const census = planStoredForms(input([containerRow(undefined, null)], { ships: unlinkedContainerBase, objectHasFieldGroups: () => false })); + expect(census.forms[0]).toMatchObject({ form: `${OBJECT}.form`, outcome: 'remove', object: OBJECT, objectHasFieldGroups: false }); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + it('not internal: an action that opens the form keeps it (it moves)', () => { + const census = planStoredForms(input([containerRow(undefined, null)], { ships: unlinkedContainerBase, actionTargets: new Set([`${OBJECT}.form`]) })); + expect(census.forms[0]).toMatchObject({ outcome: 'move' }); + }); + + it('not internal: a switched-off link is still a link (D7-a)', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: false, isDefault: true })], { ships: unlinkedBase })); + expect(census.forms[0]).toMatchObject({ outcome: 'move', served: { withdraws: SLUG } }); + }); + + it('not internal: a named form outside the record-form slots moves', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: null })], { ships: unlinkedBase })); + expect(census.forms[0]).toMatchObject({ outcome: 'move' }); + }); + + it('left in place: a list served at the name ahead of a form row moves no row of it, and holds nothing (D7-d)', () => { + const census = planStoredForms(input([listRow(BASE), viewFormRow(undefined, { enabled: true })])); + expect(census.forms[0]).toMatchObject({ outcome: 'left_in_place', reason: 'served_no_form', served: { holds: 'list' }, behind: [{ holds: 'form' }] }); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('left in place: a writable package\'s own list ahead of a package-less form row (D7-d, by name)', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([listRow(WORKSPACE), viewFormRow(undefined, { enabled: true })], { ships })); + expect(census.forms[0]).toMatchObject({ address: { kind: 'package', packageId: WORKSPACE }, outcome: 'left_in_place', reason: 'served_no_form' }); + }); + + it(`left in place (option D, ${INTERNAL_AHEAD_OF_LINKED_ROW.reason}): a served internal row ahead of a linked row moves neither, removes nothing, and is not counted`, () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([viewFormRow(WORKSPACE, { enabled: null, isDefault: true }), viewFormRow(undefined, { enabled: true })], { ships })); + expect(census.forms[0]).toMatchObject({ + outcome: INTERNAL_AHEAD_OF_LINKED_ROW.outcome, + reason: INTERNAL_AHEAD_OF_LINKED_ROW.reason, + served: { packageId: WORKSPACE }, + behind: [{ link: SLUG }], + }); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + expect(census.forms.some((f) => f.outcome === 'remove')).toBe(false); + }); + + it(`left in place (${INTERNAL_AHEAD_OF_LINKED_ROW.reason}, the twin): the row behind keeps its link with the switch off — both rows stay`, () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([viewFormRow(WORKSPACE, { enabled: null, isDefault: true }), viewFormRow(undefined, { enabled: false })], { ships })); + expect(census.forms[0]).toMatchObject({ + outcome: 'left_in_place', + reason: 'internal_ahead_of_linked_row', + behind: [{ link: SLUG, withdraws: SLUG }], + }); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + it('fold: a withdrawal the base\'s layer reads today is carried and closes nothing newly', () => { + const census = planStoredForms(input([formRow(PAIR, { enabled: true, overrides: BASE }), viewFormRow(undefined, { enabled: false })])); + expect(census.forms[0]).toMatchObject({ outcome: 'keep', carries: { slug: SLUG, from: { type: 'view' } }, newlyClosed: false }); + }); + + it('fold: a withdrawal no layer reads today (behind the row bound to the base) is carried and named newly closed', () => { + const census = planStoredForms(input([ + formRow(PAIR, { enabled: true, overrides: BASE }), + viewFormRow(BASE, { enabled: true }), + viewFormRow(undefined, { enabled: false }), + ])); + expect(census.forms[0]).toMatchObject({ outcome: 'keep', carries: { slug: SLUG, from: { withdraws: SLUG } }, newlyClosed: true }); + expect(census.forms[0]).toHaveProperty('carries.from', expect.not.objectContaining({ packageId: expect.anything() })); + expect(census.forms[0]!.behind.map((r) => r.packageId)).toEqual([BASE, undefined]); + }); + + it('fold: the address a carried withdrawal closes is the kept body\'s own slug, not the folded row\'s', () => { + const kept = viewFormRow(BASE, { enabled: true }); + (kept.holds.get(NAME) as { item: Record }).item.sharing = { publicLink: '/forms/lead-intake-v2', enabled: true, allowAnonymous: true }; + const census = planStoredForms(input([kept, viewFormRow(undefined, { enabled: false })])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', carries: { slug: 'lead-intake-v2', from: { withdraws: SLUG } } }); + }); + + it('fold: the body kept is the served one — a bound row ahead of a package-less row (D7-d)', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true }), viewFormRow(BASE, { enabled: null })])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', served: { packageId: BASE }, behind: [{ link: SLUG }] }); + expect(census.forms[0]!.behind[0]).not.toHaveProperty('packageId'); + expect(census.forms[0]).not.toHaveProperty('carries'); + }); + + it.each([ + ['administrator', 'the namespace is owned by another package'], + ['app_author', 'the App declares no namespace'], + ['kernel', 'a kernel package'], + ] as const)('hold (%s): the pair cannot be ensured, the row holds the upgrade with the door\'s refusal and its action (D7-c)', (cause, refusal) => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { + pairFix: () => ({ ok: false, cause, refusal, app: BASE }), + })); + expect(census.forms[0]).toMatchObject({ outcome: 'hold', cause, refusal }); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds).toEqual([expect.objectContaining({ base: BASE, cause, refusal, row: expect.objectContaining({ form: NAME }) })]); + expect(census.precheck.holds[0]!.action.length).toBeGreaterThan(0); + }); + + it('hold (administrator, the earlier per-package pair, ruling 7250982640): the action says no command on this release clears it', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'held by the earlier pair', app: BASE, earlierPair: true }), + })); + expect(census.precheck.holds[0]).toMatchObject({ cause: 'administrator' }); + expect(census.precheck.holds[0]!.action).toContain('no command on this release does that'); + expect(census.precheck.holds[0]!.action).not.toContain('Remove the cause'); + }); + + it('hold (unreadable): a body the projection cannot read holds the upgrade wherever it stands (D7-c, rule 7)', () => { + const census = planStoredForms(input([], { + unreadable: [{ type: 'view', name: `${OBJECT}.broken`, reason: 'a `viewKind: \'form\'` item carries no `config` object', links: [SLUG] }], + })); + expect(census.precheck.canSwitch).toBe(false); + expect(census.unreadable).toEqual([expect.objectContaining({ cause: 'unreadable', row: expect.objectContaining({ name: `${OBJECT}.broken` }) })]); + expect(census.unreadable[0]!.refusal).toContain(`/forms/${SLUG}`); + expect(census.unreadable[0]!.refusal).toContain('as they do today'); + expect(census.unreadable[0]!.refusal).not.toContain('are closed'); + }); + + it('move (ruling 7250977204): a row bound to a read-only package that ships no form of the name moves into that package\'s pair as the pair\'s own form, declaring no override', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }) })); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: OTHER }, + outcome: 'move', + destination: { kind: 'pair_form', base: OTHER, pair: `${OTHER}.custom` }, + served: expect.objectContaining({ packageId: OTHER, form: NAME }), + })]); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('move (ruling 7250977204): the ensure-door hold applies when that package\'s pair cannot be ensured', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + expect(census.forms[0]).toMatchObject({ outcome: 'hold', cause: 'administrator', address: { kind: 'base', packageId: OTHER } }); + expect(census.precheck.canSwitch).toBe(false); + }); + + 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: {}, + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'package', packageId: PAIR }, + outcome: 'move', + destination: { kind: 'pair_form', base: BASE, pair: PAIR }, + })]); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('M1 (ruling 7250977204): a package-less row behind such a row folds into it, and the name has no environment address', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true }), viewFormRow(undefined, { enabled: false })], { ships: {} })); + expect(census.forms.some((f) => f.address.kind === 'environment')).toBe(false); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: OTHER }, + outcome: 'move', + behind: [expect.objectContaining({ withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + })]); + expect(census.forms[0]!.behind[0]).not.toHaveProperty('packageId'); + }); + + it.each([ + ['switches the form off', () => viewFormRow(PAIR, { enabled: false, overrides: BASE }), 'move'], + ['carries no link', () => viewFormRow(PAIR, { enabled: null, overrides: BASE }), 'move'], + ['is already a stored `form` row', () => formRow(PAIR, { enabled: false, overrides: BASE }), 'keep'], + ] as const)('M3 (D7-d, ruling 7250977204): beside a row bound to a base that ships no form of the name, the pair\'s override is the served row at the base\'s address — it %s, the open bound row folds behind it, and nothing else moves', (_label, override, outcome) => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: true }), override()], { + ships: {}, + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + // One plan, at the base's address: no second address moves the bound row on its own. + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: BASE }, outcome]]); + const [plan] = census.forms; + expect(plan).toMatchObject({ + destination: { kind: 'pair_form', base: BASE, pair: PAIR }, + served: { packageId: PAIR, overrideOf: BASE }, + behind: [{ packageId: BASE, link: SLUG }], + newlyClosed: false, + }); + // The body the read does not serve today (the open bound row) lends the kept form nothing. + expect(plan).not.toHaveProperty('carries'); + // The override already stands in its pair: the ensure door is not asked, so its refusal holds nothing. + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + it('M3: a withdrawal in the bound row is read today by the base\'s own layer, so the kept override carries it and nothing closes newly', () => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: false }), viewFormRow(PAIR, { enabled: true, overrides: BASE })], { ships: {} })); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + destination: { kind: 'pair_form', base: BASE, pair: PAIR }, + carries: expect.objectContaining({ slug: SLUG, from: expect.objectContaining({ packageId: BASE }) }), + newlyClosed: false, + })]); + }); + + it('M3: every override the served pair holds at the name is read at the base with it — its `view` row folds behind its `form` row, and is not planned apart at the pair\'s own address', () => { + const census = planStoredForms(input([ + viewFormRow(BASE, { enabled: true }), + viewFormRow(PAIR, { enabled: true, overrides: BASE }), + formRow(PAIR, { enabled: false, overrides: BASE }), + ], { ships: {} })); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f), f.served.type, f.behind.map((r) => [r.type, r.packageId])])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'keep', { kind: 'pair_form', base: BASE, pair: PAIR }, 'form', [['view', PAIR], ['view', BASE]]], + ]); + }); + + describe('M3, where the App\'s pair is not the per-package pair an earlier version created', () => { + const SUITE = 'com.acme.suite'; + const SUITE_PAIR = 'com.acme.suite.custom'; + // BASE is a member of the App SUITE, so its pair is the App's; PAIR, its own per-package pair, is still installed. + const manifests: Record }> = { + [SUITE]: { type: 'app' }, + [BASE]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [PAIR]: {}, + }; + const over = { + ships: {}, + installed: (id: string) => manifests[id], + isWritable: (pkg: string) => pkg === PAIR || pkg === SUITE_PAIR, + // The door would send a row bound to the base into the App's pair. + pairFix: (): PairFixReading => ({ ok: true, pair: SUITE_PAIR, basedOn: '1.0.0' }), + }; + + it('an override in the earlier per-package pair is the served row at the base\'s address: the bound row folds behind it, and is not a second form of the App\'s pair', () => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: true }), viewFormRow(PAIR, { enabled: false, overrides: BASE })], over)); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + destination: { kind: 'pair_form', base: BASE, pair: PAIR }, + served: expect.objectContaining({ packageId: PAIR, overrideOf: BASE }), + behind: [expect.objectContaining({ packageId: BASE })], + })]); + }); + + it('only the override the order serves at the base is read there: the App\'s pair\'s, and the earlier pair\'s stays at its own address, where the read serves it', () => { + const census = planStoredForms(input([ + viewFormRow(SUITE_PAIR, { enabled: false, overrides: BASE }), + viewFormRow(PAIR, { enabled: true, overrides: BASE }), + viewFormRow(BASE, { enabled: true }), + ], over)); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f), f.served.packageId, f.behind.map((r) => r.packageId)])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'move', { kind: 'pair_form', base: BASE, pair: SUITE_PAIR }, SUITE_PAIR, [BASE]], + [{ kind: 'package', packageId: PAIR }, 'move', { kind: 'pair_form', base: BASE, pair: PAIR }, PAIR, []], + ]); + }); + }); + + it('S6: a row behind a removed form that is the served row at another address is not removed with it, and is not counted behind it', () => { + const name = `${OBJECT}.form`; + const ships = { [name]: [ + { packageId: BASE, writable: false, form: { name, object: OBJECT } }, + { packageId: OTHER, writable: false, form: { name, object: OBJECT, ...sharing(true) } }, + ] }; + const internal = (): StoredFormPlace => viewFormRow(BASE, { enabled: null, isDefault: true, name }); + const census = planStoredForms(input([internal(), viewFormRow(undefined, { enabled: null, name })], { + ships, + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '1.0.0' }), + })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'remove'], + [{ kind: 'base', packageId: OTHER }, 'move'], + ]); + const [removal, move] = census.forms; + // The package-less row stands over OTHER's linked form: it moves there, and no removal lists it. + expect(removal).toMatchObject({ served: { packageId: BASE }, behind: [] }); + expect(removal).toHaveProperty('servedElsewhere', [expect.not.objectContaining({ packageId: expect.anything() })]); + expect(removal!.alsoReadAt).toEqual([expect.objectContaining({ address: { kind: 'base', packageId: OTHER }, outcome: 'move', served: true })]); + expect(move).toMatchObject({ destination: { kind: 'pair_override', base: OTHER, pair: `${OTHER}.custom` } }); + expect(move!.served).not.toHaveProperty('packageId'); + + // The control: with no other address to serve it, the row behind goes with the removal. + const alone = planStoredForms(input([internal(), viewFormRow(undefined, { enabled: null, name })], { ships: { [name]: [ships[name]![0]!] } })); + expect(alone.forms).toEqual([expect.objectContaining({ outcome: 'remove', behind: [expect.objectContaining({ form: name })] })]); + expect(alone.forms[0]).not.toHaveProperty('servedElsewhere'); + }); + + it('remove (ruling 7250977204, ruling 3): an internal record form bound to a package that ships no form of the name is removed, and needs no destination', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: null, isDefault: true })], { + ships: {}, + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + expect(census.forms[0]).toMatchObject({ outcome: 'remove', address: { kind: 'base', packageId: OTHER } }); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('drafts (ruling 7250982640): a move names the drafts of the row it moves, left behind', () => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: true })], { drafts: [{ type: 'view', name: NAME, packageId: BASE }, { type: 'view', name: NAME }] })); + expect(census.forms[0]).toMatchObject({ outcome: 'move', draftsLeftBehind: [{ type: 'view', name: NAME, packageId: BASE }] }); + expect(census.drafts).toHaveLength(2); + }); + + it('M2: a deletion is per row — a package-less internal row over an unlinked base and a linked base moves at both, and is removed at neither', () => { + const name = `${OBJECT}.form`; + const ships = { [name]: [ + { packageId: BASE, writable: false, form: { name, object: OBJECT } }, + { packageId: OTHER, writable: false, form: { name, object: OBJECT, ...sharing(true) } }, + ] }; + // Two packages of two Apps: each base has a pair of its own. + const census = planStoredForms(input([containerRow(undefined, null)], { ships, pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '1.0.0' }) })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'move'], + [{ kind: 'base', packageId: OTHER }, 'move'], + ]); + expect(census.forms[0]!.alsoReadAt).toEqual([expect.objectContaining({ address: { kind: 'base', packageId: OTHER }, outcome: 'move', served: true })]); + }); + + it('M2: the same row over two unlinked bases is removed at both, and each plan names the other', () => { + const name = `${OBJECT}.form`; + const ships = { [name]: [ + { packageId: BASE, writable: false, form: { name, object: OBJECT } }, + { packageId: OTHER, writable: false, form: { name, object: OBJECT } }, + ] }; + const census = planStoredForms(input([containerRow(undefined, null)], { ships })); + expect(census.forms.map((f) => f.outcome)).toEqual(['remove', 'remove']); + expect(census.forms[1]!.alsoReadAt).toEqual([expect.objectContaining({ address: { kind: 'base', packageId: BASE }, outcome: 'remove' })]); + }); + + it('S1: a pair\'s stored `view` override keeps its pair and `basedOn` — the pair door is not asked, and a refusal now holds nothing', () => { + const census = planStoredForms(input([viewFormRow(PAIR, { enabled: true, overrides: BASE })], { + pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }), + })); + expect(census.forms[0]).toMatchObject({ outcome: 'move', destination: { kind: 'pair_override', base: BASE, pair: PAIR, basedOn: '1.0.0' } }); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('S2: a list row behind the served row is neither folded nor removed — it is named as left as stored', () => { + const census = planStoredForms(input([viewFormRow(BASE, { enabled: true }), listRow(undefined)])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', behind: [], untouched: [{ holds: 'list' }] }); + }); + + it('S3: a lone list row over a base that ships the form is reported left in place (D7-d)', () => { + const census = planStoredForms(input([listRow(BASE)])); + expect(census.forms).toEqual([expect.objectContaining({ address: { kind: 'base', packageId: BASE }, outcome: 'left_in_place', reason: 'served_no_form', served: expect.objectContaining({ holds: 'list' }) })]); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('a list row at a name no package ships as a form is a list\'s, and is not reported', () => { + const census = planStoredForms(input([listRow(BASE)], { ships: {} })); + expect(census.forms).toEqual([]); + }); + + it('a package-less row is read at every address of its name, and the pair\'s override only at its base', () => { + const ships = { [NAME]: [ + { packageId: BASE, writable: false, form: { name: NAME, object: OBJECT, ...sharing(true) } }, + { packageId: WORKSPACE, writable: true, form: undefined }, + ] }; + const census = planStoredForms(input([formRow(PAIR, { enabled: true, overrides: BASE }), viewFormRow(undefined, { enabled: true })], { ships })); + expect(census.forms.map((f) => [f.address, f.outcome, f.served.packageId ?? null])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'keep', PAIR], + [{ kind: 'package', packageId: WORKSPACE }, 'move', null], + ]); + }); + + it('names a public slug two form names declare', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true }), viewFormRow(undefined, { enabled: true, name: `${OBJECT}.intake_v2` })])); + expect(census.sharedSlugs).toEqual([{ slug: SLUG, forms: [NAME, `${OBJECT}.intake_v2`] }]); + }); +}); + +describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another address than the package it is bound to is classed by the base it stands over there', () => { + const SUITE = 'com.acme.suite'; + const MODULE = 'com.acme.suite.service'; + const SECOND = 'com.acme.suite.sales'; + const FORMER = 'com.acme.suite.legacy'; + const SUITE_PAIR = 'com.acme.suite.custom'; + // The App SUITE ships no form of the name; its module MODULE ships it, linked and open. + const manifests: Record }> = { + [SUITE]: { type: 'app' }, + [MODULE]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [SECOND]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [FORMER]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [SUITE_PAIR]: {}, + }; + const shippedBy = (packageId: string, enabled: boolean | null = true): ShippedForm => + ({ packageId, writable: false, form: { name: NAME, object: OBJECT, ...sharing(enabled) } }); + const asked: string[] = []; + const over = (pairFix: (base: string) => PairFixReading = (base) => { asked.push(base); return { ok: true, pair: SUITE_PAIR, basedOn: '2.0.0' }; }) => ({ + ships: { [NAME]: [shippedBy(MODULE)] }, + installed: (id: string) => manifests[id], + isWritable: (pkg: string) => pkg === SUITE_PAIR, + pairFix, + }); + const toPair = (base: string) => ({ kind: 'pair_override', base, pair: SUITE_PAIR, basedOn: '2.0.0' }); + + it('a row bound to a package of the App that ships no form of the name moves into the pair of the package that ships it, as its declared override', () => { + asked.length = 0; + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: false })], over())); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: MODULE }, + outcome: 'move', + destination: toPair(MODULE), + served: expect.objectContaining({ packageId: SUITE, link: SLUG, withdraws: SLUG }), + })]); + expect(asked).toEqual([MODULE]); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('a pair\'s override that declares that package moves to the same destination, re-declared over the package that ships the name', () => { + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: false, overrides: SUITE })], over())); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: MODULE }, + outcome: 'move', + destination: toPair(MODULE), + served: expect.objectContaining({ packageId: SUITE_PAIR, overrideOf: MODULE }), + })]); + }); + + it('both at one name: one plan at that address, the override served and the bound row behind it', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: true }), viewFormRow(SUITE_PAIR, { enabled: false, overrides: SUITE })], over())); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f), f.served.packageId, f.behind.map((r) => r.packageId)])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'move', toPair(MODULE), SUITE_PAIR, [SUITE]], + ]); + }); + + it('where that pair cannot be ensured, the row holds the upgrade (D7-c) and is not sent to another pair', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: false })], over(() => ({ ok: false, cause: 'administrator', refusal: 'refused' })))); + expect(census.forms).toEqual([expect.objectContaining({ address: { kind: 'base', packageId: MODULE }, outcome: 'hold', cause: 'administrator' })]); + expect(census.precheck.canSwitch).toBe(false); + }); + + it('a row with no link of its own, in a record-form slot, is never listed for removal over a linked base there (D7-b, D7-e); over a base with no link it is internal like its base', () => { + const row = (): StoredFormPlace => viewFormRow(SUITE, { enabled: null, isDefault: true }); + const linked = planStoredForms(input([row()], over())); + expect(linked.forms.map((f) => [f.address, f.outcome, destinationOf(f)])).toEqual([[{ kind: 'base', packageId: MODULE }, 'move', toPair(MODULE)]]); + const unlinked = planStoredForms(input([row()], { ...over(), ships: { [NAME]: [shippedBy(MODULE, null)] } })); + expect(unlinked.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: MODULE }, 'remove']]); + }); + + it('a row two packages serve holds the upgrade (ruling record 7265816895): a hold at each address, each naming the other, and the row named once', () => { + const ships = { [NAME]: [shippedBy(MODULE), shippedBy(SECOND)] }; + for (const row of [viewFormRow(SUITE, { enabled: null }), viewFormRow(SUITE_PAIR, { enabled: null, overrides: SUITE })]) { + const census = planStoredForms(input([row], { ...over(), ships })); + expect(census.forms.map((f) => [f.address, f.outcome, 'cause' in f ? f.cause : undefined, f.alsoReadAt.map((e) => [e.address, e.outcome, e.served])])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', 'app_author', [[{ kind: 'base', packageId: SECOND }, 'hold', true]]], + [{ kind: 'base', packageId: SECOND }, 'hold', 'app_author', [[{ kind: 'base', packageId: MODULE }, 'hold', true]]], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: row.packageId }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.refusal).toContain(`'${MODULE}' and '${SECOND}'`); + } + }); + + it('two rows that could each follow the name there are served by neither read: neither is read at that address, each is still named at its own, and the one pair slot both would land in holds the upgrade (ruling record 7265816895)', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: false }), viewFormRow(FORMER, { enabled: false })], over())); + expect(census.forms.map((f) => [f.address, f.served.packageId, f.outcome, 'cause' in f ? f.cause : undefined]).sort()).toEqual([ + [{ kind: 'base', packageId: SUITE }, SUITE, 'hold', 'app_author'], + [{ kind: 'base', packageId: FORMER }, FORMER, 'hold', 'app_author'], + ].sort()); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds.map((h) => h.row.packageId).sort()).toEqual([SUITE, FORMER].sort()); + // No exit was measured for a slot two rows claim (a package of the App already ships the form here): the action promises none. + for (const hold of census.precheck.holds) { + expect(hold.action).toContain('no exit from it was measured'); + expect(hold.action).not.toMatch(/until the App ships/); + } + }); + + 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 })]) { + const census = planStoredForms(input([own, viewFormRow(SUITE, { enabled: false })], over())); + expect(census.forms.map((f) => [f.address, f.served.packageId, f.outcome, 'cause' in f ? f.cause : undefined]).sort()).toEqual([ + [{ kind: 'base', packageId: MODULE }, SUITE, 'hold', 'app_author'], + [{ kind: 'package', packageId: SUITE_PAIR }, SUITE_PAIR, 'hold', 'app_author'], + ].sort()); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.move + census.precheck.counts.keep).toBe(0); + expect(census.precheck.holds.map((h) => h.row.packageId).sort()).toEqual([SUITE, SUITE_PAIR].sort()); + } + }); + + it('a row two packages serve, at a slot the pair\'s own row claims too: the action names no exit, and each row is named once', () => { + const ships = { [NAME]: [shippedBy(MODULE), shippedBy(SECOND)] }; + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: true }), viewFormRow(SUITE, { enabled: false })], { ...over(), ships })); + expect(census.forms.map((f) => f.outcome)).toEqual(['hold', 'hold', 'hold']); + expect(census.precheck.holds.map((h) => h.row.packageId).sort()).toEqual([SUITE, SUITE_PAIR].sort()); + for (const hold of census.precheck.holds) { + expect(hold.action).toContain('no exit from it was measured'); + expect(hold.action).not.toContain('ships the form from one of these packages only'); + } + }); + + it('a row that holds at one package\'s pair door and claims a contested slot at another is named once, by the door\'s hold', () => { + const ships = { [NAME]: [shippedBy(MODULE), shippedBy(SECOND)] }; + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: true }), viewFormRow(SUITE, { enabled: false })], { + ...over((base) => (base === SECOND ? { ok: false, cause: 'administrator', refusal: 'refused' } : { ok: true, pair: SUITE_PAIR, basedOn: '2.0.0' })), + ships, + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'cause' in f ? f.cause : undefined]).sort()).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', 'app_author'], + [{ kind: 'base', packageId: SECOND }, 'hold', 'administrator'], + [{ kind: 'package', packageId: SUITE_PAIR }, 'hold', 'app_author'], + ].sort()); + expect(census.precheck.holds.map((h) => [h.row.packageId, h.cause]).sort()).toEqual([[SUITE, 'administrator'], [SUITE_PAIR, 'app_author']].sort()); + }); + + it('a row two packages of the App serve, claiming the App\'s slot from both, and served at another App\'s base too: the slot\'s action names no exit, since the row is not read at one address alone once the App ships the form from one package', () => { + const census = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { + ...over((base) => ({ ok: true, pair: base === BASE ? PAIR : SUITE_PAIR, basedOn: '2.0.0' })), + ships: { [NAME]: [shippedBy(MODULE), shippedBy(SECOND), shippedBy(BASE)] }, + })); + expect(census.forms.map((f) => f.outcome)).toEqual(['hold', 'hold', 'hold']); + const atModule = census.forms.find((f) => f.address.kind === 'base' && f.address.packageId === MODULE) as StoredFormAddressPlan & { outcome: 'hold' }; + expect(atModule.action).toContain('no exit from it was measured'); + expect(atModule.action).not.toContain('ships the form from one of these packages only'); + }); + + it('control: the pair\'s own row alone at the pair\'s address is planned there, and nothing holds', () => { + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: true })], over())); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f)])).toEqual([ + [{ kind: 'package', packageId: SUITE_PAIR }, 'move', { kind: 'package_form', packageId: SUITE_PAIR }], + ]); + expect(census.precheck.canSwitch).toBe(true); + }); + + it('a withdrawal carried from such a row closes nothing newly: its own package\'s layer reads it today, whatever row is served ahead of it', () => { + const withdrawn = (): StoredFormPlace => viewFormRow(SUITE, { enabled: false }); + // Behind the base's own declared override, and behind a package-less row. + for (const ahead of [viewFormRow(SUITE_PAIR, { enabled: true, overrides: MODULE }), viewFormRow(undefined, { enabled: true })]) { + const [plan] = planStoredForms(input([ahead, withdrawn()], over())).forms; + expect(plan!.served.packageId).toBe(ahead.packageId); + expect(plan).toMatchObject({ + address: { kind: 'base', packageId: MODULE }, + behind: [{ packageId: SUITE, withdraws: SLUG }], + carries: { slug: SLUG, from: { packageId: SUITE } }, + newlyClosed: false, + }); + } + }); + + it('control: where the package the row is bound to still ships the name, the row stays at its own address', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: false })], { ...over(), ships: { [NAME]: [shippedBy(MODULE), shippedBy(SUITE)] } })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: SUITE }, 'move']]); + }); + + it('control: a package that ships a list at the name still holds it, so a row bound to it stays its own', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: false })], { ...over(), shipsView: () => [MODULE, SUITE] })); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f)])).toEqual([ + [{ kind: 'base', packageId: SUITE }, 'move', { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }], + ]); + }); + + it('ruling record 7250977204 stands for every row its premise holds for: a row the read serves at the package it is bound to keeps the destination it gives', () => { + const ownPair = { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }; + for (const row of [viewFormRow(SUITE, { enabled: false }), viewFormRow(SUITE_PAIR, { enabled: false, overrides: SUITE })]) { + const census = planStoredForms(input([row], { ...over(), shipsView: () => [] })); + expect(census.forms.map((f) => [f.served.packageId, f.outcome, destinationOf(f)])).toEqual([[row.packageId, 'move', ownPair]]); + expect(census.forms.some((f) => f.address.kind !== 'environment' && f.address.packageId === MODULE)).toBe(false); + } + }); + + it('a stored `form` row keeps the address of the package it is bound to', () => { + const ownPair = { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }; + const bound = planStoredForms(input([formRow(SUITE, { enabled: false })], over())); + expect(bound.forms.map((f) => [f.address, f.outcome, destinationOf(f)])).toEqual([[{ kind: 'base', packageId: SUITE }, 'move', ownPair]]); + const inPair = planStoredForms(input([formRow(SUITE_PAIR, { enabled: false, overrides: SUITE })], over())); + expect(inPair.forms.map((f) => [f.served.packageId, f.outcome, destinationOf(f)])).toEqual([[SUITE_PAIR, 'keep', ownPair]]); + }); + + it('a member of a stored container is not such a row: it keeps the address of the package the container is bound to', () => { + const name = `${OBJECT}.form`; + const census = planStoredForms(input([containerRow(SUITE, null)], { + ...over(), + ships: { [name]: [{ packageId: MODULE, writable: false, form: { name, object: OBJECT } }] }, + })); + expect(census.forms.map((f) => [f.form, f.address, f.served.packageId, f.served.grain])).toEqual([ + [name, { kind: 'base', packageId: SUITE }, SUITE, 'expansion'], + ]); + }); + + describe('a member of a stored container behind a row the read serves at another address (D7-d)', () => { + const name = `${OBJECT}.form`; + const moduleShips = () => ({ ...over(), ships: { [name]: [{ packageId: MODULE, writable: false, form: { name, object: OBJECT, ...sharing(true) } }] } }); + const bound = (enabled: boolean | null): StoredFormPlace => viewFormRow(SUITE, { name, enabled }); + const declared = (enabled: boolean | null): StoredFormPlace => viewFormRow(SUITE_PAIR, { name, enabled, overrides: SUITE }); + const shape = (f: StoredFormAddressPlan) => [f.address, f.outcome, destinationOf(f), [f.served.packageId, f.served.grain], f.behind.map((r) => [r.packageId, r.grain])]; + + it('is served at no address: it folds behind the row served ahead of it at its own address, where that row is planned, and its own address gets no plan', () => { + for (const ahead of [bound(false), declared(false)]) { + const census = planStoredForms(input([ahead, containerRow(SUITE, true)], moduleShips())); + expect(census.forms.map(shape)).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'move', toPair(MODULE), [ahead.packageId, 'item'], [[SUITE, 'expansion']]], + ]); + } + }); + + it('a withdrawal it carries closes nothing newly only where its own package\'s layer reads it today: behind the pair\'s override, not behind a row bound ahead of it', () => { + for (const [ahead, newlyClosed] of [[bound(true), true], [declared(true), false]] as const) { + const [plan, ...more] = planStoredForms(input([ahead, containerRow(SUITE, false)], moduleShips())).forms; + expect(more).toEqual([]); + expect(plan).toMatchObject({ + address: { kind: 'base', packageId: MODULE }, + served: { packageId: ahead.packageId, grain: 'item' }, + behind: [{ packageId: SUITE, grain: 'expansion', withdraws: SLUG }], + carries: { slug: SLUG, from: { packageId: SUITE, grain: 'expansion' } }, + newlyClosed, + }); + } + }); + + it('beside a package-less row served ahead of both at the shipper, it folds behind them there', () => { + const census = planStoredForms(input([viewFormRow(undefined, { name, enabled: true }), bound(false), containerRow(SUITE, true)], moduleShips())); + expect(census.forms.map(shape)).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'move', toPair(MODULE), [undefined, 'item'], [[SUITE, 'item'], [SUITE, 'expansion']]], + ]); + }); + }); + + it('a row the read serves at its own package as well is read at both addresses, and holds the upgrade at both (ruling record 7265816895)', () => { + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: null })], { + ...over(), + ships: { [NAME]: [shippedBy(MODULE), shippedBy(SUITE)] }, + shipsView: () => [MODULE], + })); + expect(census.forms.map((f) => [f.address, f.outcome, f.alsoReadAt.map((e) => e.address)])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', [{ kind: 'base', packageId: SUITE }]], + [{ kind: 'base', packageId: SUITE }, 'hold', [{ kind: 'base', packageId: MODULE }]], + ]); + expect(census.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: SUITE }, cause: 'app_author' }] }); + }); + + it('a row two packages serve holds at both where one address leaves it in place (an internal form ahead of a linked row) and the other would move it (ruling record 7265816895)', () => { + const ships = { [NAME]: [shippedBy(MODULE, null), shippedBy(SECOND)] }; + const census = planStoredForms(input([ + viewFormRow(SUITE_PAIR, { enabled: null, overrides: SUITE, isDefault: true }), + viewFormRow(SUITE, { enabled: true }), + ], { ...over(), ships })); + expect(census.forms.map((f) => [f.address, f.outcome, f.served.packageId, 'cause' in f ? f.cause : undefined])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', SUITE_PAIR, 'app_author'], + [{ kind: 'base', packageId: SECOND }, 'hold', SUITE_PAIR, 'app_author'], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: SUITE_PAIR }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.action).toContain(`'${SUITE}'`); + }); + + it('the same holds where the pair door refuses the base that leaves the row in place: the base is read as the App\'s by its App (ruling record 7265816895)', () => { + const ships = { [NAME]: [shippedBy(MODULE, null), shippedBy(SECOND)] }; + const census = planStoredForms(input([ + viewFormRow(SUITE_PAIR, { enabled: null, overrides: SUITE, isDefault: true }), + viewFormRow(SUITE, { enabled: true }), + ], { ...over((base) => (base === MODULE ? { ok: false, cause: 'app_author', refusal: 'refused' } : { ok: true, pair: SUITE_PAIR, basedOn: '2.0.0' })), ships })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold'], + [{ kind: 'base', packageId: SECOND }, 'hold'], + ]); + expect(census.precheck.canSwitch).toBe(false); + }); + + it('a row two packages serve, removed at one and left in place at the other (an internal form ahead of a linked row), is changed at neither: it holds at both (ruling record 7265816895)', () => { + const name = `${OBJECT}.form`; + const unlinked = (pkg: string): ShippedForm => ({ packageId: pkg, writable: false, form: { name, object: OBJECT } }); + const census = planStoredForms(input([viewFormRow(SUITE, { name, enabled: null, isDefault: true }), containerRow(SUITE, true)], { + ...over(), ships: { [name]: [unlinked(MODULE), unlinked(SUITE)] }, shipsView: () => [MODULE], + })); + expect(census.forms.map((f) => [f.address, f.outcome, f.served.packageId, f.served.grain])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', SUITE, 'item'], + [{ kind: 'base', packageId: SUITE }, 'hold', SUITE, 'item'], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.remove).toBe(0); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: SUITE, grain: 'item' }), cause: 'app_author' })]); + }); + + it('the linked row behind an internal form left in place stays there too (ruling record 7249158572, 「两行都不动」): where another address serves it and would move it, every address holds', () => { + // The internal package-less row is served at the module (no link there) ahead of the row bound to the App, + // which declares a link; the App ships the form linked, so the row bound to it is served at the App's own address. + const census = planStoredForms(input([viewFormRow(undefined, { enabled: null, isDefault: true }), viewFormRow(SUITE, { enabled: true })], { + ...over(), ships: { [NAME]: [shippedBy(MODULE, null), shippedBy(SUITE)] }, shipsView: () => [MODULE], + })); + expect(census.forms.map((f) => [f.address, f.outcome, f.served.packageId, 'cause' in f ? f.cause : undefined])).toEqual([ + [{ kind: 'base', packageId: MODULE }, 'hold', undefined, 'app_author'], + [{ kind: 'base', packageId: SUITE }, 'hold', SUITE, 'app_author'], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.move).toBe(0); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: SUITE, link: SLUG }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.refusal).toContain('7249158572'); + // The module only keeps the row behind its internal form: the read serves it at the App's address alone. + expect(census.precheck.holds[0]!.refusal).toContain(`The read serves view row '${NAME}' bound to '${SUITE}' at '${SUITE}', and keeps it behind the internal form left in place at '${MODULE}',`); + // No exit was measured for this shape. + expect(census.precheck.holds[0]!.action).toContain('no exit from it was measured'); + }); + + it('a plan held for one row is no hold of the row kept behind it: where a third address serves the internal row apart, the linked row still holds on its own, with no exit (ruling record 7249158572)', () => { + // As above, and the package-less row is also served at OTHER, linked there, which would move it into its own pair: + // the module's plan then holds for the package-less row, while the row bound to the App is still kept behind it. + const OTHER_PAIR = `${OTHER}.custom`; + const census = planStoredForms(input([viewFormRow(undefined, { enabled: null, isDefault: true }), viewFormRow(SUITE, { enabled: true })], { + ...over((base) => ({ ok: true, pair: base === OTHER ? OTHER_PAIR : SUITE_PAIR, basedOn: '2.0.0' })), + ships: { [NAME]: [shippedBy(MODULE, null), shippedBy(SUITE), shippedBy(OTHER)] }, + shipsView: () => [MODULE], + })); + const at = (pkg: string) => census.forms.find((f) => f.address.kind === 'base' && f.address.packageId === pkg) as StoredFormAddressPlan & { outcome: 'hold' }; + expect([at(MODULE).outcome, at(SUITE).outcome, at(OTHER).outcome]).toEqual(['hold', 'hold', 'hold']); + expect([at(MODULE).served.packageId, at(SUITE).served.packageId, at(OTHER).served.packageId]).toEqual([undefined, SUITE, undefined]); + // The row bound to the App waits on no hold: the module's is taken for the package-less row. + expect(at(SUITE).refusal).not.toContain('until that hold is cleared'); + expect(at(SUITE).refusal).toContain('7249158572'); + expect(at(SUITE).action).toContain('no exit from it was measured'); + // Each row is named once, by its own hold. + expect(census.precheck.holds.map((h) => [h.row.packageId, h.cause])).toEqual([[undefined, 'app_author'], [SUITE, 'app_author']]); + expect(census.precheck.canSwitch).toBe(false); + }); + + it('control: a package-less row two packages serve, internal over one and over a linked base at the other, holds at both', () => { + const ships = { [NAME]: [shippedBy(MODULE, null), shippedBy(SECOND)] }; + const census = planStoredForms(input([viewFormRow(SUITE, { enabled: null, isDefault: true }), viewFormRow(undefined, { enabled: true })], { ...over(), ships })); + expect(census.forms.map((f) => f.outcome)).toEqual(['hold', 'hold']); + expect(census.precheck.canSwitch).toBe(false); + }); + + describe('a row the read serves at addresses of two Apps is decided over every address that serves it (ruling record 7265816895)', () => { + const FORM = `${OBJECT}.form`; + const shipped = (packageId: string, enabled: boolean | null): ShippedForm => ({ packageId, writable: false, form: { name: FORM, object: OBJECT, ...sharing(enabled) } }); + const eachOwnPair = (base: string): PairFixReading => ({ ok: true, pair: `${base}.custom`, basedOn: '1.0.0' }); + // OTHER is a module of the App OTHER_APP, which ships no form of the name; BASE stands alone. + const OTHER_APP = 'com.acme.otherapp'; + const manifests: Record }> = { + [OTHER_APP]: { type: 'app' }, + [OTHER]: { type: 'module', dependencies: { [OTHER_APP]: '*' } }, + }; + const installed = (id: string) => manifests[id]; + // The same, with OTHER declaring a second App and no namespace: its App cannot be read. + const twoApps: Record }> = { + ...manifests, + [`${OTHER_APP}2`]: { type: 'app' }, + [OTHER]: { type: 'module', dependencies: { [OTHER_APP]: '*', [`${OTHER_APP}2`]: '*' } }, + }; + // A package-less internal row: over BASE (linked) it moves; over OTHER (no link) it is served ahead of + // a row bound to OTHER_APP whose form declares a link, read there behind it. + const rows = (): StoredFormPlace[] => [viewFormRow(undefined, { name: FORM, enabled: null, isDefault: true }), viewFormRow(OTHER_APP, { name: FORM, enabled: true })]; + const linkedAndNot = { [FORM]: [shipped(BASE, true), shipped(OTHER, null)] }; + const bothLinked = { [FORM]: [shipped(BASE, true), shipped(OTHER, true)] }; + const shape = (f: StoredFormAddressPlan) => [f.address, f.outcome, f.served.packageId, 'cause' in f ? f.cause : undefined]; + + it('moved at one App\'s base and left in place at another App\'s: it holds at both, and the precheck names it once', () => { + const census = planStoredForms(input(rows(), { ships: linkedAndNot, pairFix: eachOwnPair, installed })); + expect(census.forms.map(shape)).toEqual([ + [{ kind: 'base', packageId: BASE }, 'hold', undefined, 'app_author'], + [{ kind: 'base', packageId: OTHER }, 'hold', undefined, 'app_author'], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.move).toBe(0); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ name: FORM, grain: 'item' }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.row.packageId).toBeUndefined(); + expect(census.precheck.holds[0]!.refusal).toContain(`'${BASE}' and '${OTHER}'`); + // The action names both Apps, and does not read as if there were one. + expect(census.precheck.holds[0]!.action).toContain(`the Apps '${BASE}' and '${OTHER}'`); + expect(census.precheck.holds[0]!.action).not.toContain('author of the App'); + }); + + it('removed at a package this environment writes and left in place at an App\'s base: it holds at both, and the action says where it is served and promises no exit', () => { + const census = planStoredForms(input(rows(), { + ships: { [FORM]: [shipped(OTHER, null), { packageId: WORKSPACE, writable: true, form: undefined }] }, + installed, + pairFix: eachOwnPair, + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'cause' in f ? f.cause : undefined])).toEqual([ + [{ kind: 'base', packageId: OTHER }, 'hold', 'app_author'], + [{ kind: 'package', packageId: WORKSPACE }, 'hold', 'app_author'], + ]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.remove).toBe(0); + expect(census.precheck.holds).toHaveLength(1); + expect(census.precheck.holds[0]!.action).toContain(`packages of the App '${OTHER}', and '${WORKSPACE}', which this environment writes`); + expect(census.precheck.holds[0]!.action).toContain('no exit from it was measured'); + expect(census.precheck.holds[0]!.action).not.toContain('author of the App'); + }); + + it('moved at one App\'s base and held at another\'s pair door: the plan that would move waits on that hold, with its cause and its action, and the row is named once', () => { + for (const [refused, installedOf] of [ + [{ ok: false, cause: 'administrator', refusal: 'refused' }, installed], + [{ ok: false, cause: 'app_author', refusal: 'no single App' }, (id: string) => twoApps[id]], + ] as const) { + const census = planStoredForms(input([viewFormRow(undefined, { name: FORM, enabled: true })], { + ships: bothLinked, + installed: installedOf, + pairFix: (base) => (base === OTHER ? refused : eachOwnPair(base)), + })); + const [atBase, atOther] = census.forms as Array; + expect([atBase!.address, atBase!.outcome, atOther!.address, atOther!.outcome]).toEqual([ + { kind: 'base', packageId: BASE }, 'hold', { kind: 'base', packageId: OTHER }, 'hold', + ]); + expect(atOther!.cause).toBe(refused.cause); + expect([atBase!.cause, atBase!.action]).toEqual([atOther!.cause, atOther!.action]); + expect(atBase!.refusal).toContain(`It holds at '${OTHER}'`); + // The cause the action names is in the refusal of the plan it waits on, which the waiting plan repeats. + expect(atBase!.refusal).toContain(atOther!.refusal); + expect(census.precheck.counts.move).toBe(0); + expect(census.precheck.holds).toEqual([expect.objectContaining({ base: OTHER, cause: refused.cause })]); + } + }); + + it('a held row is folded into no other row: where it stands behind the row a third address moves, it is listed apart there and the fold is read without it (ADR-0159 D7)', () => { + const THIRD = 'com.acme.third'; + const census = planStoredForms(input([viewFormRow(undefined, { name: FORM, enabled: false }), viewFormRow(THIRD, { name: FORM, enabled: true })], { + ships: { [FORM]: [shipped(BASE, true), shipped(OTHER, true), shipped(THIRD, true)] }, + pairFix: (base) => (base === OTHER ? { ok: false, cause: 'administrator', refusal: 'refused' } : eachOwnPair(base)), + })); + expect(census.forms.map((f) => [f.address, f.outcome, f.served.packageId])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'hold', undefined], + [{ kind: 'base', packageId: OTHER }, 'hold', undefined], + [{ kind: 'base', packageId: THIRD }, 'move', THIRD], + ]); + const third = census.forms[2] as StoredFormAddressPlan & { outcome: 'move' }; + expect(third.behind).toEqual([]); + expect(third.heldApart).toEqual([expect.objectContaining({ name: FORM, withdraws: SLUG })]); + expect(third.heldApart![0]!.packageId).toBeUndefined(); + // The held row's withdrawal is not carried into the moved row. + expect(third.carries).toBeUndefined(); + expect(third.newlyClosed).toBe(false); + }); + + it('a plan waits on another hold only where clearing it would let every address treat the row alike: with a third address that leaves it in place, the move holds with no exit', () => { + const THIRD = 'com.acme.third'; + const census = planStoredForms(input(rows(), { + ships: { [FORM]: [shipped(BASE, true), shipped(OTHER, null), shipped(THIRD, true)] }, + installed, + pairFix: (base) => (base === THIRD ? { ok: false, cause: 'administrator', refusal: 'refused' } : eachOwnPair(base)), + })); + const at = (pkg: string) => census.forms.find((f) => f.address.kind === 'base' && f.address.packageId === pkg) as StoredFormAddressPlan & { outcome: 'hold' }; + expect([at(BASE).outcome, at(OTHER).outcome, at(THIRD).outcome]).toEqual(['hold', 'hold', 'hold']); + expect(at(THIRD).cause).toBe('administrator'); + // Clearing the administrator's hold would still leave the row moved at one address and left in place at another. + expect(at(BASE).cause).toBe('app_author'); + expect(at(BASE).action).toContain('no exit from it was measured'); + expect(at(BASE).action).not.toBe(at(THIRD).action); + // Nothing is said of what clearing the administrator's hold alone would do: that was not measured. + expect(at(BASE).refusal).not.toContain('clearing that hold alone'); + expect(census.precheck.holds).toEqual([expect.objectContaining({ base: THIRD, cause: 'administrator' })]); + }); + + it('control: moved at both Apps\' bases, each into its own pair, it moves at both', () => { + const census = planStoredForms(input([viewFormRow(undefined, { name: FORM, enabled: true })], { ships: bothLinked, pairFix: eachOwnPair })); + expect(census.forms.map((f) => [f.address, f.outcome, destinationOf(f)])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'move', { kind: 'pair_override', base: BASE, pair: `${BASE}.custom`, basedOn: '1.0.0' }], + [{ kind: 'base', packageId: OTHER }, 'move', { kind: 'pair_override', base: OTHER, pair: `${OTHER}.custom`, basedOn: '1.0.0' }], + ]); + expect(census.precheck.canSwitch).toBe(true); + }); + + describe('a row kept as stored under ruling record 7249158572 is folded, moved or removed at no address', () => { + // A package-less internal row ahead of a package-less container whose form declares a link: over OTHER + // (no link) both stay as stored. Package-less rows are read at every address of the name, so at a further + // linked base both stand behind the row bound to that base, which would move and fold them into it. + const THIRD = 'com.acme.third'; + const kept = (): StoredFormPlace[] => [viewFormRow(undefined, { name: FORM, enabled: null, isDefault: true }), containerRow(undefined, true)]; + const at = (census: StoredFormCensus, pkg: string) => census.forms.find((f) => f.address.kind === 'base' && f.address.packageId === pkg)!; + + it('behind the row a further address would move, the kept rows hold that move and are listed apart there, with no exit', () => { + const census = planStoredForms(input([...kept(), viewFormRow(BASE, { name: FORM, enabled: true })], { + ships: { [FORM]: [shipped(BASE, true), shipped(OTHER, null)] }, pairFix: eachOwnPair, installed, + })); + expect(census.forms.map(shape)).toEqual([ + [{ kind: 'base', packageId: BASE }, 'hold', BASE, 'app_author'], + [{ kind: 'base', packageId: OTHER }, 'left_in_place', undefined, undefined], + ]); + const held = at(census, BASE) as StoredFormAddressPlan & { outcome: 'hold' }; + expect(held.behind).toEqual([]); + expect(held.heldApart?.map((r) => [r.packageId, r.grain])).toEqual([[undefined, 'item'], [undefined, 'expansion']]); + expect(held.refusal).toContain('7249158572'); + expect(held.refusal).toContain(`folded into view row '${FORM}' bound to '${BASE}'`); + expect(held.action).toContain('no exit from it was measured'); + // The row the precheck names is served at BASE only: the action does not say it is served at OTHER too. + expect(held.action).not.toContain('This row is served at'); + expect(held.action).toContain(`The addresses this cause spans are packages of the Apps '${BASE}' and '${OTHER}'`); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.counts.move).toBe(0); + expect(census.precheck.holds.map((h) => [h.row.packageId, h.cause])).toEqual([[BASE, 'app_author']]); + }); + + it('behind the rows two further addresses would move, each of those moves holds, and each is named once', () => { + const census = planStoredForms(input([...kept(), viewFormRow(BASE, { name: FORM, enabled: true }), viewFormRow(THIRD, { name: FORM, enabled: true })], { + ships: { [FORM]: [shipped(BASE, true), shipped(OTHER, null), shipped(THIRD, true)] }, pairFix: eachOwnPair, installed, + })); + expect([at(census, BASE).outcome, at(census, OTHER).outcome, at(census, THIRD).outcome]).toEqual(['hold', 'left_in_place', 'hold']); + for (const pkg of [BASE, THIRD]) { + const held = at(census, pkg) as StoredFormAddressPlan & { outcome: 'hold' }; + expect(held.heldApart).toHaveLength(2); + expect(held.refusal).toContain('7249158572'); + expect(held.action).toContain('no exit from it was measured'); + } + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds.map((h) => h.row.packageId).sort()).toEqual([BASE, THIRD].sort()); + }); + }); + }); + + it('control: a row one package serves moves there, and two rows whose plans land in two pairs each move', () => { + const one = planStoredForms(input([viewFormRow(SUITE, { enabled: null })], over())); + expect(one.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: MODULE }, 'move']]); + const two = planStoredForms(input([viewFormRow(SUITE, { enabled: false }), viewFormRow(FORMER, { enabled: false })], { + ...over(), pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + })); + expect(two.forms.map((f) => f.outcome)).toEqual(['move', 'move']); + expect(two.precheck.canSwitch).toBe(true); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts new file mode 100644 index 00000000000..b43f1e14adc --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -0,0 +1,1693 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The stored-form ceremony, its read-only half (ADR-0159 D7, card ⑤a) + * + * Major 19 retires the three old shapes of a form (a `view` container's + * `form`, a `formViews` entry, a `viewKind: 'form'` item). A stored row cannot + * change its type in the stored pass, so the rows that hold a form in an old + * shape are moved by a ceremony the major's upgrade command runs: convert, + * then switch, all or nothing (ruling `7142585849` 2 and the addendum + * `7142658348`). This module is the read-only half: the census of what the + * ceremony would do, and the precheck that says whether the upgrade may + * switch. `os migrate stored-forms` (`@objectstack/cli`) prints it; it writes + * nothing. The move, the fold and the removal are the ceremony's write half, + * reached only from the upgrade command. + * + * ## The population + * + * Every active environment row of the `form` and `view` types (both + * spellings), read as the effective `form` read reads them: + * `storedFormPlaces` (`protocol-form-reads.ts`), the one reading. Draft `view` + * rows that carry form content are listed apart (`drafts`) and neither moved + * nor deleted: no read serves them, and after the upgrade they cannot be + * published (maintainer ruling `7250982640`). A move names the drafts of the + * row it moves, left behind (`draftsLeftBehind`). + * + * ## Per form name, per package address + * + * A form name is resolved at each address that can serve it, as D5 asks + * "served": each read-only package that ships the name in either type (the + * base), each writable package that ships it or holds a row of it of its own, + * and, when no package addresses it and no stored row of it is bound to a + * package, the environment's own address. Each row is read at the one address + * its binding names ({@link bindingOf}): a pair's declared override at its + * base, a row bound to a package at that package, a package-less row at every + * address of the name. A pair's declared override of a base that ships no + * form of the name is read at the pair's own address, unless a stored row of + * the name is bound to that base: the read then serves the override at the + * base's address, ahead of the bound row, which it serves nowhere, so the + * override is read there ({@link pairServedAtUnshippedBase}; where two pairs + * of the base each hold one, only the pair the read serves there, and the + * other pair's keeps its own address). A row the read serves at another + * address than the package it is bound to is read at each address that + * serves it, and classed by the base it stands over there + * ({@link servedAtAnotherAddress}; ruling record `7254350842`). The rows at + * an address are taken in + * the served-row order (`orderedFormRowsAt`, the order the read serves): the + * first is the served row; the form rows behind it fold into it, and a row + * behind that holds no form at the name (a list) is left as stored (ruling + * 3). A plan names every row of it another address reads too, with that + * address's outcome (`alsoReadAt`). + * + * What the address gets ({@link StoredFormAddressPlan}): + * + * - `keep` — the served row is already a stored `form` row at the + * destination. The rows behind it fold into it. + * - `move` — the served row holds an old-shape form, or a `form` row bound + * elsewhere, that is not internal: it moves to the destination with its + * body as written (D7-a, D7-b), and the rows behind fold into it. At a + * base the destination is the declared `form` override in the base's pair + * (`overrides: { package, basedOn }`), and a pair's own stored `view` + * override keeps its pair and `basedOn` (nothing to ensure); at a writable + * package, that package's own `form` row; at the environment, a + * package-less `form` row (`form` allows a runtime create). A row bound to + * a read-only package that ships no form of the name, or a pair's override + * of a base that ships none, moves into that package's pair as the pair's + * own `form` item, declaring no `overrides` (maintainer ruling + * `7250977204`, `pair_form`). Where both hold one name, the override is + * the served row at the base's address and the bound row folds behind it + * (D7-d): one move, into the pair the override stands in. + * - `remove` — the served row is an internal record form (ADR-0159 D7, all + * three parts: a record-form slot, no `sharing.publicLink`, no + * `type: 'form'` action target, and not over a base form that declares a + * link). A deletion is per row: a row read at several addresses is removed + * only when it is internal at every one of them, and moves at each of them + * otherwise. The upgrade removes it, in the run that switches (ruling 3), + * with the form rows behind it. A row behind that is the served row at + * another address is not one of them: it is not removed with the form in + * front of it, and gets what that address gives it (`servedElsewhere`; + * 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, + * 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}; + * ruling record `7265816895` on #38661). So does a row the read serves at + * more than one address, whatever App each is of, where those addresses + * would not all move it or all remove it: at each of them + * ({@link holdRowsServedApart}); the row behind an internal form left in + * place counts as kept at that address (ruling record 7249158572). A row + * kept as stored under that ruling is folded, moved or removed at no + * address: a plan that would do any of it holds, and lists it apart + * ({@link holdChangesToKeptRows}). + * - `left_in_place` — nothing moves at the address, and nothing is counted: + * 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}). + * + * 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 + * on it (`left_in_place`, `served_unreadable`: the hold is counted once, on + * the row). A name no package ships has the environment's own address only + * while no stored row of it is bound to a package. + * + * ## The fold (D7-d) + * + * The body kept is the served one. A folded row carries one thing only: an + * explicit withdrawal (`formExplicitlyWithdraws`), which the destination takes + * by keeping its own link and switching it off. Where the kept body names no link + * there is no switch to carry, and its replacement of the base keeps the + * address closed already. A withdrawal carried from a row that no layer reads + * today closes a form that is open today: the plan names it `newlyClosed`. + * + * Pure over what the host reads ({@link planStoredForms} is pure over its + * input): no write, no registry mutation. + */ + +import { pairOf, pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; +import { deriveViewContainerObject } from '@objectstack/spec'; +import { + customizationBasePackageId, + customizationDependencyRange, + customizationNamespace, +} from '@objectstack/spec/kernel'; +import { + expandViewContainerWithDiagnostics, + formExplicitlyWithdraws, + isAggregatedViewContainer, + projectViewForms, + publicFormSlug, +} from '@objectstack/spec/ui'; +import { installedManifestsOfEngine } from './installed-manifests.js'; +import { customizationPairEnsureRefusal, kernelPackageScope, type PairRegistry } from './protocol-customization-package.js'; +import { + orderedFormRowsAt, + storedFormPlaces, + type FormReadHost, + type OrderedFormRow, + type StoredFormPlace, +} from './protocol-form-reads.js'; +import { protocolHost, type ProtocolHost } from './protocol-host.js'; +import type { ShipsName } from './suite-moved-overlay.js'; +import type { ObjectStackProtocolImplementation } from './protocol.js'; + +// ── The report's shapes ───────────────────────────────────────────────────── + +/** One stored row, as the report names it. */ +export interface StoredFormRowRef { + /** The row's `type` column (`view` or `form`, either spelling). */ + readonly type: string; + /** The row's own `name` column: a container's name, for a container's form. */ + readonly name: string; + readonly packageId?: string; + /** The form name the row holds here: the name the read serves it under. */ + readonly form: string; + /** `expansion` for a container's member, `item` for a row stored under the name. */ + readonly grain: 'item' | 'expansion'; + /** What the row holds at the name: a form, a list, or a body the projection cannot read. */ + readonly holds: 'form' | 'list' | 'unreadable'; + /** The slug of the `sharing.publicLink` the row's form declares, if any. */ + readonly link?: string; + /** The slug the row's form explicitly withdraws (link kept, a switch `false`), if any. */ + readonly withdraws?: string; + /** The base the row declares it overrides, when it is a pair's declared override. */ + readonly overrideOf?: string; +} + +/** The address a form name is resolved at. */ +export type StoredFormAddress = + | { readonly kind: 'base'; readonly packageId: string } + | { readonly kind: 'package'; readonly packageId: string } + | { readonly kind: 'environment' }; + +/** Where a moved row lands. */ +export type StoredFormDestination = + | { readonly kind: 'pair_override'; readonly base: string; readonly pair: string; readonly basedOn: string } + /** + * The pair's own `form` item, declaring no `overrides`: the destination of + * a row bound to a read-only package that ships no form of the name + * (maintainer ruling `7250977204`, ADR-0146's precedent for a member the + * base does not ship). + */ + | { readonly kind: 'pair_form'; readonly base: string; readonly pair: string } + | { readonly kind: 'package_form'; readonly packageId: string } + | { readonly kind: 'environment_form' }; + +/** Who can remove the cause of a hold (ADR-0159 D7-c). */ +export type StoredFormHoldCause = + /** A cause the administrator removes in the deployment, on the pre-upgrade release. */ + | 'administrator' + /** A cause only the App's author removes: the deployment stays on the current major until then. */ + | 'app_author' + /** A base that has no pair in this version (a kernel package). */ + | 'kernel' + /** A body the projection cannot read (D6 rule 7). */ + | 'unreadable'; + +/** Why an address moves nothing and counts nothing. */ +export type StoredFormLeftReason = + /** The served row carries no form at the name: every row of the name at the address stays (D7-d). */ + | 'served_no_form' + /** {@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'; + +/** A folded row's withdrawal the destination carries (D7-d). */ +export interface StoredFormCarriedWithdrawal { + /** The kept body's own slug: the address the carried withdrawal switches off. */ + readonly slug: string; + readonly from: StoredFormRowRef; +} + +/** Another address that reads a row of this plan, and what it does there (a package-less row is read at every address of its name). */ +export interface StoredFormElsewhere { + readonly row: StoredFormRowRef; + readonly address: StoredFormAddress; + readonly outcome: StoredFormAddressPlan['outcome']; + /** Whether the row is the served row there. */ + readonly served: boolean; +} + +interface StoredFormAddressPlanBase { + readonly form: string; + readonly address: StoredFormAddress; + /** The served row: the one whose body the ceremony keeps or removes. */ + readonly served: StoredFormRowRef; + /** + * The other rows of the name at the address that hold a form, in the + * served-row order: they fold into the served row, or go with its removal. + * A removal takes no row that is the served row at another address: such + * a row is listed apart (`servedElsewhere`), never here. + */ + readonly behind: readonly StoredFormRowRef[]; + /** The rows behind that hold no form at the name (a list, or a body the projection cannot read): the ceremony leaves each as stored (ruling 3). */ + readonly untouched: readonly StoredFormRowRef[]; + /** The rows of this plan that another address reads too, with what that address does. */ + readonly alsoReadAt: readonly StoredFormElsewhere[]; +} + +/** What the ceremony does with one form name at one address. */ +export type StoredFormAddressPlan = + | (StoredFormAddressPlanBase & { + readonly outcome: 'keep' | 'move'; + readonly destination: StoredFormDestination; + /** The withdrawal the destination takes from a folded row, if any. */ + readonly carries?: StoredFormCarriedWithdrawal; + /** Open today, closed by the carried withdrawal: the administrator switches it on again in Setup. */ + readonly newlyClosed: boolean; + /** Drafts of the served row, left behind as stored when it moves. */ + readonly draftsLeftBehind?: readonly StoredFormDraft[]; + /** + * The form rows behind the served row that hold the upgrade where they + * are served: a held row is folded into no other row (ADR-0159 D7), so + * each is listed here and not in `behind`, and takes no part in the fold. + */ + readonly heldApart?: readonly StoredFormRowRef[]; + }) + | (StoredFormAddressPlanBase & { + readonly outcome: 'remove'; + /** The object the record form is of. */ + readonly object?: string; + /** Whether that object declares `fieldGroups` (New and Edit follow them after the removal). */ + readonly objectHasFieldGroups: boolean; + /** + * The form rows behind the removed form that are the served row at + * another address. None is removed with it: each gets what that + * address gives it, which `alsoReadAt` names (ADR-0159 D7-e). + */ + readonly servedElsewhere?: readonly StoredFormRowRef[]; + }) + | (StoredFormAddressPlanBase & { + readonly outcome: 'hold'; + readonly cause: StoredFormHoldCause; + /** + * Why the row holds: the ensure door's own refusal, repeated; or, for a + * hold the planner gives, the slot it would claim with another plan or + * the addresses that serve it and what each would do with it. + */ + readonly refusal: string; + /** The action for the cause. */ + readonly action: string; + /** + * The form rows behind the served row kept as stored under ruling + * record 7249158572 at another address: listed here and not in + * `behind`, since no plan folds or removes them ({@link holdChangesToKeptRows}). + */ + readonly heldApart?: readonly StoredFormRowRef[]; + }) + | (StoredFormAddressPlanBase & { + readonly outcome: 'left_in_place'; + readonly reason: StoredFormLeftReason; + }); + +/** A row that holds the upgrade: the precheck's one entry shape. */ +export interface StoredFormHold { + readonly row: StoredFormRowRef; + /** The base whose pair the move needs; absent for an unreadable body and for a hold the planner gives (a contested slot, a row served apart). */ + readonly base?: string; + readonly cause: StoredFormHoldCause; + readonly refusal: string; + readonly action: string; +} + +/** The census `os migrate stored-forms` prints. */ +export interface StoredFormCensus { + /** One plan per form name and address, ordered by name then address. */ + readonly forms: readonly StoredFormAddressPlan[]; + /** Every stored `view` body the projection cannot read, each holding the upgrade. */ + readonly unreadable: readonly StoredFormHold[]; + /** + * Draft `view` rows that carry form content in an old shape: no read + * serves them, the ceremony neither moves nor deletes them, and after the + * upgrade they cannot be published (maintainer ruling `7250982640`). + */ + readonly drafts: readonly StoredFormDraft[]; + /** A public slug declared by more than one form name across the stored rows (a retired form and its successor, say). */ + readonly sharedSlugs: readonly { readonly slug: string; readonly forms: readonly string[] }[]; + readonly precheck: StoredFormPrecheck; +} + +/** A draft row the report names. */ +export interface StoredFormDraft { + readonly type: string; + readonly name: string; + readonly packageId?: string; +} + +/** Whether the upgrade may switch: it does when no row holds it (ruling 2). */ +export interface StoredFormPrecheck { + readonly canSwitch: boolean; + readonly holds: readonly StoredFormHold[]; + /** The counts per outcome, for the one-line summary. */ + readonly counts: Readonly>; +} + +// ── The planner's input ───────────────────────────────────────────────────── + +/** One package's form of a name, as the registry ships it (either type, through the projection). */ +export interface ShippedForm { + readonly packageId: string; + readonly writable: boolean; + readonly form: Record | undefined; +} + +/** Whether the base's pair can be ensured for the move, and if not, why. */ +export type PairFixReading = + | { readonly ok: true; readonly pair: string; readonly basedOn: string } + | { + readonly ok: false; + readonly cause: PairHoldCause; + readonly refusal: string; + 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 hold causes the pair door's refusal can carry. */ +export type PairHoldCause = Exclude; + +/** Everything {@link planStoredForms} reads: pure data and pure lookups. */ +export interface StoredFormPlanInput { + readonly places: readonly StoredFormPlace[]; + readonly installed: InstalledManifestLookup; + /** The packages that ship `name` as a form, in either type. */ + readonly shippedForms: (name: string) => readonly ShippedForm[]; + readonly isWritable: (packageId: string) => boolean; + /** Every name a `type: 'form'` action opens, anywhere it is declared. */ + readonly actionTargets: ReadonlySet; + readonly pairFix: (base: string) => PairFixReading; + 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[] }[]; + readonly drafts?: readonly StoredFormDraft[]; + /** + * The packages that ship an item of `name` in the `view` type, a list or + * a form in the old shape: the reading the served `view` list takes of + * the name, which {@link servedAtAnotherAddress} asks as that list does. + */ + readonly shipsView: (name: string) => readonly string[]; +} + +// ── The rules ─────────────────────────────────────────────────────────────── + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +/** The slug of the `sharing.publicLink` a form declares, switched on or off. */ +function linkOf(form: unknown): string | undefined { + const sharing = isRecord(form) ? form.sharing : undefined; + const link = isRecord(sharing) ? sharing.publicLink : undefined; + return typeof link === 'string' && link !== '' ? publicFormSlug(link) : undefined; +} + +/** The base a stored body declares it overrides. */ +function declaredOverrideOf(body: unknown): string | undefined { + const overrides = isRecord(body) ? body.overrides : undefined; + const pkg = isRecord(overrides) ? overrides.package : undefined; + return typeof pkg === 'string' && pkg !== '' ? pkg : undefined; +} + +/** + * [ADR-0159 D7] The record-form slots a stored `view` row puts a form in, + * named as the read serves them: the container's default `form`, its + * `formViews.default` and `formViews.create`, an item with `isDefault: true`, + * and any form named `OBJECT.create` — the slots `form-view-internal-not-loaded` + * names. The expansion is the spec's own, so the names are the served ones. + */ +function recordSlotNames(body: unknown): Set { + const out = new Set(); + if (!isRecord(body)) return out; + if (isAggregatedViewContainer(body)) { + const object = deriveViewContainerObject(body); + if (object === undefined) return out; + let expanded: ReturnType; + try { + expanded = expandViewContainerWithDiagnostics(object, body); + } catch { + return out; + } + for (const item of expanded.items) { + if (item.viewKind !== 'form') continue; + if (item.isDefault === true || item.name === `${object}.create`) out.add(item.name); + } + for (const key of ['default', 'create']) { + const entry = isRecord(body.formViews) ? body.formViews[key] : undefined; + if (!isRecord(entry)) continue; + const renamed = expanded.collisions.find((c) => c.viewKind === 'form' && c.key === key)?.renamedTo; + out.add(renamed ?? `${object}.${key}`); + } + return out; + } + const name = typeof body.name === 'string' ? body.name : undefined; + if (body.viewKind === 'form' && name !== undefined) { + const projected = projectViewForms(body).forms.find((f) => f.name === name); + const object = typeof projected?.object === 'string' ? projected.object : undefined; + if (body.isDefault === true || (object !== undefined && name === `${object}.create`)) out.add(name); + } + return out; +} + +function rowRef(row: OrderedFormRow, form: string): StoredFormRowRef { + const { place, holding } = row; + const item = holding.kind === 'form' ? holding.item : undefined; + const link = linkOf(item); + const withdraws = item === undefined ? undefined : formExplicitlyWithdraws(item); + return { + type: place.entry.type, + name: place.entry.name, + ...(place.packageId !== undefined ? { packageId: place.packageId } : {}), + form, + grain: place.grain, + holds: holding.kind === 'form' ? 'form' : holding.reason, + ...(link !== undefined ? { link } : {}), + ...(withdraws !== undefined ? { withdraws } : {}), + ...(row.overrideOf !== undefined ? { overrideOf: row.overrideOf } : {}), + }; +} + +type Binding = + | { readonly kind: 'packageless' } + /** + * `unshipped`: the row is bound to a read-only package that ships no form + * of the name (`packageId` is that package), or is a pair's declared + * override of a base that ships none (`packageId` is the pair). Its + * destination is the pair's own `form` item (maintainer ruling `7250977204`). + */ + | { readonly kind: 'at'; readonly packageId: string; readonly unshipped?: { readonly base: string } } + /** Read at each of `at`, the addresses that serve the row today ({@link servedAtAnotherAddress}). */ + | { readonly kind: 'elsewhere'; readonly at: readonly string[] }; + +/** + * The one address a row of `name` is read at (ADR-0159 D7-d): `packageless` + * for a row bound to no package (read at every address of the name), the + * base for a pair's declared override of a base, the package for a row bound + * to a writable package or to a read-only package that ships the name. A row + * bound to a read-only package that ships no form of the name, or a pair's + * declared override of a base that ships none, is read at the package it is + * bound to (the read seats a slot for every package a stored row is bound + * to), and is marked `unshipped`: its destination is the pair's own `form` + * item (maintainer ruling `7250977204`). One such override is read at its + * base instead, where a stored row seats that address + * ({@link pairServedAtUnshippedBase}, applied over the name's bindings). + */ +function bindingOf( + place: StoredFormPlace, + name: string, + input: Pick, + shipsReadOnly: (packageId: string, name: string) => boolean, +): Binding { + if (place.packageId === undefined) return { kind: 'packageless' }; + const base = declaredOverrideOf(place.entry.data); + if (base !== undefined && base !== place.packageId && pairsOf(base, input.installed).includes(place.packageId)) { + return shipsReadOnly(base, name) ? { kind: 'at', packageId: base } : { kind: 'at', packageId: place.packageId, unshipped: { base } }; + } + if (input.isWritable(place.packageId)) return { kind: 'at', packageId: place.packageId }; + return shipsReadOnly(place.packageId, name) + ? { kind: 'at', packageId: place.packageId } + : { kind: 'at', packageId: place.packageId, unshipped: { base: place.packageId } }; +} + +/** + * [ADR-0159 D7; ruling record 7254350842 on #37111] The rows of `name` the + * read serves at another address than the package each is bound to, with + * those addresses: THE one place this case is decided. The question is put + * to the served-row order at every package that ships the form + * (`orderedFormRowsAt` asked with `ships`; `suite-moved-overlay.ts` has the + * rule), so a row two of them serve is read at both, and where the read + * serves neither of two rows that could each follow the name, neither is + * here: each keeps its own address. + * + * Such a row is classed by the base it stands over at each address (D7-b) + * and takes the destination D7 gives a row bound to that base, with D7-c's + * hold where its pair cannot be ensured; D7-e is unchanged, and ruling + * `7250977204` stands for every row its premise holds for. + */ +function servedAtAnotherAddress( + holding: readonly StoredFormPlace[], + name: string, + formShippers: readonly string[], + installed: InstalledManifestLookup, + ships: ShipsName, +): Map { + const out = new Map(); + for (const shipper of formShippers) { + for (const row of orderedFormRowsAt(holding, name, shipper, installed, undefined, ships)) { + if (row.moved !== undefined) out.set(row.place, [...(out.get(row.place) ?? []), shipper]); + } + } + return out; +} + +/** + * [ADR-0159 D7-d; maintainer ruling `7250977204`] A pair's declared override + * of a base that ships no form of the name, where a stored row of the name + * is bound to that base: THE one place this case is decided. It answers the + * pair whose overrides are read at the base's address, or `undefined` when + * none is. + * + * The read seats a slot for every package a stored row is bound to + * (`mergePackageAwareOverlay`), and at that slot the served-row order tries + * the pair's declared override first, whether or not the base ships the name + * (`isServedOverrideRowOf` does not ask). So the override is the row served + * at the base's address, and the row bound to the base is served nowhere. + * Read at the base's address, the override is the served row there, the + * bound row folds behind it, and one move goes to the pair's own `form` + * item. Read apart, at two addresses, each row would move there, and the + * ceremony would serve a body the read does not serve today (D7-d). + * + * Only the pair the order serves at the base's address is read there, with + * every override of the base it holds at the name (a `form` row ahead of a + * `view` row, as the order has them). The App's pair and an earlier + * per-package pair can each hold one: the second pair's is not served at the + * base, and stays at its own pair's address, where the read serves it. With + * no stored row bound to the base, nothing seats its address, and every such + * override stays at its own pair's. + */ +function pairServedAtUnshippedBase( + places: readonly StoredFormPlace[], + name: string, + base: string, + installed: InstalledManifestLookup, +): string | undefined { + if (!places.some((place) => place.packageId === base && place.holds.has(name))) return undefined; + // The served-row order at the base's address, over every stored row: the read's own order. + const [first] = orderedFormRowsAt(places, name, base, installed); + return first !== undefined && first.overrideOf === base ? first.place.packageId : undefined; +} + +/** + * [ADR-0159 D7-d] The row the read serves at `packageId`'s address, where + * that row is one the plan reads at other addresses and not at this one: + * THE one place this case is decided. It answers that row, or `undefined` + * when the address's served row is one of its own. + * + * The plan keeps each row to the addresses its binding names, so at the + * address of a package a row is bound to it orders the rows bound there + * alone. D7-d finds the served row among every stored row at the address: + * where the read's own order there is headed by a row the plan reads + * elsewhere ({@link servedAtAnotherAddress}), every row bound to this + * address stands behind it and is served nowhere today. Such a row folds + * behind that row where that row is planned, and the address gets no plan + * of its own: a body the read does not serve today is never served by the + * ceremony. + * + * `layer` is the row the package's per-package layer reads today: the first + * row of the order that is not the pair's override. A withdrawal carried + * from it closes its name today ({@link foldOf}); one carried from another + * row bound to the address is read by no layer. + */ +function servedAheadFromElsewhere( + places: readonly StoredFormPlace[], + name: string, + packageId: string, + bindings: ReadonlyMap, + installed: InstalledManifestLookup, + ships: ShipsName, +): { readonly at: readonly string[]; readonly layer: StoredFormPlace | undefined } | undefined { + // The served-row order at the address, over every stored row: the read's own order. + const order = orderedFormRowsAt(places, name, packageId, installed, undefined, ships); + const binding = order[0] === undefined ? undefined : bindings.get(order[0].place); + if (binding?.kind !== 'elsewhere' || binding.at.includes(packageId)) return undefined; + return { at: binding.at, layer: order.find((row) => row.overrideOf === undefined)?.place }; +} + +/** + * [ADR-0159 D7-d; maintainer ruling 「两行都不动,写进报告」, ruling record + * 7249158572 on #37111] An internal record form is the served row, and a row + * behind it at the same address declares a `sharing.publicLink`, switched on + * or off: THE one place this case is decided. Neither row moves and no row of + * the name is deleted; the report names both as left in place (the internal + * form is not removed because a row with a public link stands behind it), and + * the upgrade is not held — a "not counted" kind beside the two of ruling + * 7136809727 and the one ADR-0159 adds, on the same whole-name-left branch. + * + * The ruling answers the package-less row behind; the predicate is wider (any + * linked row behind, e.g. a base-bound one behind an internal pair override), + * which is ADR-0159 D7-d's own reading of that ruling, open to correction. + * Narrowing it would send those shapes to the removal branch, which deletes + * the row that holds the address closed. + * + * Whatever the answer, the address answers `404` on both doors before and + * after the ceremony: the served internal row serves no link, and a body not + * served today is never served by the ceremony. + */ +export const INTERNAL_AHEAD_OF_LINKED_ROW = { + /** Whether the case applies: the served row is internal, and a row behind it declares a link. */ + applies: (servedIsInternal: boolean, behind: readonly StoredFormRowRef[]): boolean => + servedIsInternal && behind.some((row) => row.link !== undefined), + /** What the address gets: option D, left in place and not counted. */ + outcome: 'left_in_place' as const, + reason: 'internal_ahead_of_linked_row' as const, +}; + +/** + * [ADR-0159 D7-c] The action an administrator reads for a hold's cause. + * `contested`: the hold of a pair's slot that more than one plan claims + * ({@link holdContestedPairSlots}), for a row read at two addresses or for + * a slot other rows claim too; `kept`, the hold of a plan that would change a + * row kept as stored at another address ({@link holdChangesToKeptRows}), + * worded as the slot's where `app` is given. + */ +export function storedFormHoldAction( + cause: StoredFormHoldCause, + detail: { + base?: string; pair?: string; app?: string; earlierPair?: boolean; contested?: 'two_addresses' | 'slot' | 'kept'; + /** + * Where a held row is served, when that is not packages of one App that + * can be read: the Apps that can be read, the bases whose App cannot be, + * the packages this environment writes, and whether the environment's + * own address is among them. + */ + apps?: StoredFormServedApps; + } = {}, +): string { + switch (cause) { + case 'administrator': + // [maintainer ruling 7250982640] The earlier per-package pair: no + // command on this release re-identifies it, so nothing clears it here. + if (detail.earlierPair === true) { + return 'The row holds the upgrade until the paired customization package an earlier version created is re-identified as' + + ' the App\'s pair (ADR-0146 D3, merge question 12), and no command on this release does that. The row keeps answering' + + ' as it does today meanwhile.'; + } + return `Remove the cause the refusal names on this release, then run the upgrade command again: the row then moves` + + `${detail.pair !== undefined ? ` into '${detail.pair}'` : ' into the base\'s paired customization package'} with its body as written.`; + case 'app_author': + // The slot case and a row served apart: no exit was measured, so the + // action promises none (step 4 of #38661; ruling 7250982640's precedent). + if (detail.contested === 'kept' && detail.apps !== undefined) { + // The row the precheck names is served at the plan's address only; the kept row is kept at another. + return `The addresses this cause spans are ${servedAppsWords(detail.apps)}, so no one App's author can remove it alone.` + + ` ${NO_MEASURED_EXIT}`; + } + if (detail.contested !== undefined && detail.apps !== undefined) { + return `This row is served at ${servedAppsWords(detail.apps)}, so no one App's author can remove this cause alone.` + + ` ${NO_MEASURED_EXIT}`; + } + if (detail.contested === 'slot' || detail.contested === 'kept') { + return `The cause is in the App${detail.app !== undefined ? ` '${detail.app}'` : ''}, its author's to remove. ${NO_MEASURED_EXIT}`; + } + if (detail.contested === 'two_addresses') { + // Measured (step 8 of #38661): a row read at two packages of one App is read at one once only one of them ships the form. + return `Only the author of the App${detail.app !== undefined ? ` '${detail.app}'` : ''} can remove this cause. The deployment stays on` + + ' the release it is running until the App ships the form from one of these packages only: the row is then read at that' + + ' address alone and takes what that address gives it. Every address keeps answering as it does today meanwhile.'; + } + return `Only the author of the App${detail.app !== undefined ? ` '${detail.app}'` : ''} can remove this cause. The deployment stays on` + + ' the release it is running until the App ships a version without it; the row keeps closing what it closes today meanwhile.'; + case 'kernel': + return `'${detail.base ?? 'The base'}' is a kernel package and has no paired customization package in this version, so no action` + + ' moves the row: report it to the platform maintainers before upgrading.'; + case 'unreadable': + return 'Save the view again on this release with its form content repaired (a `form` or `formViews` entry that is an' + + ' object), then run the upgrade command again: the row then moves.'; + } +} + +/** The sentence of an action whose cause has no measured exit. */ +const NO_MEASURED_EXIT = 'No action on this release clears it, and no exit from it was measured. The deployment stays on the release it is' + + ' running, and every address keeps answering as it does today meanwhile.'; + +/** Where a held row is served, when that is not packages of one App that can be read. */ +export interface StoredFormServedApps { + readonly named: readonly string[]; + readonly unreadable: readonly string[]; + readonly writable: readonly string[]; + readonly environment: boolean; +} + +function servedAppsWords(apps: StoredFormServedApps): string { + const quoted = (ids: readonly string[]): string => ids.map((id) => `'${id}'`).join(' and '); + return [ + ...(apps.named.length > 0 ? [`packages of ${apps.named.length > 1 ? 'the Apps' : 'the App'} ${quoted(apps.named)}`] : []), + ...(apps.unreadable.length > 0 ? [`${quoted(apps.unreadable)}, whose App cannot be read`] : []), + ...(apps.writable.length > 0 ? [`${quoted(apps.writable)}, which this environment writes`] : []), + ...(apps.environment ? ['the environment'] : []), + ].join(', and '); +} + +/** A row as a refusal names it. */ +function rowWords(row: StoredFormRowRef): string { + return `${row.type} row '${row.name}'${row.packageId !== undefined ? ` bound to '${row.packageId}'` : ' bound to no package'}`; +} + +/** An address as a refusal names it. */ +function addressWords(address: StoredFormAddress): string { + return address.kind === 'environment' ? 'the environment' : `'${address.packageId}'`; +} + +/** The App a base is of, where its pair id can be read; `undefined` for a base whose App cannot be read. */ +function appAt( + address: StoredFormAddress & { kind: 'base' }, + pairFix: StoredFormPlanInput['pairFix'], + installed: InstalledManifestLookup, +): string | undefined { + const fix = pairFix(address.packageId); + // A base whose pair the ensure door refuses still has the App's pair id + // where its App can be read: the address is then of that App all the same. + const pair = fix.ok ? fix.pair : (() => { const id = pairOf(address.packageId, installed); return id.ok ? id.value : undefined; })(); + return pair === undefined ? undefined : customizationBasePackageId(pair) ?? undefined; +} + +/** Turns a plan into a hold, with the refusal and action given (the App author's cause unless another is given). */ +function holdPlan( + plans: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[], + index: number, + refusal: string, + action: string, + cause: StoredFormHoldCause = 'app_author', +): void { + const { plan, rows } = plans[index]!; + plans[index] = { + plan: { + form: plan.form, address: plan.address, served: plan.served, behind: plan.behind, untouched: plan.untouched, alsoReadAt: plan.alsoReadAt, + outcome: 'hold', cause, refusal, action, + }, + rows, + }; +} + +/** + * [ADR-0159 D7; maintainer ruling 「A 拦住升级·同类全覆盖」, ruling record + * 7265816895 on #38661] A slot of a pair that more than one plan of a name + * claims: THE one place this case is decided. A pair holds one row of a type + * and name, and a row declares one base (ADR-0146 D2), so no claimant has a + * destination. Each claimant's plan holds the upgrade instead, and the + * precheck names each claimant's row once: a row the read serves at two + * addresses of one App (its two plans claim the App's one pair), and two rows + * whose plans each land in one pair. Nothing moves, and every address answers + * as it does today. A row the read serves at two addresses that would treat + * it differently is {@link holdRowsServedApart}'s. + * + * The cause is the App author's (`app_author`): no administrator's exit that + * leaves every address's answer as it is was measured. One exit was measured, + * for one row read at two addresses of one App with no other row at the + * slot: once the App ships the form from one of those packages only, the row + * is read at that address alone and takes what that address gives it. Every + * other slot's action names no exit. A row one of whose plans already holds + * elsewhere is named by that hold, not a second time. No new cause, plan kind + * or "not counted" kind comes with it. + */ +function holdContestedPairSlots( + name: string, + plans: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[], + holds: StoredFormHold[], +): void { + // A slot is a pair's one row of the name: a declared override or the pair's + // own `form` item, and the pair's own row read at the pair's own address + // (a writable package's `form` row, declaring no `overrides`) as well. + const slotOf = (plan: StoredFormAddressPlan): string | undefined => { + if (plan.outcome !== 'keep' && plan.outcome !== 'move') return undefined; + const { destination } = plan; + if (destination.kind === 'pair_override' || destination.kind === 'pair_form') return destination.pair; + if (destination.kind === 'package_form' && customizationBasePackageId(destination.packageId) !== null) return destination.packageId; + return undefined; + }; + const bySlot = new Map(); + plans.forEach(({ plan }, index) => { + const slot = slotOf(plan); + if (slot !== undefined) bySlot.set(slot, [...(bySlot.get(slot) ?? []), index]); + }); + for (const [pair, claimants] of bySlot) { + if (claimants.length < 2) continue; + // The rows held at this slot, each with the plans of it that claim the slot. + const held = new Map(); + for (const index of claimants) { + const { plan, rows } = plans[index]!; + const entry = held.get(rows[0]!.place) ?? { row: plan.served, plans: [] }; + entry.plans.push(index); + held.set(rows[0]!.place, entry); + } + for (const [place, { row, plans: served }] of held) { + const at = served.map((index) => plans[index]!.plan.address); + const others = [...held].filter(([other]) => other !== place).map(([, entry]) => entry.row); + const refusal = (at.length > 1 + ? `The read serves ${rowWords(row)} at ${at.map(addressWords).join(' and ')}, and a move into '${pair}' under the name '${name}' is planned for it at more than one of them.` + : `${rowWords(row)} ${plans[served[0]!]!.plan.outcome === 'keep' ? 'already stands in' : 'would move into'} '${pair}' under the name '${name}'.`) + + (others.length > 0 ? ` The same slot is claimed for ${others.map(rowWords).join(' and ')}.` : '') + + ' A pair holds one row of a type and name, and a row declares one base (ADR-0146 D2), so no destination can be given.'; + const app = customizationBasePackageId(pair) ?? undefined; + // The two-address exit was measured for one row alone at the slot (step 8 of #38661); with another + // row claiming it too, the slot's sentence, which names no exit. + // ...and only where no address outside the slot serves the row too (then it is not read at one address alone). + const servedOutside = plans.some(({ rows }, index) => !served.includes(index) && rows[0]?.place === place); + const action = storedFormHoldAction('app_author', { contested: at.length > 1 && others.length === 0 && !servedOutside ? 'two_addresses' : 'slot', ...(app !== undefined ? { app } : {}) }); + for (const index of served) holdPlan(plans, index, refusal, action); + // A row one of whose plans already holds elsewhere (the pair door) is named by that hold, not a second time. + const namedElsewhere = plans.some(({ plan, rows }, index) => !served.includes(index) && plan.outcome === 'hold' && rows[0]?.place === place); + if (!namedElsewhere) holds.push({ row, cause: 'app_author', refusal, action }); + } + } +} + +/** + * [ADR-0159 D7, D7-d, D7-e; ruling record 7265816895 on #38661] A stored row + * the read serves at more than one address, where those addresses would not + * all do the same to it: THE one place this case is decided. 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 away from every address + * that serves it, so it is planned only where every such address would move + * the row (each into its own destination) or every one would remove it. Where + * one would move or remove it and another keeps it (an internal form left in + * place ahead of a linked row, ruling record 7249158572; a row already at its + * destination; a plan that holds, a base whose App cannot be read among + * them), or one would move it and another remove it, every plan of the row + * holds the upgrade, nothing is moved or removed, and every address answers + * as it does today. The precheck names the row once, with every address, + * unless one of its plans already holds and names it. + * + * Where a plan of the row already holds (the pair door, or a contested + * slot), the other plans wait on that hold: they take its cause and its + * action, and the refusal names the address it stands at; clearing it is + * what lets the row be planned again. Otherwise the cause is the App + * author's (`app_author`) and no exit was measured: the action names the App + * where every address is a base of one App that can be read, and otherwise + * says where the row is served (each App that can be read, each base whose + * App cannot be, each package this environment writes) and promises nothing. + */ +function holdRowsServedApart( + name: string, + plans: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[], + holds: StoredFormHold[], + pairFix: StoredFormPlanInput['pairFix'], + installed: InstalledManifestLookup, +): void { + // Every row of the name with the plans that serve it, and the plans that + // keep it behind an internal form they leave in place (ruling record + // 7249158572, 「两行都不动」: both rows stay, so that address keeps the row + // behind as it keeps the one it serves; the seat's reading, with 7265816895). + const byRow = new Map(); + const add = (place: StoredFormPlace, entry: { index: number; behind: boolean }): void => { + byRow.set(place, [...(byRow.get(place) ?? []), entry]); + }; + plans.forEach(({ plan, rows }, index) => { + const place = rows[0]?.place; + if (place !== undefined) add(place, { index, behind: false }); + if (plan.outcome === 'left_in_place' && plan.reason === INTERNAL_AHEAD_OF_LINKED_ROW.reason) { + for (const row of rows.slice(1)) if (row.holding.kind === 'form') add(row.place, { index, behind: true }); + } + }); + const words: Record = { + move: 'moved', remove: 'removed', keep: 'kept as it is', left_in_place: 'kept as it is', hold: 'held', + }; + // What each plan did before this pass, and the rows each hold is for: a plan + // held here for one row (a row kept behind its internal form, say) is no + // hold of another row's, which waits only on a hold taken for itself. + const before = plans.map(({ plan }) => plan.outcome); + const heldFor = new Map>(); + plans.forEach(({ plan, rows }, index) => { + if (plan.outcome === 'hold' && rows[0] !== undefined) heldFor.set(index, new Set([rows[0].place])); + }); + for (const [place, entries] of byRow) { + if (entries.length < 2) continue; + // A row kept behind counts as left in place there, whatever that plan serves or holds for. + const outcomeOf = ({ index, behind }: { index: number; behind: boolean }): StoredFormAddressPlan['outcome'] => { + if (heldFor.get(index)?.has(place) === true) return 'hold'; + return behind ? 'left_in_place' : before[index]!; + }; + const outcomes = entries.map(outcomeOf); + if (!outcomes.some((outcome) => outcome === 'move' || outcome === 'remove')) continue; + if (outcomes.every((outcome) => outcome === 'move') || outcomes.every((outcome) => outcome === 'remove')) continue; + const involved = [...new Set(entries.map((e) => e.index))]; + const held = involved.filter((index) => plans[index]!.plan.outcome !== 'hold'); + for (const index of involved) heldFor.set(index, new Set([...(heldFor.get(index) ?? []), place])); + const at = entries.map((e) => plans[e.index]!.plan.address); + const servedEntry = entries.find((e) => !e.behind); + const row = servedEntry !== undefined ? plans[servedEntry.index]!.plan.served : rowRefOf(plans[entries[0]!.index]!.rows, place, name); + const keptBehind = entries.filter((e) => e.behind).map((e) => addressWords(plans[e.index]!.plan.address)); + const byWord = new Map(); + entries.forEach((entry, i) => { + const word = entry.behind && outcomes[i] === 'left_in_place' ? 'kept as it is behind the internal form left in place' : words[outcomes[i]!]; + byWord.set(word, [...(byWord.get(word) ?? []), addressWords(plans[entry.index]!.plan.address)]); + }); + const servedAt = entries.filter((e) => !e.behind).map((e) => addressWords(plans[e.index]!.plan.address)); + const refusal = `The read serves ${rowWords(row)} at ${servedAt.join(' and ')}` + + (keptBehind.length > 0 ? `, and keeps it behind the internal form left in place at ${keptBehind.join(' and ')},` : '') + + ` under the name '${name}': it would be` + + ` ${[...byWord].map(([word, addresses]) => `${word} at ${addresses.join(' and ')}`).join(', and ')}.` + + ' A move or a removal takes the row from every address that serves it, so it is planned only where every one of them would do the same.' + + (keptBehind.length > 0 ? ` Under ruling 7249158572 both rows stay where an internal form is left in place ahead of it, at ${keptBehind.join(' and ')}.` : ''); + const waitsOn = entries.find((_entry, i) => outcomes[i] === 'hold'); + // Clearing that hold lets the row be planned only where every other address would move it, as the hold's own plan + // would then (measured for two addresses); otherwise the row would still be served apart, and the hold's action + // says more than was measured. + const clearsWithIt = waitsOn !== undefined && entries.every((e, i) => e.index === waitsOn.index || outcomes[i] === 'move'); + if (waitsOn !== undefined && clearsWithIt) { + if (held.length === 0) continue; + // Another plan of the row already holds: this one waits on that hold, its cause and its action. + const holding = plans[waitsOn.index]!.plan as StoredFormAddressPlan & { outcome: 'hold' }; + const waiting = `${refusal} It holds at ${addressWords(holding.address)}, so it is planned at none of them until that hold is cleared: ${holding.refusal}`; + for (const index of held) holdPlan(plans, index, waiting, holding.action, holding.cause); + continue; + } + const { apps, oneApp } = servedAppsAt(at, pairFix, installed); + // The exit step 8 measured is for a row served (not kept behind) at two packages of one App. + const measured = oneApp !== undefined && outcomes.includes('move') && keptBehind.length === 0 && waitsOn === undefined; + const action = storedFormHoldAction('app_author', oneApp !== undefined + ? { contested: measured ? 'two_addresses' : 'slot', app: oneApp } + : { contested: 'slot', apps }); + for (const index of held) holdPlan(plans, index, refusal, action); + if (waitsOn === undefined) holds.push({ row, cause: 'app_author', refusal, action }); + } +} + +/** The Apps, unreadable bases, writable packages and environment among `at`, and the one App where every address is a base or pair of it. */ +function servedAppsAt( + at: readonly StoredFormAddress[], + pairFix: StoredFormPlanInput['pairFix'], + installed: InstalledManifestLookup, +): { apps: StoredFormServedApps; oneApp?: string } { + const named = new Set(); + const unreadable: string[] = []; + const writable: string[] = []; + let environment = false; + for (const address of at) { + if (address.kind === 'environment') environment = true; + else if (address.kind === 'package') { + const app = customizationBasePackageId(address.packageId); + if (app !== null) named.add(app); + else if (!writable.includes(address.packageId)) writable.push(address.packageId); + } else { + const app = appAt(address, pairFix, installed); + if (app !== undefined) named.add(app); + else if (!unreadable.includes(address.packageId)) unreadable.push(address.packageId); + } + } + const oneApp = named.size === 1 && unreadable.length === 0 && writable.length === 0 && !environment ? [...named][0] : undefined; + return { apps: { named: [...named], unreadable, writable, environment }, ...(oneApp !== undefined ? { oneApp } : {}) }; +} + +/** + * Each row kept as stored under ruling record 7249158572, with the index of + * the plan that keeps it: the served row of a plan that leaves an internal + * form in place ahead of a linked row, and every form row behind it there. + * Read before any hold is given, so a plan held afterwards still keeps them. + */ +function keptRowsOf(plans: readonly { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[]): Map { + const kept = new Map(); + plans.forEach(({ plan, rows }, index) => { + if (plan.outcome !== 'left_in_place' || plan.reason !== INTERNAL_AHEAD_OF_LINKED_ROW.reason) return; + for (const row of rows) if (row.holding.kind === 'form' && !kept.has(row.place)) kept.set(row.place, index); + }); + return kept; +} + +/** Whether two references name the same stored row. */ +function sameRow(a: StoredFormRowRef, b: StoredFormRowRef): boolean { + return a.type === b.type && a.name === b.name && a.packageId === b.packageId && a.grain === b.grain; +} + +/** + * The rows kept as stored under ruling record 7249158572 that a plan would + * fold, move or remove, each with what the plan would do to it. THE one + * predicate {@link holdChangesToKeptRows} reads. + */ +function keptRowsChanged( + plan: StoredFormAddressPlan, + rows: readonly OrderedFormRow[], + kept: ReadonlyMap, +): { row: OrderedFormRow; behind: boolean; would: string }[] { + if (plan.outcome === 'hold' || plan.outcome === 'left_in_place') return []; + const [first, ...rest] = rows; + const out: { row: OrderedFormRow; behind: boolean; would: string }[] = []; + if (first !== undefined && kept.has(first.place)) { + if (plan.outcome === 'move') out.push({ row: first, behind: false, would: 'moved' }); + else if (plan.outcome === 'remove') out.push({ row: first, behind: false, would: 'removed' }); + else if (plan.carries !== undefined) out.push({ row: first, behind: false, would: 'given the withdrawal of a row folded into it' }); + } + for (const row of rest) { + if (row.holding.kind !== 'form' || !kept.has(row.place)) continue; + const ref = rowRef(row, plan.form); + if (plan.outcome === 'remove') { + if (plan.behind.some((b) => sameRow(b, ref))) out.push({ row, behind: true, would: `removed with ${rowWords(plan.served)}` }); + } else { + out.push({ row, behind: true, would: `folded into ${rowWords(plan.served)}` }); + } + } + return out; +} + +/** + * [ADR-0159 D7, D7-d; ruling record 7249158572, 「两行都不动」; the seat's + * step] A row kept as stored under the ruling (the internal form left in place + * ahead of a linked row, and every form row behind it there) is kept so at + * every address: no plan folds it, moves it or removes it. A plan that would + * do any of it holds the upgrade (`app_author`; no exit was measured), its + * refusal names the row, the address that keeps it and what the plan would + * do, and a kept row standing behind its served row is listed apart + * (`heldApart`), not in `behind`. The precheck names each such plan's served + * row once. Runs after {@link holdRowsServedApart}: a plan that already holds + * keeps its own hold, and lists a kept row behind it apart all the same. + */ +function holdChangesToKeptRows( + name: string, + plans: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[], + kept: ReadonlyMap, + holds: StoredFormHold[], + pairFix: StoredFormPlanInput['pairFix'], + installed: InstalledManifestLookup, +): void { + if (kept.size === 0) return; + plans.forEach(({ plan, rows }, index) => { + const changed = keptRowsChanged(plan, rows, kept); + if (changed.length > 0) { + const keepers = [...new Set(changed.map(({ row }) => kept.get(row.place)!))]; + const refusal = changed.map(({ row, would }) => + `${rowWords(rowRef(row, name))} is kept as stored at ${addressWords(plans[kept.get(row.place)!]!.plan.address)} under ruling 7249158572` + + ` (an internal form left in place ahead of a linked row: both rows stay as stored); at ${addressWords(plan.address)} it would be ${would}.`).join(' ') + + ` A row kept under that ruling is folded, moved or removed at no address, so the plan for '${name}' at ${addressWords(plan.address)} is not made.`; + const { apps, oneApp } = servedAppsAt([plan.address, ...keepers.map((k) => plans[k]!.plan.address)], pairFix, installed); + const action = storedFormHoldAction('app_author', oneApp !== undefined ? { contested: 'kept', app: oneApp } : { contested: 'kept', apps }); + holdPlan(plans, index, refusal, action); + holds.push({ row: plan.served, cause: 'app_author', refusal, action }); + } + // A kept row behind a held plan is listed apart there, whatever holds it. + const held = plans[index]!.plan; + if (held.outcome !== 'hold') return; + const apart = rows.slice(1).filter((row) => row.holding.kind === 'form' && kept.has(row.place)).map((row) => rowRef(row, name)); + if (apart.length === 0) return; + plans[index] = { + plan: { ...held, behind: held.behind.filter((b) => !apart.some((a) => sameRow(a, b))), heldApart: apart }, + rows, + }; + }); +} + +/** A row's reference from the rows of a plan, by its place. */ +function rowRefOf(rows: readonly OrderedFormRow[], place: StoredFormPlace, name: string): StoredFormRowRef { + return rowRef(rows.find((row) => row.place === place)!, name); +} + +/** + * [ADR-0159 D7] The pure planner: one {@link StoredFormAddressPlan} per form + * name and address, the holds, and the precheck. See the module header for + * the rules. + */ +export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { + const shippedCache = new Map(); + const shipped = (name: string): readonly ShippedForm[] => { + let hit = shippedCache.get(name); + if (hit === undefined) { + hit = input.shippedForms(name); + shippedCache.set(name, hit); + } + return hit; + }; + const shipsReadOnly = (packageId: string, name: string): boolean => + shipped(name).some((s) => s.packageId === packageId && !s.writable); + const addressKey = (address: StoredFormAddress): string => (address.kind === 'environment' ? '' : address.packageId); + const ships = (address: StoredFormAddress, name: string): boolean => + address.kind !== 'environment' && shipped(name).some((s) => s.packageId === address.packageId); + + // The names some stored row holds a form at, and the names a package + // ships as a form that a stored row holds a list at (D7-d: the list is + // served ahead of the form, and is reported left in place). A name only + // lists are stored at, and no package ships as a form, is a list's. + const names = new Set(); + for (const place of input.places) { + for (const [name, holding] of place.holds) { + if (holding.kind === 'form' || shipped(name).length > 0) names.add(name); + } + } + + const forms: StoredFormAddressPlan[] = []; + const holds: StoredFormHold[] = []; + + for (const name of [...names].sort()) { + const holding = input.places.filter((place) => place.holds.has(name)); + const bindings = new Map(); + const formShippers = shipped(name).map((s) => s.packageId).sort(); + const viewShippers = input.shipsView(name); + const shipsInView: ShipsName = { item: (p) => viewShippers.includes(p), name: (p) => viewShippers.includes(p) }; + const servedAt = servedAtAnotherAddress(holding, name, formShippers, input.installed, shipsInView); + for (const place of holding) { + const own = bindingOf(place, name, input, shipsReadOnly); + const at = servedAt.get(place); + if (at === undefined) { + bindings.set(place, own); + continue; + } + // The read may serve the row at the package it is stored against + // as well: that address is then one of the row's. + const ownToo = own.kind === 'at' && own.unshipped === undefined && formShippers.includes(own.packageId); + bindings.set(place, { kind: 'elsewhere', at: ownToo ? [own.packageId, ...at] : at }); + } + // A pair's declared override of a base that ships no form of the name + // is read at that base's address where a stored row seats it: the + // read serves the override there, ahead of the row bound to the base. + const overriddenUnshipped = new Set(); + for (const binding of bindings.values()) { + if (binding.kind === 'at' && binding.unshipped !== undefined && binding.unshipped.base !== binding.packageId) { + overriddenUnshipped.add(binding.unshipped.base); + } + } + for (const base of overriddenUnshipped) { + const pair = pairServedAtUnshippedBase(input.places, name, base, input.installed); + if (pair === undefined) continue; + for (const [place, binding] of bindings) { + if (binding.kind === 'at' && binding.packageId === pair && binding.unshipped?.base === base) { + bindings.set(place, { kind: 'at', packageId: base, unshipped: { base } }); + } + } + } + + // The addresses of the name. The environment's own address is the + // name's only when no stored row of it is bound to a package: a row + // bound to one is served there, and a package-less row beside it is + // read nowhere (the read seats a slot per bound package). + const addresses: StoredFormAddress[] = []; + const seen = new Set(); + const add = (address: StoredFormAddress): void => { + if (seen.has(addressKey(address))) return; + seen.add(addressKey(address)); + addresses.push(address); + }; + for (const s of shipped(name)) add(s.writable ? { kind: 'package', packageId: s.packageId } : { kind: 'base', packageId: s.packageId }); + for (const [, binding] of bindings) { + // A row served elsewhere is read at packages that ship the form: each is an address already. + if (binding.kind !== 'at') continue; + add(input.isWritable(binding.packageId) ? { kind: 'package', packageId: binding.packageId } : { kind: 'base', packageId: binding.packageId }); + } + const bound = [...bindings.values()].some((b) => b.kind !== 'packageless'); + if (addresses.length === 0 && !bound) add({ kind: 'environment' }); + + // The rows each address reads, and the addresses each row is read at. + const rowsAt = new Map(); + const readAt = new Map(); + for (const address of addresses) { + const at = address.kind === 'environment' ? null : address.packageId; + const rows = orderedFormRowsAt(input.places, name, at, input.installed, (place) => { + const binding = bindings.get(place); + if (binding === undefined) return false; + if (binding.kind === 'packageless') return true; + if (binding.kind === 'elsewhere') return at !== null && binding.at.includes(at); + return binding.packageId === at; + }, shipsInView); + rowsAt.set(addressKey(address), rows); + } + // A row bound to an address whose served row the plan reads + // elsewhere folds behind that row where it is planned; the address + // gets no plan of its own (D7-d). + // Each folded row, and whether its own package's layer reads it today. + const folded = new Map(); + for (const address of addresses) { + if (address.kind === 'environment') continue; + const ahead = servedAheadFromElsewhere(input.places, name, address.packageId, bindings, input.installed, shipsInView); + if (ahead === undefined) continue; + const behindAhead = rowsAt.get(addressKey(address))!.filter((row) => { + const binding = bindings.get(row.place); + return binding?.kind === 'at' && binding.packageId === address.packageId; + }); + rowsAt.set(addressKey(address), []); + for (const at of ahead.at) { + const rows = rowsAt.get(at) ?? []; + rowsAt.set(at, [...rows, ...behindAhead.filter((row) => !rows.some((r) => r.place === row.place))]); + } + for (const row of behindAhead) folded.set(row.place, row.place === ahead.layer); + } + for (const address of addresses) { + for (const row of rowsAt.get(addressKey(address))!) readAt.set(row.place, [...(readAt.get(row.place) ?? []), address]); + } + /** Whether `place` is the served row at an address of the name other than `here`. */ + const servedAtAnother = (place: StoredFormPlace, here: StoredFormAddress): boolean => + addresses.some((other) => other !== here && rowsAt.get(addressKey(other))?.[0]?.place === place); + + const plansOfName: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[] = []; + 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 + // move, unless the address ships the form a list stands over. + if (rows.length === 0) continue; + if (!rows.some((row) => row.holding.kind === 'form') && !ships(address, name)) continue; + const [first, ...rest] = rows; + const formRows = rest.filter((row) => row.holding.kind === 'form'); + const served = rowRef(first!, name); + const behind = formRows.map((row) => rowRef(row, name)); + const untouched = rest.filter((row) => row.holding.kind !== 'form').map((row) => rowRef(row, name)); + const base = { form: name, address, served, behind, untouched, alsoReadAt: [] as StoredFormElsewhere[] }; + const push = (plan: StoredFormAddressPlan): void => { plansOfName.push({ plan, rows }); }; + + if (first!.holding.kind === 'closed') { + push({ ...base, outcome: 'left_in_place', reason: first!.holding.reason === 'list' ? 'served_no_form' : 'served_unreadable' }); + continue; + } + const body = first!.holding.item; + // A pair's stored `view` override keeps its package, its name and + // its `overrides` declaration, `basedOn` unchanged (D7): nothing to + // ensure, so the pair door is not asked. + // A row the read serves here although it is stored against + // another package declares, or is bound to, that package, not + // this base: it takes the destination this base gives a row bound + // to it (ruling record 7254350842), and the pair door is asked. + const ownOverride = address.kind === 'base' && first!.overrideOf === address.packageId && first!.moved === undefined; + // A row bound to a package that ships no form of the name moves + // into that package's pair as the pair's own `form` item, declaring + // no `overrides` (maintainer ruling 7250977204, ADR-0146's precedent). + // A pair's override read at such a base already stands in its pair. + const firstBinding = bindings.get(first!.place); + const unshipped = firstBinding?.kind === 'at' ? firstBinding.unshipped : undefined; + const standsIn = unshipped !== undefined && first!.overrideOf !== undefined ? first!.place.packageId : undefined; + const destination: DestinationReading = unshipped !== undefined + ? pairFormDestination(address, unshipped.base, input, standsIn) + : ownOverride + ? keptDestination(address, first!) + : destinationOf(address, input); + const atDestination = first!.place.type === 'form' && ( + standsIn !== undefined + || (address.kind === 'base' + ? first!.overrideOf === address.packageId + : address.kind === 'package' + ? first!.place.packageId === address.packageId + : first!.place.packageId === undefined)); + + if (!atDestination) { + const internal = isInternal(first!, name, address, input, shipped); + if (INTERNAL_AHEAD_OF_LINKED_ROW.applies(internal, behind)) { + push({ ...base, outcome: INTERNAL_AHEAD_OF_LINKED_ROW.outcome, reason: INTERNAL_AHEAD_OF_LINKED_ROW.reason }); + continue; + } + // A deletion is per row: a row read at several addresses (a + // package-less row) is removed only when it is internal at + // every one of them; over a linked base anywhere it moves at + // each address instead (D7-b, D7-e). + const removable = internal + && (readAt.get(first!.place) ?? [address]).every((a) => isInternal(first!, name, a, input, shipped)); + if (removable) { + const object = typeof body.object === 'string' && body.object !== '' ? body.object : undefined; + // A row behind that is the served row at another address + // is not removed with this form: it gets what that address + // gives it, and a row that stands over a linked base there + // is never listed for removal (D7-e). + const elsewhere = formRows.filter((row) => servedAtAnother(row.place, address)); + push({ + ...base, + behind: formRows.filter((row) => !elsewhere.includes(row)).map((row) => rowRef(row, name)), + outcome: 'remove', + ...(object !== undefined ? { object } : {}), + objectHasFieldGroups: object !== undefined && input.objectHasFieldGroups(object), + ...(elsewhere.length > 0 ? { servedElsewhere: elsewhere.map((row) => rowRef(row, name)) } : {}), + }); + continue; + } + if (destination.kind === 'hold') { + const action = storedFormHoldAction(destination.cause, { + base: (address as { packageId: string }).packageId, + ...(destination.app !== undefined ? { app: destination.app } : {}), + ...(destination.earlierPair === true ? { earlierPair: true } : {}), + }); + push({ ...base, outcome: 'hold', cause: destination.cause, refusal: destination.refusal, action }); + holds.push({ row: served, base: (address as { packageId: string }).packageId, cause: destination.cause, refusal: destination.refusal, action }); + continue; + } + } + if (destination.kind === 'hold') { + // A stored `form` override already at its base's pair: kept, whatever the ensure door says now. + 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 kept = keptRowsOf(plansOfName); + holdContestedPairSlots(name, plansOfName, holds); + holdRowsServedApart(name, plansOfName, holds, input.pairFix, input.installed); + holdChangesToKeptRows(name, plansOfName, kept, holds, input.pairFix, input.installed); + + // A held row is folded into no other row (ADR-0159 D7): a row that holds + // where it is served and stands behind the row a plan keeps or moves is + // listed apart there, and the fold is read without it. + const heldRows = new Set(plansOfName.filter(({ plan }) => plan.outcome === 'hold').map(({ rows }) => rows[0]!.place)); + plansOfName.forEach(({ plan, rows }, index) => { + if (plan.outcome !== 'keep' && plan.outcome !== 'move') return; + const [first, ...rest] = rows; + const apart = rest.filter((row) => row.holding.kind === 'form' && heldRows.has(row.place)); + if (apart.length === 0) return; + const kept = rest.filter((row) => !apart.includes(row)); + const behind = kept.filter((row) => row.holding.kind === 'form').map((row) => rowRef(row, name)); + const { carries: _carries, newlyClosed: _newlyClosed, ...unfolded } = plan; + plansOfName[index] = { + plan: { ...unfolded, behind, heldApart: apart.map((row) => rowRef(row, name)), ...foldOf(first!, kept, plan.served, behind, plan.address, folded) }, + rows, + }; + }); + + // Each plan names the rows another address reads too, and what it does. + for (const { plan, rows } of plansOfName) { + const elsewhere: StoredFormElsewhere[] = []; + for (const row of rows) { + if (row.holding.kind !== 'form') continue; + for (const other of plansOfName) { + if (other.plan === plan) continue; + const index = other.rows.findIndex((r) => r.place === row.place); + if (index < 0) continue; + elsewhere.push({ row: rowRef(row, name), address: other.plan.address, outcome: other.plan.outcome, served: index === 0 }); + } + } + const withElsewhere = elsewhere.length > 0 ? { ...plan, alsoReadAt: elsewhere } : plan; + const left = withElsewhere.outcome === 'move' + ? (input.drafts ?? []).filter((d) => d.name === withElsewhere.served.name && d.packageId === withElsewhere.served.packageId) + : []; + forms.push(left.length > 0 ? { ...withElsewhere, draftsLeftBehind: left } as StoredFormAddressPlan : withElsewhere); + } + } + + const unreadable: StoredFormHold[] = input.unreadable.map((u) => ({ + row: { + type: u.type, + name: u.name, + ...(u.packageId !== undefined ? { packageId: u.packageId } : {}), + form: u.name, + grain: 'item', + holds: 'unreadable', + }, + cause: 'unreadable', + refusal: `The stored view '${u.name}' carries form content that cannot be read: ${u.reason}.` + + (u.links.length > 0 + ? ` On this release both public doors answer for it as they do today; on the next major its links close: ${u.links.map((l) => `/forms/${l}`).join(', ')}.` + : ''), + action: storedFormHoldAction('unreadable'), + })); + + const counts: Record = { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 }; + for (const plan of forms) counts[plan.outcome] += 1; + const allHolds = [...holds, ...unreadable]; + return { + forms, + unreadable, + drafts: input.drafts ?? [], + sharedSlugs: sharedSlugsOf(input.places), + precheck: { canSwitch: allHolds.length === 0, holds: allHolds, counts }, + }; +} + +type DestinationReading = StoredFormDestination | { kind: 'hold'; cause: PairHoldCause; refusal: string; app?: string; earlierPair?: boolean }; + +function holdOf(fix: Extract): DestinationReading { + return { + kind: 'hold', + cause: fix.cause, + refusal: fix.refusal, + ...(fix.app !== undefined ? { app: fix.app } : {}), + ...(fix.earlierPair === true ? { earlierPair: true } : {}), + }; +} + +function destinationOf(address: StoredFormAddress, input: Pick): DestinationReading { + if (address.kind === 'package') return { kind: 'package_form', packageId: address.packageId }; + if (address.kind === 'environment') return { kind: 'environment_form' }; + const fix = input.pairFix(address.packageId); + if (!fix.ok) return holdOf(fix); + return { kind: 'pair_override', base: address.packageId, pair: fix.pair, basedOn: fix.basedOn }; +} + +/** + * [maintainer ruling 7250977204] The pair's own `form` item, for a row bound + * to a package that ships no form of the name: a row bound to the read-only + * package needs that package's pair ensured (the ensure-door hold applies + * when it cannot be); a pair's override of a base that ships none already + * stands in the pair, at the pair's own address or (`ownPair`) read at its + * base's, and the door is not asked. + */ +function pairFormDestination( + address: StoredFormAddress, + base: string, + input: Pick, + ownPair?: string, +): DestinationReading { + 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); + return { kind: 'pair_form', base, pair: fix.pair }; +} + +/** 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; + const basedOn = isRecord(overrides) && typeof overrides.basedOn === 'string' ? overrides.basedOn : ''; + return { kind: 'pair_override', base: (address as { packageId: string }).packageId, pair: served.place.packageId ?? '', basedOn }; +} + +/** + * [ADR-0159 D7, all three parts] Whether the served row is an internal record + * form: in a record-form slot, declaring no `sharing.publicLink` (D7-a: a link + * switched off is still a link), opened by no `type: 'form'` action, and not + * standing over a base form that declares a link (D7-b: classed by its base). + */ +function isInternal( + served: OrderedFormRow, + name: string, + address: StoredFormAddress, + input: Pick, + shipped: (name: string) => readonly ShippedForm[], +): boolean { + if (served.holding.kind !== 'form') return false; + if (served.place.type === 'form') return false; // a `form` row is no old shape: never removed here + if (linkOf(served.holding.item) !== undefined) return false; + if (input.actionTargets.has(name)) return false; + if (address.kind !== 'environment') { + const baseForm = shipped(name).find((s) => s.packageId === address.packageId)?.form; + if (linkOf(baseForm) !== undefined) return false; + } + // A container's member is in a slot by the key it expands from; read off the row's own body. + return recordSlotNames(served.place.entry.data).has(name); +} + +/** + * [ADR-0159 D7-d] The fold: the withdrawal the destination carries, and + * whether it closes a form open today. The rows a layer reads today are the + * served row and, at a read-only base, the first of the row bound to the base + * and the package-less row (the base's per-package layer); a row behind them + * is read by none. A row served here although it is stored against another + * package ({@link servedAtAnotherAddress}) is read today in that package's + * own layer, whatever stands ahead of it, and a withdrawal closes its name + * in every package: carried from such a row, it closes nothing newly. A row + * `folded` here from the address it is bound to + * ({@link servedAheadFromElsewhere}) is read today only where its own + * package's layer reads it, the value it maps to. + */ +function foldOf( + first: OrderedFormRow, + rest: readonly OrderedFormRow[], + served: StoredFormRowRef, + behind: readonly StoredFormRowRef[], + address: StoredFormAddress, + folded: ReadonlyMap = new Map(), +): { carries?: StoredFormCarriedWithdrawal; newlyClosed: boolean } { + if (served.link === undefined || served.withdraws !== undefined) return { newlyClosed: false }; + const index = behind.findIndex((row) => row.withdraws !== undefined); + if (index < 0) return { newlyClosed: false }; + const from = behind[index]!; + // The base's per-package layer reads the first of the row bound to the + // base and the package-less row; when the served row is the pair's + // override, that row stands behind it, and is read today. `rest` is every + // row behind (a list included: the layer reads it, and it withdraws + // nothing); `behind` is the form rows among them, in the same order. + 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; + const closesToday = behind.some((row, i) => row.withdraws !== undefined + && (forms[i]?.place === layer || forms[i]?.moved !== undefined || folded.get(forms[i]!.place) === true)); + // 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 }; +} + +function sharedSlugsOf(places: readonly StoredFormPlace[]): StoredFormCensus['sharedSlugs'] { + const bySlug = new Map>(); + for (const place of places) { + for (const [name, holding] of place.holds) { + if (holding.kind !== 'form') continue; + const slug = linkOf(holding.item); + if (slug === undefined) continue; + const set = bySlug.get(slug) ?? new Set(); + set.add(name); + bySlug.set(slug, set); + } + } + return [...bySlug].filter(([, set]) => set.size > 1).map(([slug, set]) => ({ slug, forms: [...set].sort() })) + .sort((a, b) => a.slug.localeCompare(b.slug)); +} + +// ── The host reading ──────────────────────────────────────────────────────── + +/** The host members the census reads. */ +export type StoredFormCensusHost = FormReadHost & Pick; + +/** + * [ADR-0159 D7-c] Whether `base`'s pair can be ensured for the move, read + * from the ensure door's own judgement (`customizationPairEnsureRefusal`, its + * kernel verdict included) and the base's recorded version (`basedOn`); a + * refusal is classed by who can remove its cause, its text repeated. + */ +export function storedFormPairFix(engine: ProtocolHost['engine'], base: string): PairFixReading { + const installed = installedManifestsOfEngine(engine); + const pairId = pairOf(base, installed); + if (!pairId.ok) { + 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).`, + }; + } + const pair = pairId.value; + const registry = (engine as { registry?: PairRegistry } | undefined)?.registry; + if (!registry || typeof registry.getPackage !== 'function') { + return { ok: false, cause: 'administrator', refusal: `The registry cannot answer for '${base}' (no package lookup).` }; + } + const refused = customizationPairEnsureRefusal(engine, registry, base, pair); + const appId = customizationBasePackageId(pair) ?? base; + if (refused !== undefined) { + if (kernelPackageScope(engine, base) !== undefined) return { ok: false, cause: 'kernel', refusal: refused.message }; + const app = appId === base ? registry.getPackage(base) : registry.getPackage(appId); + // The door's order, classed by who removes each cause (ADR-0159 D7-c): + // the App not installed, and a package under the pair's id, are the + // administrator's; no valid namespace and a non-SemVer version are the + // App author's; the namespace held by another package, or by a + // per-package pair of an earlier version, is the administrator's (the + // latter with no command on this release to clear it). + const cause: PairHoldCause = !app + ? 'administrator' + : !customizationNamespace(app.manifest?.namespace).ok + ? 'app_author' + : registry.getPackage(pair) + ? 'administrator' + : !customizationDependencyRange(app.manifest?.version).ok + ? 'app_author' + : 'administrator'; + // The door's own words for the per-package pair an earlier version + // created (ADR-0146 D3, merge question 12): no command on this release + // re-identifies it (maintainer ruling 7250982640). + const earlierPair = (refused as { statusCode?: number }).statusCode === 409 && refused.message.includes('re-identified as the App\'s pair'); + return { ok: false, cause, refusal: refused.message, app: appId, ...(earlierPair ? { earlierPair: true } : {}) }; + } + 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: true, pair, basedOn }; +} + +/** Every `type: 'form'` action target a value declares, at any depth: a literal target only. */ +function collectFormActionTargets(value: unknown, out: Set, depth = 0): void { + if (depth > 16 || value === null || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const v of value) collectFormActionTargets(v, out, depth + 1); + return; + } + const record = value as Record; + if (record.type === 'form' && typeof record.target === 'string' && record.target !== '' && !record.target.includes('{')) { + out.add(record.target); + } + for (const v of Object.values(record)) collectFormActionTargets(v, out, depth + 1); +} + +/** + * [ADR-0159 D7] The census over a live protocol: reads the stored rows, the + * registry and the ensure door's judgement, and hands them to + * {@link planStoredForms}. Writes nothing. + */ +export async function listStoredForms(host: StoredFormCensusHost): Promise { + const places = await storedFormPlaces(host); + const installed = installedManifestsOfEngine(host.engine); + const registry = (host.engine as unknown as { registry?: { listItems?: (type: string) => unknown[] } }).registry; + const list = (type: string): unknown[] => { + try { + return typeof registry?.listItems === 'function' ? registry.listItems(type) ?? [] : []; + } catch { + return []; + } + }; + const readStored = async (type: string, state: 'active' | 'draft' = 'active'): Promise> => { + try { + const rows = state === 'active' + ? await host.readActiveOverlayRows({ type }) + : await host.findEnvironmentRows('sys_metadata', { where: { type, state: 'draft' }, context: { isSystem: true } }); + return rows.length === 0 ? [] : host.storedOverlayEntries({ type }, rows); + } catch (error) { + host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); + return []; + } + }; + + const actionTargets = new Set(); + for (const type of ['action', 'object', 'page']) { + collectFormActionTargets(list(type), actionTargets); + collectFormActionTargets((await readStored(type)).map((e) => e.data), actionTargets); + } + + const objects = new Map(); + for (const object of list('object')) { + const name = isRecord(object) ? object.name : undefined; + if (typeof name === 'string') objects.set(name, object); + } + + const shippedForms = (name: string): ShippedForm[] => { + const byPackage = new Map | undefined>(); + const put = (pkg: unknown, form: Record | undefined): void => { + if (typeof pkg !== 'string' || pkg === '' || byPackage.has(pkg)) return; + byPackage.set(pkg, form); + }; + for (const a of host.shippedArtifactsOf('form', name)) put((a as { _packageId?: unknown } | null)?._packageId, isRecord(a) ? a : undefined); + for (const a of host.shippedArtifactsOf('view', name)) { + const form = projectViewForms(a).forms.find((f) => f.name === name); + if (form !== undefined) put((a as { _packageId?: unknown } | null)?._packageId, form); + } + return [...byPackage].map(([packageId, form]) => ({ packageId, writable: host.isWritablePackage(packageId), form })); + }; + + const unreadable: Array = []; + for (const entry of await readStored('view')) { + const projection = projectViewForms(entry.data); + if (projection.unreadable === undefined) continue; + unreadable.push({ + type: entry.type, + name: entry.name, + ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}), + reason: projection.unreadable.reason, + links: projection.unreadable.links, + }); + } + + // Old-shape drafts only: a `form` draft is in the new shape, and publishes after the upgrade (ruling 7250982640). + const drafts: StoredFormDraft[] = []; + for (const type of ['view', 'views']) { + for (const entry of await readStored(type, 'draft')) { + const projection = projectViewForms(entry.data); + if (projection.forms.length === 0 && projection.unreadable === undefined) continue; + drafts.push({ type: entry.type, name: entry.name, ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}) }); + } + } + + return planStoredForms({ + places, + installed, + shippedForms, + isWritable: (packageId) => host.isWritablePackage(packageId), + actionTargets, + pairFix: (base) => storedFormPairFix(host.engine, base), + 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; + }, + unreadable, + drafts, + shipsView: (name) => { + const out = new Set(); + for (const a of host.shippedArtifactsOf('view', name)) { + const pkg = (a as { _packageId?: unknown } | null)?._packageId; + if (typeof pkg === 'string' && pkg !== '') out.add(pkg); + } + return [...out]; + }, + }); +} + +/** + * [ADR-0159 D7, card ⑤a] The census `os migrate stored-forms` prints, over a + * live protocol instance: {@link listStoredForms} through the instance's + * host. A function beside the facade rather than a facade method, so the + * facade file does not grow (`check:facade-delegation-only`). Writes nothing. + * + * @throws the `sys_metadata` read failure, classified by the protocol's + * `rethrowUnlessMetadataStoreUnprovisioned`; an unprovisioned table + * answers an empty census. + */ +export function listStoredFormsOf(protocol: ObjectStackProtocolImplementation): Promise { + return listStoredForms(protocolHost(protocol)); +} diff --git a/packages/objectql/src/protocol-stored-form-migration.test.ts b/packages/objectql/src/protocol-stored-form-migration.test.ts new file mode 100644 index 00000000000..d019a72bcc7 --- /dev/null +++ b/packages/objectql/src/protocol-stored-form-migration.test.ts @@ -0,0 +1,579 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7, card ⑤a] The stored-form ceremony's census over the real + * protocol and the real `ObjectQL` engine (the harness of + * `protocol-packageless-overlay-migration.test.ts`): `listStoredForms`, the + * read-only half `os migrate stored-forms` prints (`listStoredFormsOf`). + * + * - a package-less old-shape row over a base's linked form is listed as + * moving into the base's pair as a declared override, `basedOn` the base's + * version, and the census writes nothing (no row, no pair); + * - a body the projection cannot read holds the upgrade; + * - a base whose App declares no namespace holds it, the cause the App + * author's, the ensure door's refusal repeated; + * - an internal record form over an unlinked base is listed for removal; + * - beside a row bound to a base that ships no form of the name, the pair's + * declared override is the only body the read serves, and the census + * plans one move, the bound row behind it; + * - a row the read serves at another address than the package it is bound + * to is planned where it is served, as that base's declared override: at + * each address when two serve it, and with a withdrawal it holds read + * today in its own package's layer (ruling record 7254350842). + * + * The planner's every outcome on its own fixture is pinned in + * `packages/metadata-protocol/src/protocol-stored-form-migration.test.ts`. + * + * Test-path resolution: the protocol is `@objectstack/metadata-protocol`'s + * `dist/`, so a change there is read here after that package is rebuilt. + */ +// Pays the lint root's first load at collection, never inside a clocked case. +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 { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; +import { ObjectQL } from './engine.js'; + +const BASE = 'com.example.forms'; +const PAIR = 'com.example.forms.custom'; +const NO_NAMESPACE = 'com.example.nonamespace'; +const OBJECT = 'forms_inquiry'; +const NAME = `${OBJECT}.contact`; +const SLUG = 'contact-37111'; +const LONE_OBJECT = 'lone_inquiry'; + +const sysMetadataObject: ServiceObject = { + name: 'sys_metadata', + label: 'System Metadata', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const }, + type: { name: 'type', label: 'Type', type: 'text' as const, required: true }, + name: { name: 'name', label: 'Name', type: 'text' as const, required: true }, + organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const }, + package_id: { name: 'package_id', label: 'Package', type: 'text' as const }, + bundle_member: { name: 'bundle_member', label: 'Bundle Member', type: 'text' as const, maxLength: 100 }, + metadata: { name: 'metadata', label: 'Body', type: 'textarea' as const }, + draft_changes: { name: 'draft_changes', label: 'Draft Changes', type: 'textarea' as const }, + checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 }, + state: { name: 'state', label: 'State', type: 'text' as const }, + version: { name: 'version', label: 'Version', type: 'number' as const }, + created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const }, + updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const }, + }, +}; + +function makeMemoryDriver() { + const stores = new Map>>(); + const storeFor = (obj: string) => { + let s = stores.get(obj); + if (!s) { s = new Map(); stores.set(obj, s); } + return s; + }; + let nextId = 0; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { + if (!v.every((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k === '$or' && Array.isArray(v)) { + if (!v.some((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k.startsWith('$')) continue; + const rowVal = row[k]; + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { + if (!(v as any).$in.includes(rowVal === undefined ? null : rowVal)) return false; + continue; + } + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + const a = rowVal === undefined ? null : rowVal; + const b = expected === undefined ? null : expected; + if (a !== b) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + nextId += 1; + const id = (data.id as string) ?? `r_${nextId}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const cur = s.get(id); + if (!cur) throw new Error(`not found: ${object}/${id}`); + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return updated; + }, + async upsert(object: string, data: Record) { + const id = data.id as string | undefined; + if (id && storeFor(object).has(id)) return this.update(object, id, data); + return this.create(object, data); + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, stores }; +} + +const sharing = (enabled: boolean) => ({ sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true } }); +const formBody = (object: string, extra: Record = {}) => ({ + type: 'simple', sections: [{ fields: ['name'] }], data: { provider: 'object', object }, ...extra, +}); +const objectOf = (name: string) => ({ + name, label: name, sharingModel: 'private', + fields: { name: { name: 'name', label: 'Name', type: 'text' } }, +}); + +async function boot() { + const engine = new ObjectQL(); + const { driver, stores } = makeMemoryDriver(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(sysMetadataObject, 'test-package'); + for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + // The base ships a linked form `NAME` (formViews.contact) and an unlinked default record form. + engine.registerApp({ + id: BASE, name: 'forms', version: '1.2.0', namespace: 'forms', + objects: [objectOf(OBJECT)], + views: [{ object: OBJECT, form: formBody(OBJECT), formViews: { contact: formBody(OBJECT, sharing(true)) } }], + }); + // An App with no namespace: its pair cannot be ensured, and only its author can fix that. + engine.registerApp({ + id: NO_NAMESPACE, name: 'lone', version: '1.0.0', + objects: [objectOf(LONE_OBJECT)], + views: [{ object: LONE_OBJECT, formViews: { contact: formBody(LONE_OBJECT, sharing(true)) } }], + } as any); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); + const snapshot = () => JSON.stringify([...(stores.get('sys_metadata')?.values() ?? [])]); + return { engine, protocol, snapshot }; +} + +/** + * An App that ships no form, and its module that ships `SUITE_NAME`, linked and open, in the old shape; + * `second`, a second module that ships it too; `moduleAs: 'form'`, the module ships it as a `form` item + * instead; `appShipsForm`, the App ships it as a `form` item as well, carrying `appForm` beside its body; + * `appOwnsObject`, the App owns the object in the module's place; `moduleForm`, what the module's old-shape + * form carries beside its sections. + */ +const SUITE = 'com.example.suite'; +const MODULE = 'com.example.suite.service'; +const SECOND = 'com.example.suite.sales'; +const SUITE_PAIR = 'com.example.suite.custom'; +const SUITE_OBJECT = 'suite_ticket'; +const SUITE_NAME = `${SUITE_OBJECT}.contact`; + +async function bootSuite({ second = false, moduleAs = 'view', appShipsForm = false, appOwnsObject = false, moduleForm = sharing(true), appForm = sharing(true) }: { + second?: boolean; moduleAs?: 'view' | 'form'; appShipsForm?: boolean; appOwnsObject?: boolean; moduleForm?: Record; appForm?: Record; +} = {}) { + const engine = new ObjectQL(); + const { driver, stores } = makeMemoryDriver(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(sysMetadataObject, 'test-package'); + for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + const formItem = { name: SUITE_NAME, object: SUITE_OBJECT, label: 'Shipped form', type: 'simple', sections: [{ fields: ['name'] }], ...sharing(true) }; + engine.registerApp({ + id: SUITE, name: 'suite', version: '3.0.0', type: 'app', namespace: 'suite', + ...(appOwnsObject ? { objects: [objectOf(SUITE_OBJECT)] } : {}), + ...(appShipsForm ? { forms: [{ ...formItem, sharing: undefined, ...appForm }] } : {}), + } as any); + engine.registerApp({ + id: MODULE, name: 'suite-service', version: '3.1.0', type: 'module', namespace: 'suite', + dependencies: { [SUITE]: '^3.0.0' }, + ...(appOwnsObject ? {} : { objects: [objectOf(SUITE_OBJECT)] }), + ...(moduleAs === 'form' + ? { forms: [formItem] } + : { views: [{ object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, moduleForm) } }] }), + } as any); + if (second) { + engine.registerApp({ + id: SECOND, name: 'suite-sales', version: '3.2.0', type: 'module', namespace: 'suite', + dependencies: { [SUITE]: '^3.0.0' }, + views: [{ object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, sharing(true)) } }], + } as any); + } + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); + const snapshot = () => JSON.stringify([...(stores.get('sys_metadata')?.values() ?? [])]); + return { engine, protocol, snapshot }; +} + +const storeRow = (engine: ObjectQL, name: string, body: Record, packageId: string | null = null, type: 'view' | 'form' = 'view') => + engine.insert('sys_metadata', { + type, name, organization_id: null, package_id: packageId, + metadata: JSON.stringify(body), state: 'active', version: 1, + }, { context: { isSystem: true } }); + +const viewItem = (name: string, object: string, extra: Record = {}) => ({ + name, object, viewKind: 'form', label: 'Contact us', config: formBody(object, extra), +}); + +const census = (protocol: ObjectStackProtocolImplementation): Promise => listStoredFormsOf(protocol); + +describe('[ADR-0159 D7] listStoredForms over the real protocol', () => { + it('lists a package-less old-shape row over the base\'s linked form as moving into the pair, and writes nothing', async () => { + const { engine, protocol, snapshot } = await boot(); + await storeRow(engine, NAME, viewItem(NAME, OBJECT, sharing(false))); + const before = snapshot(); + const result = await census(protocol); + const plan = result.forms.find((f: any) => f.form === NAME && f.address.kind === 'base' && f.address.packageId === BASE); + expect(plan).toMatchObject({ + outcome: 'move', + destination: { kind: 'pair_override', base: BASE, pair: PAIR, basedOn: '1.2.0' }, + served: { type: 'view', name: NAME, holds: 'form', link: SLUG, withdraws: SLUG }, + }); + expect(result.precheck.canSwitch).toBe(true); + expect(snapshot()).toBe(before); + expect((engine.registry as any).getPackage(PAIR)).toBeUndefined(); + }); + + it('a body the projection cannot read holds the upgrade, its links named', async () => { + const { engine, protocol } = await boot(); + await storeRow(engine, `${OBJECT}.broken`, { name: `${OBJECT}.broken`, viewKind: 'form', ...sharing(true) }); + const result = await census(protocol); + expect(result.precheck.canSwitch).toBe(false); + expect(result.unreadable).toEqual([expect.objectContaining({ + cause: 'unreadable', + row: expect.objectContaining({ name: `${OBJECT}.broken` }), + })]); + expect(result.unreadable[0].refusal).toContain(`/forms/${SLUG}`); + }); + + it('a base whose App declares no namespace holds the upgrade: the App author\'s cause, the ensure door\'s refusal repeated', async () => { + const { engine, protocol } = await boot(); + const lone = `${LONE_OBJECT}.contact`; + await storeRow(engine, lone, viewItem(lone, LONE_OBJECT, sharing(false))); + const result = await census(protocol); + const plan = result.forms.find((f: any) => f.form === lone); + expect(plan).toMatchObject({ outcome: 'hold', cause: 'app_author', address: { kind: 'base', packageId: NO_NAMESPACE } }); + expect(plan.refusal).toContain('com.example.nonamespace.custom'); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.holds).toEqual([expect.objectContaining({ base: NO_NAMESPACE, cause: 'app_author' })]); + }); + + it('an internal record form over the base\'s unlinked default form is listed for removal, and does not hold the upgrade', async () => { + const { engine, protocol } = await boot(); + // The base's container copied as stored (its own name, the object's), its default form edited. + await storeRow(engine, OBJECT, { name: OBJECT, object: OBJECT, form: formBody(OBJECT, { label: 'Edited' }), formViews: { contact: formBody(OBJECT, sharing(true)) } }); + const result = await census(protocol); + const plan = result.forms.find((f: any) => f.form === `${OBJECT}.form`); + expect(plan).toMatchObject({ outcome: 'remove', object: OBJECT, address: { kind: 'base', packageId: BASE } }); + expect(result.precheck.canSwitch).toBe(true); + }); + + it('beside a row bound to a base that ships no form of the name, the read serves the pair\'s override alone, and the census plans one move with the bound row behind it (D7-d, ruling 7250977204)', async () => { + const { engine, protocol, snapshot } = await boot(); + const name = `${OBJECT}.legacy`; // no package ships a form of this name + await storeRow(engine, name, { ...viewItem(name, OBJECT, sharing(true)), label: 'Bound to the base' }, BASE); + await storeRow(engine, name, { + ...viewItem(name, OBJECT, sharing(false)), label: 'Override in the pair', overrides: { package: BASE, basedOn: '1.2.0' }, + }, PAIR); + const before = snapshot(); + // The read today: the bound row seats the base's address, and the override is + // the body served there and at the pair's; the bound row's body is served nowhere. + const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items.filter((item: any) => item?.name === name); + expect(served.map((item: any) => [item._packageId, item.label]).sort()).toEqual([ + [BASE, 'Override in the pair'], + [PAIR, 'Override in the pair'], + ]); + // The plan: one, at the base's address. The override is the body kept, in the pair it stands in. + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === name)).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + destination: { kind: 'pair_form', base: BASE, pair: PAIR }, + served: expect.objectContaining({ type: 'view', packageId: PAIR, overrideOf: BASE }), + behind: [expect.objectContaining({ type: 'view', packageId: BASE })], + newlyClosed: false, + })]); + expect(result.precheck.canSwitch).toBe(true); + expect(snapshot()).toBe(before); + }); +}); + +describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another address than the package it is bound to, over the real protocol', () => { + /** The effective `form` items of the name: the package each is served under, and its label. */ + const servedForms = async (protocol: ObjectStackProtocolImplementation): Promise> => + ((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === SUITE_NAME) + .map((item: any) => [item._packageId, item.label] as [string, string]); + const switchedOff = { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }; + const declaring = (base: string) => ({ overrides: { package: base, basedOn: '3.0.0' } }); + const plansOf = async (protocol: ObjectStackProtocolImplementation): Promise => + (await census(protocol)).forms.filter((f: any) => f.form === SUITE_NAME); + + for (const shape of ['bound to the App', 'a pair\'s override declaring the App'] as const) { + it(`${shape}: the read serves it at the module, and the census moves it into that module's pair as its declared override, writing nothing`, async () => { + const { engine, protocol, snapshot } = await bootSuite(); + if (shape === 'bound to the App') await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + else await storeRow(engine, SUITE_NAME, { ...switchedOff, ...declaring(SUITE) }, SUITE_PAIR); + const before = snapshot(); + // The read today: the stored body is the one served at the module's address. + expect(await servedForms(protocol)).toEqual([[MODULE, 'Switched off']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === SUITE_NAME)).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: MODULE }, + outcome: 'move', + destination: { kind: 'pair_override', base: MODULE, pair: SUITE_PAIR, basedOn: '3.1.0' }, + })]); + expect(result.precheck.canSwitch).toBe(true); + expect(snapshot()).toBe(before); + }); + } + + it('served at two modules: the read serves the stored body at each, and the census holds the upgrade at each address, the row named once (ruling record 7265816895)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ second: true }); + // No link of its own: at each address the row stands over that module's linked form. + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + const before = snapshot(); + expect((await servedForms(protocol)).sort()).toEqual([[SECOND, 'No link'], [MODULE, 'No link']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === SUITE_NAME).map((f: any) => [f.address.packageId, f.outcome, f.cause]).sort()).toEqual([ + [SECOND, 'hold', 'app_author'], + [MODULE, 'hold', 'app_author'], + ]); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: SUITE }), cause: 'app_author' })]); + // Nothing written, and both addresses answer as they did. + expect(snapshot()).toBe(before); + expect((await servedForms(protocol)).sort()).toEqual([[SECOND, 'No link'], [MODULE, 'No link']]); + }); + + it('a withdrawal it holds behind the module\'s own open override is read today in its own package\'s layer: the census carries it and does not name the form newly closed', async () => { + const { engine, protocol } = await bootSuite(); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Open override', ...declaring(MODULE) }, SUITE_PAIR); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + // The read today: the override is the body served, and the per-package layer the doors + // judge a withdrawal against holds the bound row's switched-off body under the App. + expect(await servedForms(protocol)).toEqual([[MODULE, 'Open override']]); + const layer = ((await protocol.getMetaItemsPerPackage({ type: 'form' })) as any).items.filter((item: any) => item?.name === SUITE_NAME); + expect(layer.filter((item: any) => item._packageId === SUITE).map((item: any) => [item.label, item.sharing?.enabled])).toEqual([['Switched off', false]]); + expect(await plansOf(protocol)).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: MODULE }, + served: expect.objectContaining({ packageId: SUITE_PAIR, overrideOf: MODULE }), + behind: [expect.objectContaining({ packageId: SUITE, withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + 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 () => { + 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 }], + ]); + }); + + it('a stored `form` row the read serves at the package it is bound to is planned there', async () => { + const { engine, protocol } = await bootSuite(); + await storeRow(engine, SUITE_NAME, { name: SUITE_NAME, object: SUITE_OBJECT, label: 'Stored form', type: 'simple', sections: [{ fields: ['name'] }] }, SUITE, 'form'); + expect((await servedForms(protocol)).map(([pkg]) => pkg).sort()).toEqual([SUITE, MODULE]); + expect((await servedForms(protocol)).find(([pkg]) => pkg === SUITE)).toEqual([SUITE, 'Stored form']); + expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.destination?.kind])).toEqual([[SUITE, SUITE, 'pair_form']]); + }); + + it('served at its own package as well: the read serves the stored body at both, and the census holds the upgrade at each, the row named once (ruling record 7265816895)', async () => { + const { engine, protocol } = await bootSuite({ appShipsForm: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + expect((await servedForms(protocol)).sort()).toEqual([[SUITE, 'No link'], [MODULE, 'No link']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === SUITE_NAME).map((f: any) => [f.address.packageId, f.outcome, f.cause]).sort()).toEqual([ + [SUITE, 'hold', 'app_author'], + [MODULE, 'hold', 'app_author'], + ]); + 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 () => { + 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 }], + ]); + }); + + 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 () => { + for (const type of ['view', 'form'] as const) { + 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, switchedOff, SUITE); + const before = snapshot(); + // The read today: the row bound to the App is served at the module, and the pair's own row is + // read in the pair's own per-package layer. + expect(await servedForms(protocol)).toContainEqual([MODULE, 'Switched off']); + const perPackage = ((await protocol.getMetaItemsPerPackage({ type: 'form' })) as any).items + .filter((item: any) => item?.name === SUITE_NAME) + .map((item: any) => [item._packageId, item.label]); + expect(perPackage).toContainEqual([SUITE_PAIR, 'Pair own']); + const result = await census(protocol); + expect((await plansOf(protocol)).map((f: any) => [f.address.packageId, f.outcome, f.served.packageId, f.cause]).sort()).toEqual([ + [MODULE, 'hold', SUITE, 'app_author'], + [SUITE_PAIR, 'hold', SUITE_PAIR, 'app_author'], + ].sort()); + expect(result.precheck.canSwitch).toBe(false); + expect(snapshot()).toBe(before); + } + }); + + it('served at two modules, left in place at one (an internal form ahead of a linked row) and moved at the other: the census holds the upgrade at both, the row named once (ruling record 7265816895)', 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); + const before = snapshot(); + // The read today: the override's body at both modules. + expect((await servedForms(protocol)).sort()).toEqual([[SECOND, 'Internal override'], [MODULE, 'Internal override']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === SUITE_NAME).map((f: any) => [f.address.packageId, f.outcome, f.served.packageId]).sort()).toEqual([ + [SECOND, 'hold', SUITE_PAIR], + [MODULE, 'hold', SUITE_PAIR], + ]); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ packageId: SUITE_PAIR }), cause: 'app_author' })]); + expect(snapshot()).toBe(before); + }); + + it('served at the App and at the module, removed at one and left in place at the other (an internal form ahead of a linked row): the census changes it at neither and holds the upgrade at both (ruling record 7265816895)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true, appForm: {}, appOwnsObject: true, moduleForm: {} }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal', isDefault: true }, SUITE); + await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, { label: 'Member', ...sharing(true) }) } }, SUITE); + const before = snapshot(); + // The read today: the internal row's body at the App and at the module. + expect((await servedForms(protocol)).sort()).toEqual([[SUITE, 'Internal'], [MODULE, 'Internal']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === SUITE_NAME).map((f: any) => [f.address.packageId, f.outcome, f.served.packageId]).sort()).toEqual([ + [SUITE, 'hold', SUITE], + [MODULE, 'hold', SUITE], + ]); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.counts.remove).toBe(0); + expect(snapshot()).toBe(before); + }); + + it('a package-less row served at addresses of two Apps, moved at one App\'s base and left in place at the other\'s (an internal form ahead of a linked row): the census holds the upgrade at both, the row named once (ruling record 7265816895)', async () => { + const { engine, protocol, snapshot } = await boot(); + // A second App that ships no form of the name, and its module that ships it with no link. + engine.registerApp({ id: 'com.example.other', name: 'other', version: '2.0.0', type: 'app', namespace: 'other' } as any); + engine.registerApp({ + id: 'com.example.other.desk', name: 'other-desk', version: '2.1.0', type: 'module', namespace: 'other', + dependencies: { 'com.example.other': '^2.0.0' }, + views: [{ object: OBJECT, formViews: { contact: formBody(OBJECT) } }], + } as any); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT), label: 'Internal', isDefault: true }); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT, sharing(true)), label: 'Linked' }, 'com.example.other'); + const before = snapshot(); + // The read today: the package-less row's body at both Apps' addresses. + const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === NAME) + .map((item: any) => [item._packageId, item.label]); + expect(served.sort()).toEqual([[BASE, 'Internal'], ['com.example.other.desk', 'Internal']]); + const result = await census(protocol); + expect(result.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address.packageId, f.outcome, f.served.packageId]).sort()).toEqual([ + [BASE, 'hold', undefined], + ['com.example.other.desk', 'hold', undefined], + ]); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.counts.move).toBe(0); + expect(result.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ name: NAME }), cause: 'app_author' })]); + // The action names both Apps, and does not read as if there were one. + expect(result.precheck.holds[0].action).toContain(`the Apps '${BASE}' and 'com.example.other'`); + expect(snapshot()).toBe(before); + }); + + it('the linked row behind an internal form left in place stays there too (ruling record 7249158572): where the App\'s own address serves it and would move it, the census holds the upgrade at both', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true, appOwnsObject: true, moduleForm: {} }); + 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 before = snapshot(); + // The read today: the internal row at the module, the linked row at the App. + expect((await servedForms(protocol)).sort()).toEqual([[SUITE, 'Linked'], [MODULE, 'Internal']].sort()); + const result = await census(protocol); + expect((await plansOf(protocol)).map((f: any) => [f.address.packageId, f.outcome, f.served.packageId]).sort()).toEqual([ + [MODULE, 'hold', undefined], + [SUITE, 'hold', SUITE], + ].sort()); + expect(result.precheck.canSwitch).toBe(false); + expect(result.precheck.counts.move).toBe(0); + expect(snapshot()).toBe(before); + }); + + /** The stored container whose member is `SUITE_NAME`, bound to the App, and the row ahead of it at the App's address. */ + const memberBehind = async (engine: ObjectQL, shape: 'bound to the App' | 'a pair\'s override declaring the App', member: boolean, ahead: boolean) => { + await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, { label: 'Member', ...sharing(member) }) } }, SUITE); + const row = { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(ahead)), label: 'Ahead' }; + if (shape === 'bound to the App') await storeRow(engine, SUITE_NAME, row, SUITE); + else await storeRow(engine, SUITE_NAME, { ...row, ...declaring(SUITE) }, SUITE_PAIR); + }; + /** The per-package `form` layer of the name: the package each item is listed under, and its label. */ + const layerOf = async (protocol: ObjectStackProtocolImplementation): Promise> => + ((await protocol.getMetaItemsPerPackage({ type: 'form' })) as any).items + .filter((item: any) => item?.name === SUITE_NAME && item._packageId !== MODULE) + .map((item: any) => [item._packageId, item.label] as [string, string]); + + for (const shape of ['bound to the App', 'a pair\'s override declaring the App'] as const) { + it(`a member of a stored container behind a row ${shape}: the read serves that row at the module and the member at no address, and the census folds the member behind it there (D7-d)`, async () => { + const { engine, protocol, snapshot } = await bootSuite({ appOwnsObject: true }); + await memberBehind(engine, shape, true, false); + const before = snapshot(); + // The read today: the row ahead at the module, and the member's body at no address. + expect(await servedForms(protocol)).toEqual([[MODULE, 'Ahead']]); + // The plan: one, at the module's address, the member behind the row served there. + expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.outcome, f.destination, f.served.grain, f.behind.map((r: any) => [r.packageId, r.grain])])).toEqual([ + [MODULE, 'move', { kind: 'pair_override', base: MODULE, pair: SUITE_PAIR, basedOn: '3.1.0' }, 'item', [[SUITE, 'expansion']]], + ]); + expect(snapshot()).toBe(before); + }); + } + + for (const [shape, layer, newlyClosed] of [ + ['bound to the App', [SUITE, 'Ahead'], true], + ['a pair\'s override declaring the App', [SUITE, 'Member'], false], + ] as const) { + it(`a withdrawal the member carries behind a row ${shape} closes the form newly only where the App's own layer does not read the member today`, async () => { + const { engine, protocol } = await bootSuite({ appOwnsObject: true }); + await memberBehind(engine, shape, false, true); + // The read today: the open row ahead at the module, and what the App's per-package layer holds. + expect(await servedForms(protocol)).toEqual([[MODULE, 'Ahead']]); + expect((await layerOf(protocol)).filter(([pkg]) => pkg === SUITE)).toEqual([layer]); + expect(await plansOf(protocol)).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: MODULE }, + behind: [expect.objectContaining({ packageId: SUITE, grain: 'expansion', withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + newlyClosed, + })]); + }); + } +}); 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 190e1d1e12d..d715f47a4b1 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -360,6 +360,8 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c const said = lines.filter((l) => l.includes(`${OBJECT}.broken`)); expect(said).toHaveLength(1); expect(said[0]).toContain(SLUG); + // [ADR-0159 D7-c, card ⑤a item 3] …and names the read-only ceremony that lists the rows holding the major. + expect(said[0]).toContain('`os migrate stored-forms`'); await closedOnBothDoors(b); }); diff --git a/scripts/docs-audit/handwritten-docs.json b/scripts/docs-audit/handwritten-docs.json index 23888cbdac2..987058eccbe 100644 --- a/scripts/docs-audit/handwritten-docs.json +++ b/scripts/docs-audit/handwritten-docs.json @@ -109,6 +109,7 @@ "content/docs/deployment/seed-tenancy-repair.mdx", "content/docs/deployment/self-hosting.mdx", "content/docs/deployment/single-project-mode.mdx", + "content/docs/deployment/stored-forms-upgrade.mdx", "content/docs/deployment/tenancy-modes.mdx", "content/docs/deployment/troubleshooting.mdx", "content/docs/deployment/validating-metadata.mdx",