diff --git a/.changeset/37111-stored-forms-census.md b/.changeset/37111-stored-forms-census.md new file mode 100644 index 00000000000..29e5f1f6b32 --- /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, or its form content cannot be read) 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. 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..4fe8324f4dc --- /dev/null +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -0,0 +1,78 @@ +--- +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. 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. 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, with what the upgrade does there. + +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. | +| 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..48baec9954a 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 four 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). 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). - **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,10 @@ 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). - **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 +41,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 +283,28 @@ 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 (this record's reading, open to correction). - 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. + - **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. - **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. - **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 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 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: 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. 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). 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. "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,13 +327,15 @@ 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 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: the destination, as the declared override the other moves take); - **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); - **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); @@ -526,8 +536,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 +571,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..699c74136e5 --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -0,0 +1,309 @@ +// 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', +}; + +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}` + + (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}` + + (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)} cannot move — ${plan.refusal} ${plan.action}`; + 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, or a + * body the projection cannot read, each with its cause and the action for it. + * The rows behind the served one fold into it; 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 57e8016f5bc..193abf3d4ac 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -347,6 +347,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..0aa84534525 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -56,7 +56,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 +240,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 +269,71 @@ 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 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 one address its binding names). */ -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 { + admits?: (place: StoredFormPlace) => boolean, +): OrderedFormRow[] { + const out: OrderedFormRow[] = []; + const seen = new Set(); for (const candidate of servedOverlayRowCandidates({ packageId, servedOverride: true, installed })) { // 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.packageId === undefined || (place.packageId ?? null) === candidate.packageId) && holdsServedOverlayCandidate(candidate, { type: place.entry.type, package_id: place.packageId ?? null, metadata: place.entry.data }, installed, undefined)); // 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); + out.push(candidate.overrideOf === undefined ? { holding: hit.holds.get(name)!, place: hit } - : { holding: hit.holds.get(name)!, place: hit, overrideOf: candidate.overrideOf }; + : { holding: hit.holds.get(name)!, place: hit, overrideOf: candidate.overrideOf }); } } - 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 +540,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 +569,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..c394dcb8b2e --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts @@ -0,0 +1,517 @@ +// 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 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] ?? [], + 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) } }, + ] }; + const census = planStoredForms(input([containerRow(undefined, null)], { ships })); + 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`] }]); + }); +}); 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..46cae65a115 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -0,0 +1,1092 @@ +// 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). 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. + * - `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 { 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[]; + }) + | (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; + /** The ensure door's own refusal, repeated. */ + readonly refusal: string; + /** The action for the cause. */ + readonly action: string; + }) + | (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. */ + 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 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 } }; + +/** + * 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-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; 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. */ +export function storedFormHoldAction(cause: StoredFormHoldCause, detail: { base?: string; pair?: string; app?: string; earlierPair?: boolean } = {}): 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': + 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.'; + } +} + +/** + * [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(); + for (const place of holding) bindings.set(place, bindingOf(place, name, input, shipsReadOnly)); + // 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) { + 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; + return binding.kind === 'at' && binding.packageId === at; + }); + rowsAt.set(addressKey(address), rows); + for (const row of rows) 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. + const ownOverride = address.kind === 'base' && first!.overrideOf === address.packageId; + // 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) }); + continue; + } + push({ ...base, outcome: atDestination ? 'keep' : 'move', destination, ...foldOf(first!, rest, served, behind, address) }); + } + + // 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. + */ +function foldOf( + first: OrderedFormRow, + rest: readonly OrderedFormRow[], + served: StoredFormRowRef, + behind: readonly StoredFormRowRef[], + address: StoredFormAddress, +): { 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)?.place; + const closesToday = behind.some((row, i) => row.withdraws !== undefined && forms[i]?.place === layer); + // 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, + }); +} + +/** + * [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..2ac8642268b --- /dev/null +++ b/packages/objectql/src/protocol-stored-form-migration.test.ts @@ -0,0 +1,264 @@ +// 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. + * + * 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 }; +} + +const storeRow = (engine: ObjectQL, name: string, body: Record, packageId: string | null = null) => + engine.insert('sys_metadata', { + type: 'view', 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); + }); +}); 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",