@openlup/platform 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +150 -138
  2. package/README.md +80 -3
  3. package/dist/composition/nodeHost.d.ts +1 -1
  4. package/dist/composition/nodeHost.js +3 -2
  5. package/dist/lifecycle/appUpgrade.d.ts +52 -0
  6. package/dist/lifecycle/appUpgrade.js +180 -0
  7. package/dist/lifecycle/index.d.ts +2 -0
  8. package/dist/lifecycle/index.js +2 -0
  9. package/dist/lifecycle/postgresInstallQualification.d.ts +51 -0
  10. package/dist/lifecycle/postgresInstallQualification.js +74 -0
  11. package/dist/migrations/postgresRunner.d.ts +9 -0
  12. package/dist/migrations/postgresRunner.js +17 -10
  13. package/dist/operations/adminAlertsSchemas.d.ts +153 -0
  14. package/dist/operations/adminAlertsSchemas.js +69 -0
  15. package/dist/operations/adminAlertsView.d.ts +73 -0
  16. package/dist/operations/adminAlertsView.js +184 -0
  17. package/dist/operations/alertPagingPolicy.d.ts +15 -0
  18. package/dist/operations/alertPagingPolicy.js +43 -0
  19. package/dist/operations/alertThrottlePolicy.d.ts +3 -0
  20. package/dist/operations/alertThrottlePolicy.js +18 -0
  21. package/dist/operations/clients.d.ts +17 -0
  22. package/dist/operations/clients.js +32 -0
  23. package/dist/operations/contracts/admin.d.ts +93 -0
  24. package/dist/operations/contracts/admin.js +1 -0
  25. package/dist/operations/contracts/adminAlertsContracts.d.ts +40 -0
  26. package/dist/operations/contracts/adminAlertsContracts.js +1 -0
  27. package/dist/operations/contracts/alertHumanContext.d.ts +7 -0
  28. package/dist/operations/contracts/alertHumanContext.js +1 -0
  29. package/dist/operations/contracts/index.d.ts +6 -0
  30. package/dist/operations/contracts/index.js +6 -0
  31. package/dist/operations/contracts/observabilityContracts.d.ts +41 -0
  32. package/dist/operations/contracts/observabilityContracts.js +1 -0
  33. package/dist/operations/contracts/observabilityPorts.d.ts +18 -0
  34. package/dist/operations/contracts/observabilityPorts.js +1 -0
  35. package/dist/operations/contracts/ports.d.ts +19 -0
  36. package/dist/operations/contracts/ports.js +1 -0
  37. package/dist/operations/errors.d.ts +6 -0
  38. package/dist/operations/errors.js +6 -0
  39. package/dist/operations/index.d.ts +9 -0
  40. package/dist/operations/index.js +9 -0
  41. package/dist/operations/schemas.d.ts +138 -0
  42. package/dist/operations/schemas.js +104 -0
  43. package/dist/operations/server/adminAlertsHandlers.d.ts +16 -0
  44. package/dist/operations/server/adminAlertsHandlers.js +35 -0
  45. package/dist/operations/server/adminPipelineHandlers.d.ts +12 -0
  46. package/dist/operations/server/adminPipelineHandlers.js +48 -0
  47. package/dist/operations/server/adminSettingsHandlers.d.ts +14 -0
  48. package/dist/operations/server/adminSettingsHandlers.js +82 -0
  49. package/dist/operations/server/controlPlaneHandler.d.ts +7 -0
  50. package/dist/operations/server/controlPlaneHandler.js +54 -0
  51. package/dist/operations/server/controlPlaneStore.d.ts +12 -0
  52. package/dist/operations/server/controlPlaneStore.js +138 -0
  53. package/dist/operations/server/controlPlaneWatchdog.d.ts +7 -0
  54. package/dist/operations/server/controlPlaneWatchdog.js +20 -0
  55. package/dist/operations/server/index.d.ts +12 -0
  56. package/dist/operations/server/index.js +12 -0
  57. package/dist/operations/server/migrations.d.ts +14 -0
  58. package/dist/operations/server/migrations.js +7 -0
  59. package/dist/operations/server/platformWatchdogDecision.d.ts +34 -0
  60. package/dist/operations/server/platformWatchdogDecision.js +71 -0
  61. package/dist/operations/server/platformWatchdogDeliveryPolicy.d.ts +10 -0
  62. package/dist/operations/server/platformWatchdogDeliveryPolicy.js +53 -0
  63. package/dist/operations/server/platformWatchdogQueue.d.ts +11 -0
  64. package/dist/operations/server/platformWatchdogQueue.js +94 -0
  65. package/dist/operations/server/platformWatchdogService.d.ts +47 -0
  66. package/dist/operations/server/platformWatchdogService.js +105 -0
  67. package/dist/operations/validation.d.ts +2 -0
  68. package/dist/operations/validation.js +3 -0
  69. package/dist/portability/filesystemObjects.d.ts +12 -0
  70. package/dist/portability/filesystemObjects.js +191 -0
  71. package/dist/portability/index.d.ts +5 -0
  72. package/dist/portability/index.js +4 -0
  73. package/dist/portability/objects.d.ts +63 -0
  74. package/dist/portability/objects.js +138 -0
  75. package/dist/portability/postgresRows.d.ts +64 -0
  76. package/dist/portability/postgresRows.js +182 -0
  77. package/dist/scheduler/advisoryLock.js +20 -2
  78. package/dist/scheduler/nodeScheduler.d.ts +2 -2
  79. package/dist/scheduler/nodeScheduler.js +35 -6
  80. package/package.json +27 -2
  81. package/release-gates.json +73 -7
  82. package/sql/20260814010000_platform_control_plane.sql +286 -0
  83. package/src/composition/nodeHost.ts +4 -3
  84. package/src/lifecycle/appUpgrade.ts +186 -0
  85. package/src/lifecycle/index.ts +19 -0
  86. package/src/lifecycle/postgresInstallQualification.ts +125 -0
  87. package/src/migrations/postgresRunner.ts +24 -9
  88. package/src/operations/adminAlertsSchemas.ts +78 -0
  89. package/src/operations/adminAlertsView.ts +238 -0
  90. package/src/operations/alertPagingPolicy.ts +50 -0
  91. package/src/operations/alertThrottlePolicy.ts +22 -0
  92. package/src/operations/clients.ts +44 -0
  93. package/src/operations/contracts/admin.ts +24 -0
  94. package/src/operations/contracts/adminAlertsContracts.ts +13 -0
  95. package/src/operations/contracts/alertHumanContext.ts +17 -0
  96. package/src/operations/contracts/index.ts +6 -0
  97. package/src/operations/contracts/observabilityContracts.ts +40 -0
  98. package/src/operations/contracts/observabilityPorts.ts +30 -0
  99. package/src/operations/contracts/ports.ts +22 -0
  100. package/src/operations/errors.ts +6 -0
  101. package/src/operations/index.ts +9 -0
  102. package/src/operations/schemas.ts +122 -0
  103. package/src/operations/server/adminAlertsHandlers.ts +61 -0
  104. package/src/operations/server/adminPipelineHandlers.ts +73 -0
  105. package/src/operations/server/adminSettingsHandlers.ts +114 -0
  106. package/src/operations/server/controlPlaneHandler.ts +56 -0
  107. package/src/operations/server/controlPlaneStore.ts +150 -0
  108. package/src/operations/server/controlPlaneWatchdog.ts +28 -0
  109. package/src/operations/server/index.ts +12 -0
  110. package/src/operations/server/migrations.ts +7 -0
  111. package/src/operations/server/platformWatchdogDecision.ts +93 -0
  112. package/src/operations/server/platformWatchdogDeliveryPolicy.ts +92 -0
  113. package/src/operations/server/platformWatchdogQueue.ts +96 -0
  114. package/src/operations/server/platformWatchdogService.ts +209 -0
  115. package/src/operations/validation.ts +3 -0
  116. package/src/portability/filesystemObjects.ts +138 -0
  117. package/src/portability/index.ts +12 -0
  118. package/src/portability/objects.ts +160 -0
  119. package/src/portability/postgresRows.ts +169 -0
  120. package/src/scheduler/advisoryLock.ts +20 -5
  121. package/src/scheduler/nodeScheduler.ts +28 -8
package/CHANGELOG.md CHANGED
@@ -10,6 +10,156 @@ in the source repository.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.30.0]
14
+
15
+ - Publishable on the npm `latest` dist-tag as `0.30.0`, from tag
16
+ `openlup-platform-v0.30.0`.
17
+
18
+ ### Qualified reference-source installation and retained imports
19
+
20
+ Migration: The reference-source PostgreSQL binding still selects the unchanged
21
+ 88-unit legacy plan by default. Fresh PostgreSQL 16 installations may explicitly
22
+ select `qualified-v2` and either `installer-managed` or `operator-provisioned`
23
+ roles. The actual migration session must use the declared SUPERUSER login that
24
+ owns the database; it may be the cluster bootstrap login or a separate declared
25
+ migration login. Runtime and optional restore logins must be distinct restricted
26
+ non-owner principals. Admission checks the actual role graph and capabilities;
27
+ selection alone establishes no installation or managed-host readiness.
28
+
29
+ Migration: Qualified bootstrap/runtime SQL and the reference selection binding
30
+ are source-tree inputs, not a complete installation catalogue shipped in the npm
31
+ package. The E-only 89-unit shape remains a separate historical expectation.
32
+ Selecting the retained-import tail requires the explicit restore binding and its
33
+ 90-unit catalogue. This fresh-generation route does not convert a legacy database.
34
+
35
+ Migration: The qualified retained-import tail gives the restore login EXECUTE
36
+ only on `client_import_retained_row` and
37
+ `subscription_cycle_import_retained_row`. These fixed routines insert an absent
38
+ row, replay an identical retained row and refuse a differing row with `23505`;
39
+ non-`origin` replication mode refuses with `55000`. Ordinary runtime writes keep
40
+ their existing lifecycle and delivery-alignment behavior. Restore parents,
41
+ history, frozen terms and identity mappings through their existing owners; the
42
+ two routines do not provide a full-store restore or stable upgrade service.
43
+
44
+ ### Added
45
+
46
+ Add the experimental Node-only `@openlup/platform/lifecycle` entry with explicit
47
+ application-file snapshot planning and apply. It preserves unmanaged files and
48
+ customized upstream-unchanged files, refuses divergent changed paths before
49
+ writes, and recognizes exact completed states for interruption/resume. It needs
50
+ no optional SDK and activates no route, timer, provider or installer.
51
+
52
+ The same entry exports `inspectLegacyPostgresInstallRoles` for one fixed,
53
+ read-only PostgreSQL role observation through an injected query handle. Its
54
+ `legacy-fresh-bootstrap-role-prerequisites` / `rolePrerequisitesMet` result
55
+ retains the immutable legacy bootstrap's superuser, shared-login, mode and
56
+ pre-existing-role refusals. It adds no DDL, role support or install-readiness claim.
57
+
58
+ The owner-authorized byte reserve after the direct directory-prefix and catalog
59
+ binding repair sets code-gzip 1,743,872 B, tarball 2,029,568 B and unpacked
60
+ 9,447,424 B caps. The supervisor computed each as 5% above the actual measured
61
+ 1,660,249 / 1,932,801 / 8,996,893 B, rounded up to KiB. These fixed limits
62
+ supersede the historical exact-minimum C+D allocation and grant no automatic
63
+ future increases or additional programme scope. Code/total file caps remain
64
+ 2574/2628; docs/browser caps, released baseline, versions and locks stay exact.
65
+ Actual approved-input remeasurement remains required because metadata edits can
66
+ change packed bytes; this budget decision establishes no final review or proof.
67
+
68
+ ### Migration
69
+
70
+ Select this entry explicitly from a Node application. Supply immutable UTF-8
71
+ predecessor/candidate snapshots, an absolute canonical root and separately
72
+ observed schema-range evidence. Hold an exclusive maintenance window. Apply
73
+ rechecks the current tree; a changed managed file with divergent local bytes
74
+ requires adopter reconciliation. Existing managed path components must match
75
+ their actual directory-entry spelling exactly; a filesystem case or normalization
76
+ alias does not authorize changing an unlisted entry. Per-file rename is not an
77
+ all-files transaction or a hostile-concurrency/power-loss guarantee. No SQL, dependency install,
78
+ version marker or deployment runs, and file completion does not establish their
79
+ compatibility or completion. Keep database expand/contract and dependency
80
+ provenance work at their existing owners.
81
+
82
+ - Add an optional trusted-source session admission observation to the experimental PostgreSQL migration runner. It runs once under the existing migration lock after exact-prefix validation and before status, dry-run or pending SQL; existing sources retain their current queries and execution.
83
+
84
+ ### Added
85
+
86
+ - Experimental operations contracts/browser/server subpaths expose existing
87
+ settings, pipeline-read, alert overview, watchdog delivery and control-plane
88
+ behavior through injected host ports. The public reference binds these owners.
89
+
90
+ ### Migration
91
+
92
+ - Existing reference imports remain compatible. Select the new operations entries
93
+ explicitly; imports register no route, job or provider. Identity membership and
94
+ tracking effects retain their existing owners.
95
+ - Native control-plane storage requires the complete canonical native prefix,
96
+ including the job ledger and `20260814010000_platform_control_plane.sql`.
97
+ The packaged SQL is a sparse unchanged projection. Supply current capability-local
98
+ operator authority, routine EXECUTE and underlying relation grants; no managed
99
+ parity or hosted-provider certification is established.
100
+
101
+ ### Packaging
102
+
103
+ - Code/total file limits are 2,574/2,628. After the 0.29.0 main integration, the
104
+ operations candidate measures 2,553 code files and 2,607 total files. The remaining 21
105
+ files are allocated to the seven already-authored B/C/D production TypeScript
106
+ files (4/2/1), each packaged as source, JavaScript and declarations. This is a
107
+ finite source-derived forecast, not an executed B–D package result or capacity
108
+ for later modules. Each stacked candidate must pass its actual pack checks;
109
+ additional files or byte-limit crossings need another bounded review.
110
+ - Integrated main's byte, documentation-file and browser limits are unchanged.
111
+ Combining or deleting contracts solely to reduce the count would add ownership and proof churn without
112
+ changing the required capability.
113
+
114
+ ### Added
115
+
116
+ Add the experimental Node-only `@openlup/platform/portability` entry for verified,
117
+ bounded object copy/resume and compatible PostgreSQL row capture/restore through
118
+ injected transaction handles. Object reads distinguish absent, denied and
119
+ unavailable; private filesystem publication preserves bytes, metadata and source
120
+ lineage with an explicit process-owner access policy. Row replay is exact and
121
+ conflicts refuse atomically; every enabled user INSERT trigger refuses.
122
+
123
+ Filesystem publication and readback share one encoded-descriptor byte ceiling
124
+ covering admitted Unicode metadata; oversize encodings refuse before publication.
125
+ Filesystem locators hash JSON-encoded logical keys, preserving distinct admitted
126
+ strings including lone UTF-16 surrogates. This first unpublished layout has no
127
+ legacy-format migration or fallback.
128
+
129
+ The bounded M14 B budget reads approved the initial code-gzip minimum of
130
+ 1,650,493 bytes, exactly 128 bytes for that necessary Unicode repair and 10 bytes
131
+ for exact string-key identity. The current measured minimum is 1,650,631 bytes,
132
+ cumulatively 2,631 above 1,648,000.
133
+ This allocates no additional forecast headroom. Other byte, file, docs and
134
+ browser limits and the released baseline are unchanged by this decision; later
135
+ candidates still need their own actual package measurement.
136
+
137
+ ### Migration
138
+
139
+ Select the entry explicitly. Install the canonical target catalogue
140
+ and qualify the source/target privileges separately; this API does not install
141
+ schema, copy migration ledgers, map managed identities or activate executors.
142
+ Changed-row catch-up, guarded-domain import and hosted effect-time fencing remain
143
+ M14 dependencies. Local synthetic proof does not certify complete-store transfer,
144
+ provider revocation or a stable migration service.
145
+
146
+ Node host shutdown now fences its stopped scheduler registrations and waits for
147
+ admitted callbacks, including pending lock acquisition and asynchronous unlock,
148
+ before closing the dedicated advisory-lock session. Other hosts remain excluded
149
+ until the running job releases ownership. Shutdown still attempts the listener
150
+ and lock cleanup, caches its promise and aggregates failures in the existing order.
151
+ PostgreSQL advisory locks now refuse locally pending or held numeric keys,
152
+ including colliding job IDs, so a dedicated session cannot reenter a job lock.
153
+ Failed acquisition permits a later attempt; failed unlock remains reserved until
154
+ the session closes.
155
+
156
+ Migration: `NodeSchedulerAdapter.stopAll()` explicitly returns `Promise<void>`
157
+ instead of `void`. Await it before disposing resources used by admitted callbacks.
158
+ It fences/stops current timers synchronously and supports later registrations.
159
+ The only in-tree production caller, `createNodeHost`, awaits that drain before
160
+ closing the lock; its public `stop(): Promise<void>` signature remains unchanged.
161
+ Custom implementations of `NodeSchedulerAdapter` must return the drain promise.
162
+
13
163
  ## [0.29.0]
14
164
 
15
165
  - Publishable on the npm `latest` dist-tag as `0.29.0`, from tag
@@ -395,141 +545,3 @@ reference handle or schema requirement is forwarded.
395
545
  Configured recovery/purchase elements use explicit host paths and clients. No SQL, version, serving
396
546
  activation or source-release snapshot changes. Regenerated account-support and
397
547
  composition API reports describe these additions; no sibling API report changed.
398
-
399
- ## [0.27.0]
400
-
401
- - Publishable on the npm `latest` dist-tag as `0.27.0`, from tag
402
- `openlup-platform-v0.27.0`.
403
-
404
- - Bind experimental native new-purchase previews to the existing ATP reader through the inventory and reference composition, protecting subscription stock without another stock calculation.
405
- - Migration: PostgreSQL hosts supply the optional `stockSourceKey` binding dependency to enable `newPurchaseStockReadPort`. The preview then binds with no unsupported reason; an absent or blank key reports `inventory_stock_source_key_required`. Admin readiness is unchanged; a required preview leaves reference readiness refused until the key is supplied.
406
- - Migration: Native previews subtract all live holds, remaining active subscription demand inside 14 days and channel exposure. For 20 units with 5 held and 7 still due, both availability fields report 8; a provider-tag-filtered preview counting only 2 of those held units would report 11 for new purchases. Credited own-cycle holds are not subtracted twice. Exposure of 4 reduces a budget of 11 to 7.
407
- - Migration: Native budgets clamp at zero, stale stock contributes zero to ATP, and local-only stock has no native source. The native preview refuses own-order exclusions or a horizon other than 14 days as `native_stock_read_options_unsupported`; it provides no one-time or replacement allocation seam.
408
- - Migration: Managed hosts apply the managed forward `20261025109000_inventory_new_purchase_stock_read.sql` after the managed migration prefix (`public.inventory_new_purchase_stock_read(p_skus jsonb, p_as_of timestamptz) RETURNS jsonb`, service_role-only execution), then supply optional `stockRpc` to the inventory binding (also forwarded through the reference store). An injected `newPurchaseStockReadPort` wins; without either dependency the existing `inventory_new_purchase_stock_reader_required` remains.
409
- - Migration: Managed preview quantities equal ATP with renewal exemption fixed false, preserving M10 provider-tagged holds, safety, 14-day uncredited demand and channel exposure. Both availability fields now include demand and clamp at zero. Other horizons and own-order exclusions refuse `managed_stock_read_options_unsupported`; SQL accepts at most 200 requested array items before deduplication and refuses a NULL as-of timestamp as `inventory_stock_as_of_invalid` (SQLSTATE `22023`). The managed preview treats ANY stale provider-stock evidence for the SKU as stale (fail-safe; exact when one provider kind exists); quantities remain unchanged and the allocator's own stale refusal stays authoritative.
410
- - Migration: Managed `source` is "provider" iff ATP returns a row for the SKU; otherwise it is "missing".
411
-
412
- - Add experimental `@openlup/platform/commerce` neutral schema cores, contract helpers and ports, plus type-only browser-safe `@openlup/platform/commerce/contracts`. Reference bindings extend these cores with existing profile, locale, fiscal and provider policy. No version or artifact cap changes.
413
- Migration: Commerce-owned ports and generic records may be imported from `commerce/contracts`. Pricing DTOs remain at `@openlup/platform/pricing/contracts` directly, without convenience re-exports from commerce. Reference exported names remain available.
414
- Migration: `commerceOfferVersionSchema` now validates opaque offer tokens of at most 40 characters, using the lower-case token grammar (D1).
415
- Migration: The commerce quote port's out-of-band `CreateQuoteOptions` now accepts the server-bound `offerVersion`; the M05 options and quote DTOs remain their existing owner (D2).
416
- Migration: Reference quote context types additionally carry optional shipping and acquisition terms using their existing package definitions (D3).
417
- Migration: Checkout expected-quote acceptance and price-change responses now admit acquisition expectations independently of totals; invalid revisions and discount bounds are refused (D4).
418
- Migration: Configurator intents additionally admit acquisition capability, opaque `offerVersion` and bounded `minimumUnits` asks (D5).
419
- Migration: A supplied minimum replaces the injected host default for untrusted intent validation only; it does not authorize server checkout admission (D6).
420
- Migration: `offerAvailabilityRequestItems` projects one unit per variant in input order and the supplied checkout mode (D7).
421
- Migration: The reference configurator-to-quote mapper forwards an admitted acquisition capability, leaving absent capabilities absent (D8). This does not activate an acquisition issuer or offer guard.
422
- Migration: `CheckoutOfferPolicyPort<Intent, Quote>` and its bound/refused result are available as types only (D9). Offer resolution, evidence execution and the starter guard remain outside K1 and are deferred to K2a.
423
- Migration: Reference recovery policy, nominal errors and order-contact helpers delegate to the package with identity preserved. Neutral checkout, resume and defaults schema factories require explicit host bindings; their reference extensions retain existing acceptance, parsed output and error paths.
424
- Migration: `commerce/server` is a reserved empty Node-only entry; browser consumers continue to use `commerce` and `commerce/contracts`. Canonical order-money and commerce outbox payload validation are available from `commerce`; host quote/draft schemas are injected with the existing validation behavior.
425
- Migration: Checkout admission refuses unbound offer/minimum asks while no server offer resolver is composed, retaining the host floor for ordinary requests; untrusted intent parsing still accepts those asks.
426
- Migration: The commerce quote port requires request, response and host-options type parameters; the reference binds the existing pricing definitions and retains its named types. This removes an unnecessary pricing declaration closure without copying its contracts or changing pricing behavior.
427
- - Add browser-safe `@openlup/platform/pricing/browser` with direct re-exports of the existing quote primitive factory and acquisition capability/expectation schemas. Reference imports retain symbol identity and validation behavior; the pricing root and contracts entry are unchanged.
428
- Migration: Regenerated `communications.api.md`, `fulfillment.api.md` and `inventory.api.md` change declaration order only: TypeScript emits union and enum members in literal-creation order across the program. For `defaultCommunicationPurposeRegistry`, before: `"transactional" | "marketing_launch_offer" | "marketing_newsletter" | "tester_program" | "subscription_dunning" | "admin_notification"`; after: `"transactional" | "subscription_dunning" | "marketing_launch_offer" | "marketing_newsletter" | "tester_program" | "admin_notification"`. Communications newsletter, fulfillment and inventory enum members likewise appear in a different order. The member sets and all types are unchanged; type consumers are unaffected and need no code or SQL migration.
429
-
430
- - K2 lands no SQL. A dedicated later PR, L1, lands all nine reviewed managed M11 slots (`scripts/fixtures/reviewed-m11/supabase/migrations/20261025100000..110000`) in order; no release ships K2 without them (D-M11-SQL-LAND-1).
431
- - Until L1 lands on the managed rail, a 21-day starter graduation cadence passes admission but fails at provisional-subscription creation: the installed `subscription_create_provisional_for_checkout` and `subscription_apply_starter_graduation` still accept only 14 and 28. Checkout returns the generic failure (HTTP 503).
432
- - Until L1 lands on the managed rail, the finalize acquisition-admission backstop is inert: `commerce_finalize_order_for_checkout` does not invoke `private.commerce_assert_acquisition_admission` to raise `acquisition_terms_changed` (SQLSTATE 55000), so the package mapping and the safe-compensation re-quote it triggers never fire from the database. The TypeScript quote guard still re-quotes a changed acquisition expectation before finalize.
433
- - Until L1 lands on the managed rail, `commerce_configurator_persist_intent` lacks the donor preference write scope: preference/consent writes are not restricted to the authenticated owner, and the legacy country fallback stays as installed.
434
-
435
- - Move the unchanged checkout compensation helper and cleanup port into `@openlup/platform/commerce/server`. The reference facade re-exports the identical function; release/cancellation ordering, idempotency keys, reasons and warnings are unchanged.
436
-
437
- - Move checkout handlers, the shared paid-order saga, runtime and command execution into the experimental Node-only commerce entry. Host projections, schemas, response routing, starter policy and existing payment execution are injected; reference paths delegate to one package implementation.
438
- Migration: Acquisition expectations independently reject changed terms in the TypeScript quote guard before finalize; a locked finalize refusal re-quotes only after safe draft compensation once the managed forwards land (L1) (N1). Shipping or acquisition terms now require promotion acceptance even without a current promotion discount (F2).
439
- Migration: Failed promotion-price-change re-quotes now map `CommerceQuoteError` code `UNKNOWN_SKU` to `BAD_REQUEST` (HTTP 400), and `PRICE_NOT_CONFIGURED`, `UNSUPPORTED_TAX_PROFILE` or `PRICING_INVARIANT_VIOLATION` to `CONFLICT` (HTTP 409), forwarding `error.message` and `error.details` instead of the base's `UPSTREAM_UNAVAILABLE` (HTTP 503), "Checkout failed" and `{ feature: "checkout", stage: "quote" }`. Newly supported acquisition-terms-change re-quotes use the same typed mapping (donor N1).
440
- Migration: Failed promotion-price-change re-quotes with `CommerceQuoteCatalogReadError` retain `UPSTREAM_UNAVAILABLE` (HTTP 503), but now return "Commerce catalog is unavailable" and `{ reason: "catalog_unavailable", refusalCode: error.code }` instead of the base's "Checkout failed" and `{ feature: "checkout", stage: "quote" }`. Newly supported acquisition-terms-change re-quotes use the same catalog mapping (donor N1).
441
- Migration: Initial quotes, including normal quoting after saved-continuation fallback, and promotion-price-change re-quotes now map `AcquisitionTermsError` reasons `acquisition_terms_capability_required` and `acquisition_terms_v2_required` to `CONFLICT` (HTTP 409), "Acquisition terms unavailable" and `{ reason: error.reason, refreshRequired: true }`. The base returned `UPSTREAM_UNAVAILABLE` (HTTP 503), "Checkout failed" and `{ feature: "checkout", stage: "orchestrate_order" }` with an optional sanitized preview `diagnosticReason` for initial quotes, or `{ feature: "checkout", stage: "quote" }` for promotion re-quotes. Newly supported acquisition-terms-change re-quotes use the same acquisition mapping (donor N1).
442
- Migration: On those initial/continuation and promotion re-quote paths, `AcquisitionTermsError` reasons `acquisition_terms_policy_unconfigured`, `acquisition_terms_invalid`, `acquisition_terms_ambiguous` and `acquisition_terms_not_effective` retain `UPSTREAM_UNAVAILABLE` (HTTP 503), but now return "Acquisition terms unavailable" and `{ reason: error.reason, refreshRequired: false }` instead of the base's "Checkout failed" and initial-quote orchestration/preview or promotion re-quote stage details described above. Newly supported acquisition-terms-change re-quotes use the same acquisition mapping (donor N1).
443
- Migration: An offer-version or minimum-units ask requires a server offer-policy binding. Without a resolver, reference admission retains its host minimum and original validation refusal before persistence. A composed resolver binds or refuses before any quote, order-draft or runtime write; identity persistence retains its existing earlier ordering. Accepted evidence is bounded and the bound version follows authoritative, steady and replacement quotes (N2).
444
- Migration: An owned saved acquisition quote may continue before re-quoting only when subject context, basket, total, terms, contact, invoice, delivery and starter state match exactly; edits and failed/incomplete lookups take normal quoting (N3).
445
- Migration: Scoped inventory admission contention returns retryable unavailability without provider dispatch or compensation capability; retry identities are unchanged (N4). Raw database error classification remains an adapter responsibility.
446
- Migration: Starter admission accepts injected terms and a supplied graduation constraint, includes the 21-day graduation cadence, compares acquisition revision and rate, and freezes the selected second-delivery discount with steady quote policy/version (N5). Reference starter defaults remain host inputs. End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
447
- Migration: The best-effort account-link helper accepts an optional trigger for its existing timeout log; without a trigger its log and timeout behavior are unchanged (N8).
448
- Migration: Saved-method alias and recurring-mode metadata are host-defined string generics throughout the checkout resolver, handler, orchestration, command and runtime APIs. Reference bindings retain their existing provider unions, wire values and execution behavior.
449
- Migration: The offer-evidence JSON-length limit is internal; consumers use the exported evidence schema.
450
- Migration: The reference browser quote context now admits optional shipping and resolved acquisition terms through their existing validators, preserving strictness and existing fields (donor D3; K1-scope port carried by K2). `pricing/browser` re-exports the identical schema objects without new validation logic.
451
- Migration: `outbox.commerceOrderDraftCreatedEventSchema` now accepts the 21-day starter cadence at `payload.quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`, `payload.orderDraftSnapshot.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
452
- Migration: `outbox.commerceOrderDraftCreatedOutboxRecordSchema` now accepts the 21-day starter cadence at `payload.quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`, `payload.orderDraftSnapshot.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
453
- Migration: `outbox.commerceOrderDraftCreatedPayloadSchema` now accepts the 21-day starter cadence at `quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`, `orderDraftSnapshot.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
454
- Migration: `checkout.checkoutRequestSchema` now accepts the 21-day starter cadence at `intent.starterOffer.steady.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
455
- Migration: `checkout.checkoutResponseSchema` now accepts the 21-day starter cadence at `authoritativeQuote.quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
456
- Migration: `contracts.commerceQuoteSchema` now accepts the 21-day starter cadence at `context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
457
- Migration: `contracts.createOrderDraftRequestSchema` now accepts the 21-day starter cadence at `quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
458
- Migration: `contracts.createOrderDraftResponseSchema` now accepts the 21-day starter cadence at `orderDraft.quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
459
- Migration: `contracts.createQuoteBatchResponseSchema` now accepts the 21-day starter cadence at `quotes.0.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
460
- Migration: `contracts.createQuoteResponseSchema` now accepts the 21-day starter cadence at `quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
461
- Migration: `contracts.orderDraftSummarySchema` now accepts the 21-day starter cadence at `quoteSnapshot.quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
462
- Migration: `contracts.publicCreateQuoteBatchResponseSchema` now accepts the 21-day starter cadence at `quotes.0.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
463
- Migration: `contracts.publicCreateQuoteResponseSchema` now accepts the 21-day starter cadence at `quote.context.starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
464
- Migration: `contracts.quoteContextSchema` now accepts the 21-day starter cadence at `starterPack.graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
465
- Migration: `contracts.starterPackPlanSchema` now accepts the 21-day starter cadence at `graduation.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
466
- Migration: `intent.configuratorIntentSchema` now accepts the 21-day starter cadence at `starterOffer.steady.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
467
- Migration: `persistence.configuratorIntentPersistenceRequestSchema` now accepts the 21-day starter cadence at `starterOffer.steady.cadenceDays`; invalid-cadence issue alternatives change from `[14, 28]` to `[14, 21, 28]` in that order (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
468
- Migration: The reference subscription starter-marker reader now also accepts the 21-day graduation cadence, matching the checkout starter plan; 30 days remains refused (donor N5). End-to-end managed checkout with this cadence requires the managed forwards to land (L1).
469
-
470
- - Move generic draft/finalize/intent/resume stores, cancellation and sweep adapters, bounded recovery classifiers and token helpers into `commerce/server`. Reference factories inject existing schemas, ordered arguments, response projections and phone normalization; verified subject stamping remains last. Recovery projection/routes stay reference-owned; the C2 release handoff is to be released.
471
- Migration: Runtime-finalize `acquisition_terms_changed` now retains its scoped conflict reason; database-triggered safe pre-dispatch draft compensation and repricing become reachable once the managed forwards land (L1) (N1).
472
- Migration: Draft catalog-head-moved, missing-anchor and offer-membership refusals now map to catalog-admission conflicts without superseding a draft (N1).
473
- Migration: Expired subscription recovery permits an absent host subject only with the exact persisted neutral-command marker and all other eligibility fences; public runtime schemas gain no marker bypass (N6).
474
- Migration: Recovery commercial fingerprints now include shipping terms version, currency, flat charge and threshold; same-money policy drift refuses recreation (N6).
475
- Migration: The token-state classifier permits continuation only for active/order-not-recoverable, separates expired-policy handling and refuses revoked/used/missing/unknown states. Retained routes are not rewired by this addition (N7).
476
- Migration: `StarterDeclaration` stays internal to the checkout engine; derive a declaration type from the `createStarterOfferGuard` binding signature instead of importing a standalone type from `commerce/server`.
477
-
478
- - Add the unchanged physical-table offer-availability projection at `commerce/server` over a structural client and explicit provider predicate, and the pure status/reason ladder at browser-safe `commerce`. Reference adapters retain SDK/provider policy and delegate to the one package implementation; M06 retains normalized stock reads and reservation TTL ownership. No preview ATP switch or second allocator.
479
- Migration: The reference reservation binding now maps protected inventory `55P03` failures to scoped `inventory_admission_busy`/`inventory_lock_unavailable` details, refuses schema fallback under contention and preserves the original retry keys (N4). Checkout exposes the existing retryable refusal before dispatch; no compensation capability is fabricated.
480
- - Give structural draft, resume, intent and compensation factories neutral RPC/query names. Reference bindings retain their incumbent exported names and behavior.
481
-
482
- - Add experimental neutral OMS schema cores, browser-safe DTOs and ports, generic handler factories, read builders and managed adapters through the existing commerce entries. Reference wrappers bind identity, settlement, fiscal fields, governance and provider projections. No versions, SQL, migrations or pack caps change.
483
- Migration: Host integrations supply `respond`, `authorizeAdmin` and optional read-gate/schema bindings. Mutation request parsing and response envelopes use the donor shared helpers; invalid results remain 502, nominal conflicts 409 and upstream throws 503 with their existing messages.
484
- Migration: Managed clients are structural and RPC-only; query hydration and idempotent note persistence require a separately injected query capability. Manual refund marking calls only the operator-mark RPC and creates no refund.
485
- Migration: Neutral read contracts omit private identity and first-cycle presentation, use open provider/accounting status strings, a neutral fiscal field and neutral provider counter. Hosts extend the schema and pass projections through final validation to preserve their existing response fields and acceptance.
486
- Migration: The reference replacement facade now delegates to the existing fulfillment handler instead of its local handler engine. For managed results, request parsing, success bodies (including defaulted released hold IDs), replay receipts, metadata, idempotency keys, RPC arguments, receiver identity, named 409 refusals and ordinary 400/401/403/405/502/503 responses are unchanged. The fulfillment handler additionally recognizes the native-unsupported sentinel and returns its specific 503; the old local handler would classify that sentinel as an invalid 502 response. The managed adapter does not emit this sentinel. Neither path creates a refund or confirms delivery alignment.
487
- Migration: Default neutral settlement validation checks a three-letter currency and labels empty totals with `XXX`; hosts inject their actual acceptance/default policy. Delivery summaries and labels use neutral defaults until the host supplies its projections.
488
- Migration: Browser-safe `./commerce` exports schemas and pure helpers; handlers, managed RPC/query adapters and detail composition now import from the Node-only `./commerce/server` entry. `./commerce/contracts` remains type-only.
489
- Migration: Unprojected OMS timeline labels now use canonical step keys (for example `delivered`) instead of the reference locale labels. Unknown tokens retain `Delivery status updated`; reference presentation remains behind the existing `timelineLabel` projection. Managed query clients must implement the required `is(column, value)` filter for hydration; class query receivers are preserved by the adapter factory.
490
- Migration: Omitted fulfillment debug now defaults to `No fulfillment data.` in neutral detail schemas. The reference schema binding retains its previous localized summary and serialized field order.
491
- Migration: Commerce no longer re-exports the core locale label helper `timelineLabelForStep` or the label-bearing `FULFILLMENT_STATUS_MAP`. Presentation consumers import these from their core owner or host binding; commerce retains pure canonical step and recovery helpers.
492
- Migration: OMS binds K1 order-money and paid-event exports directly. The concrete OMS payment type is `OmsOrderPaymentStatus`, using K1's unchanged generic `OmsPaymentStatus<PaymentIntentStatus>`. Fulfillment recovery DTOs are commerce-owned alongside their pure recovery helpers.
493
- Migration: Regenerated `commerce.api.md`, `commerce-contracts.api.md`, `commerce-server.api.md`, `communications.api.md`, `fulfillment.api.md` and `identity.api.md` reflect this final declaration graph. Beyond the commerce additions described above, existing declarations change order only: newsletter event `ignored`, fulfillment status members and identity lifecycle-stage members move within their existing declarations. Before and after member sets and types are identical; consumers need no code or SQL migration for this ordering.
494
- - @openlup/platform size growth: Neutral OMS read model, handlers, managed adapters and contracts moved into `@openlup/platform/commerce` and the new Node-only `./commerce/server` entry, together with the rest of the M11 commerce stack; K1+K3a measured 1,562,728 packed bytes; adding K3b, K4, K2 (K2a x1.4) and F3 projects 1,749,300 packed bytes; caps raised once with 10% headroom to 1,925,000 packed bytes, 1,648,000 code-gzip bytes, 8,970,000 unpacked bytes, 2,520 code files and 2,580 total files (K3a PR #370, cap-raise commit 5e42e9ec).
495
-
496
- - Add experimental returns, native order review/media and separate hosted-feedback contracts at `@openlup/platform/commerce`, with handlers and adapters at `@openlup/platform/commerce/server`. Reference paths remain thin facades; no route, SQL, activation or release is added.
497
- - Migration: Import returns and native order-review/media handlers and adapters from `@openlup/platform/commerce/server`; schemas and port declarations remain at `@openlup/platform/commerce`. Standalone returns handlers require an injected `BffResponder`; reference handler signatures and observed response context are preserved by their facades. Raw upload HTTP types now use the equivalent package HTTP shapes.
498
- - Migration: Hosted-feedback schemas and RPC-name constants are available from `@openlup/platform/commerce`; Supabase submit/token-check factories are at `@openlup/platform/commerce/server`. Adopters must supply `submit_order_feedback` and `check_order_feedback_token`; native `db/platform` has neither RPC. Hosted feedback remains distinct from native order reviews.
499
- - Returns scope (F9): only request, approve and reject exist. `restockDisposition`, `refundMode` and `refundAmountCents` record intent; receive, restock and refund execution were never implemented. Request owner/key/fingerprint enforcement stays in the database; the contributed TypeScript RPC arguments are unchanged.
500
- - Native handler donor-ahead command-runner contribution is observably identical to the prior inline handlers: the 96 pre-move result pins pass, including admin error mapping and exact `replayed` presence. No behavior migration arises from this command-runner contribution.
501
- - HOST-OWNED class (b) retention: review delay is SQL-only, 14 days native and 21 days in the contributed managed profile. No TypeScript delay seam or SQL change is included.
502
- - Media retains its existing private storage/upload seams. M02 blob storage lacks private read, inspection, temporary write and promotion operations, so a behavior-changing bridge is not included.
503
- - Migration: The package default returns reason set is neutral. Use `createCommerceReturnsSchemas(reasonCodes)` and the customer handler's `requestSchema` dependency for host policy; the reference keeps the legacy set with BASE-identical parsed output, refusal details and responses. Return request/approve/reject RPC behavior is unchanged.
504
- - Migration: Reference browser review and hosted-feedback facades restore jitless Zod initialization before package schema construction. This restores BASE/donor CSP behavior without adding global configuration to the package modules.
505
- - Migration: `runOrderReviewCommand` is internal to the package. Import the customer/admin handler factories from the commerce/server entry; the reference customer-handler facade keeps its BASE factory export.
506
- - Migration: Handlers, adapters and raw upload use the existing `@openlup/platform/commerce/server` entry. The `./commerce` runtime graph is browser-safe; `./commerce/contracts` stays type-only. Reference import paths and observed behavior are unchanged.
507
-
508
- - Add experimental Node-only commerce domain-effect consumers at `@openlup/platform/commerce/server`; browser-safe event contracts, projections and ports stay at `@openlup/platform/commerce`. No new executor, emitter or dispatcher.
509
- - Record omitted adopter-private W8/W9 assertions and their owners in the [reference commerce guide](../../src/domains/commerce/README.md#w8w9-conformance-dropped-adopter-private-assertions).
510
- - Migration: Import handler factories, registry composition and `CommerceEmailRuntime` from `@openlup/platform/commerce/server`. The browser entry never imports the server entry or M08 runtime.
511
- - Migration: Reference email handlers and the dispatch registry bind a single neutral implementation. Package ports use `contextName` and `messageId`; reference adapters retain their existing extension/provider fields and public send behavior.
512
- - Migration: `uniqueRegistry` is injected from the existing outbox rail, with no new package dependency. `CommerceEmailRuntime` requires explicit communications parser, transactional scaffold, outcome mapping, locale, money, line-label, paid-presentation, tracking and notification-policy bindings. Reference locale, formatting, provider outcomes and legacy tracking URLs remain unchanged.
513
- - Migration: Refund notices display amounts only with `refundEvidenceVersion: "provider-refund.v2"`; historical order totals and unversioned refund amounts no longer appear as refund evidence (donor-ahead).
514
- - Migration: The frozen refund consumer subset ignores legacy `totalCents` and admits optional string `refundEvidenceVersion`; supplied refund amounts and currencies retain their existing validation.
515
- - Migration: Paid-receipt presentation forwards its proved discount percentage, including non-default percentages (donor-ahead); commercial eligibility stays with the host.
516
- - Migration: Core handler descriptors and expected-descriptor validation are available before claiming. Claim order, flags, independent paid-email/fulfillment duties, same-event timeout composition and risk gating retain donor behavior.
517
- - Migration: Channel-owned buyer communication settles as processed with `skipped: "channel_owns_buyer_comms"`, using a live policy read per event. Cancellation email remains unregistered; its fact can be consumed through adopter `extraHandlers`.
518
- - Migration: Producer event-type literals and payload schema behavior remain unchanged; the draft-event factory accepts exact host snapshot schemas. The neutral source projection preserves external-reference bytes and case, with no inventory SQL or exposure default.
519
- - Migration: Reference email payload parsing binds the existing fulfillment `parseOutboxPayload` export; its schema issues and bounded discard reason are unchanged. K1 owns all producer schemas through `createCommerceOutboxEventSchemas`; all nine golden parse/refusal cases pass unchanged.
520
- - Migration: Paid-fulfillment registration re-exports the existing fulfillment descriptor, preserving its identity, event literal and timeout instead of maintaining a second descriptor.
521
-
522
- - Add an experimental structural commerce contribution at the existing composition entry, with explicit installed commerce exports, namespaced ports and existing handler, route and schedule descriptors. Duplicate registrations refuse before maps can overwrite an executor.
523
- - Add an inert, default-off reference commerce binding over existing package callables and the existing native checkout-recovery adapter. Only ready schema observations admit work; unknown and unsatisfied candidates leave the serving selection intact. Native recovery records reminder intents, authorizes their delivery and compacts terminal outbox rows; managed-only expiry and recreation remain separate.
524
- - K5 adds no refactor: the event-contract gap and server entry scaffold are already resolved in the preceding imports. Existing commerce witnesses and engines remain unchanged; no SQL, timer, route activation or second executor is introduced.
525
- Migration: `@openlup/platform/composition` additively exports `createCommerceContribution`. Supply the selected callables, complete required schema and existing descriptors; the factory declares them without installation or execution. Existing imports and default compositions need no change.
526
-
527
- - Managed commerce migrations preserve the exact reviewed fixture bytes and ordered prerequisite chain.
528
- Migration: Guest configurator destinations do not rewrite saved delivery or payment preferences; preference writes require a server-proved matching account.
529
- Migration: Legacy omitted-country fallback uses `platform_region_code()` for address identity and insertion; configure the adopter's settlement region. Neutral commands require explicit country.
530
- Migration: Return creation and replay require the server-supplied principal's owned order and identical normalized command; foreign or changed commands refuse atomically.
531
- Migration: Checkout payment-link receipts use the service-only operator entry point and the `checkout_payment_link_mint` audit action.
532
- Migration: Subscription finalize validates retained acquisition terms under the shared policy lock; policy writers require its exclusive counterpart. Completed finalize replay preserves its response after policy changes; one-time checkout is exempt.
533
- Migration: The acquisition terms reader refuses absent effective terms; the no-policy finalize compatibility branch remains available.
534
- Migration: New-purchase stock reads use ATP with renewal exemption fixed false, bounded SKU arrays and conservative stale reporting. The service-only reader uses owner privileges with `SECURITY DEFINER` and `search_path = pg_catalog, pg_temp`.
535
- Migration: Starter graduation admits 14, 21 or 28 days, while provisional creation uses the retained starter interval and subscription timezone default. Rolling back below the forward with a 21-day marker is unsupported; roll forward.
package/README.md CHANGED
@@ -10,8 +10,8 @@ Development preview. This package is part of the publishable set with core and o
10
10
 
11
11
  It holds the runnable server substrate an OpenLup application composes: the Node HTTP runtime, BFF dispatch, scheduling and job leases, blob storage, data gateways, the node-postgres migration runner and bundle composition. Ports and their contracts stay in `@openlup/core/platform-runtime`.
12
12
 
13
- For the prepared `0.29.0` set, read the [adjacent-release migration and known
14
- limitations](CHANGELOG.md#0290) before selecting optional services. Experimental
13
+ For the prepared `0.30.0` set, read the [adjacent-release migration and known
14
+ limitations](CHANGELOG.md#0300) before selecting optional services. Experimental
15
15
  M13 marketing uses browser-safe `./marketing`, type-only browser-safe
16
16
  `./marketing/contracts`, and Node-only `./marketing/server` and
17
17
  `./marketing/server/postgres`. Marketing contributions and bindings remain
@@ -54,7 +54,7 @@ Adopters must not activate unselected or unready invoicing; installation and
54
54
  inert contributions register no runner, worker, route or schedule.
55
55
  M06 managed-host proof classes remain pending in the
56
56
  [M06 parity ledger](../../docs/platform/plans/oss-m06-stock-reservations-delivery.md#parity-pending-rows).
57
- Size comparison uses the published `0.28.0` tarball. Preparation and offline
57
+ Size comparison uses the published `0.29.0` tarball. Preparation and offline
58
58
  adapter evidence grant no publication or provider-account certification.
59
59
 
60
60
  Longer module recipes live in the [platform package reference](../../docs/platform/PLATFORM_PACKAGE_REFERENCE.md).
@@ -68,12 +68,52 @@ alongside seconds/fractions, compact offsets and local timestamps. Calendar
68
68
  validation still rejects impossible dates; validation never rewrites the raw
69
69
  timestamp used in the webhook's idempotency key.
70
70
 
71
+ The experimental migration source may supply `assertSession` to observe host
72
+ facts once under the existing advisory lock, after exact ledger-prefix admission
73
+ and before status, dry-run or pending SQL. Sources without it retain current
74
+ execution. The [migration owner](../../docs/platform/DATA_AND_MIGRATIONS.md#module-catalogues-and-installed-histories)
75
+ and [runner witness](test/migrations/postgresRunner.test.ts) define that boundary;
76
+ this callback does not provision or qualify a hosted installation.
77
+
71
78
  ## Package surface
72
79
 
80
+ The experimental Node-only `./lifecycle` entry plans and applies explicit
81
+ application-file snapshots. It preserves unmanaged files and local edits in
82
+ upstream-unchanged files, refuses divergent changed files before writes, and
83
+ resumes exact completed replacements after interruption. The caller holds an
84
+ exclusive maintenance window and supplies schema-range evidence; this entry
85
+ runs no database migration, npm install or deployment. Read the
86
+ [file-ownership boundary](../../docs/platform/ARCHITECTURE_AND_EXTENSIONS.md#application-file-upgrades)
87
+ and [disposable app recipe](../../docs/platform/PLATFORM_PACKAGE_REFERENCE.md#application-file-upgrade).
88
+
89
+ The same entry exports `inspectLegacyPostgresInstallRoles`, a read-only query
90
+ through a caller-owned PostgreSQL handle. Its
91
+ `legacy-fresh-bootstrap-role-prerequisites` report observes finite immutable
92
+ legacy bootstrap role conditions; `rolePrerequisitesMet` does not establish
93
+ install readiness, schema/ACL correctness or provider support. See the
94
+ [legacy role boundary](../../docs/platform/DATA_AND_MIGRATIONS.md#legacy-fresh-bootstrap-role-observation).
95
+
96
+ The experimental Node-only `./portability` entry copies a bounded, explicitly
97
+ complete immutable/quiesced object inventory and captures/restores selected
98
+ compatible PostgreSQL rows through injected transaction handles. Private
99
+ filesystem objects publish bytes and metadata together, bind an explicit access
100
+ label to the filesystem owner's private policy and resume by verified readback.
101
+ Row replay preserves exact JSON/numeric/time values, refuses conflicts and every
102
+ enabled user INSERT trigger, and copies no schema, migration ledger or grants.
103
+ The host qualifies the canonical catalogue, credentials and source completeness.
104
+ These helpers activate no executor and do not supply managed identity mapping,
105
+ live changed-row catch-up or hosted old-worker fencing. Read the
106
+ [transfer boundary](../../docs/platform/ARCHITECTURE_AND_EXTENSIONS.md#existing-store-transfer-and-recovery)
107
+ and the retained [M14 obligations](../../docs/platform/plans/oss-m14-operations-portability.md).
108
+ The provider-owned HTTP counterexample exercises an existing adapter's cached
109
+ bearer; its local fixture establishes no hosted revocation guarantee.
110
+
73
111
  `release-gates.json` declares kind `rail`: this foundation provides runtime infrastructure over core ports, matching the architecture's rail responsibility. Its experimental entries each bind a declaration snapshot and package-owned smoke tests. The API checker reads this same inventory.
74
112
 
75
113
  | Export | Contents |
76
114
  | --- | --- |
115
+ | `./lifecycle` | Experimental Node file-snapshot planning/apply and read-only legacy PostgreSQL role prerequisites; no install-readiness claim, optional SDK or activation |
116
+ | `./portability` | Experimental server object copy/resume, private filesystem transfer store and compatible PostgreSQL row capture/restore; injected handles, explicit refusal and no activation |
77
117
  | `./http` | Generic capped raw-body reader, hex HMAC and constant-time token comparison; Node request adaptation, deadlines, security headers and static documents, and `createNodeHttpRuntime` with its fixed request order |
78
118
  | `./bff` | `createBffDispatcher`, `lazyBffRoute`, the hosted router URL rewrite, the response envelope (`createBffResponder`), the observed request context and the health route |
79
119
  | `./scheduler` | Transport-neutral scheduled jobs (`ScheduledJob`, the job registry, the lease-aware runner and the authenticated HTTP cron entry), path-declared jobs from configuration, the node-cron scheduler with per-job advisory locks, hosted cron verification, the cron entrypoint guard (it compares the presented bearer token with `CRON_SECRET` in constant time) and direct job bindings |
@@ -723,6 +763,25 @@ both exported helpers and their signatures: `calculateIncludedVat` delegates to
723
763
 
724
764
  A job is `{ id, schedule, lease?, run(context) }` with a UTC cron expression. Domains and packages contribute jobs to `createScheduledJobRegistry`, which refuses duplicate ids and ships empty. The Node host runs registry jobs on its own timers and calls `run` directly, with no HTTP request and no secret. `createScheduledJobHttpEntry` mounts the same job behind the cron guard for a hosted cron. A job that declares `lease` runs only after the injected job-lease port grants it; a lease held elsewhere skips the run, and a finish the port refuses fails the run. `scheduledJobsFromContribution` turns a contribution's cadence schedules into jobs and refuses a cadence that no cron expression matches exactly; a contribution run that reports a failed outcome fails the job.
725
765
 
766
+ `NodeSchedulerAdapter.stopAll()` returns `Promise<void>`. It fences and stops the
767
+ current registrations synchronously, then waits for callbacks already admitted,
768
+ including pending lock acquisition and unlock. Await it before disposing their
769
+ resources; custom scheduler implementations must return that drain promise.
770
+ Later registrations remain supported. The Node host caches its `stop()` promise,
771
+ closes its listener and retains the dedicated PostgreSQL lock session until the
772
+ drain settles, including failure cleanup.
773
+
774
+ The PostgreSQL lock adapter also reserves each numeric advisory key locally
775
+ before acquisition. This prevents reentry on the same session, including pending
776
+ acquisitions and colliding job IDs. Failed acquisition releases the reservation;
777
+ failed unlock retains it until session disposal. The
778
+ [disposable PostgreSQL witness](../../tests/postgres/nodeHostRuntimeDrain.test.ts)
779
+ checks same-session exclusion and replacement-host admission after drain.
780
+ This graceful-stop contract does not fence an old host at external provider I/O
781
+ or settle an effect accepted before an acknowledgement; the
782
+ [transfer boundary](../../docs/platform/ARCHITECTURE_AND_EXTENSIONS.md#existing-store-transfer-and-recovery)
783
+ retains those separate duties.
784
+
726
785
  ## Bundle readiness
727
786
 
728
787
  `PLATFORM_BUNDLE` selects `vercel-supabase` (the default when absent), `node-supabase` or `node-postgres`. A bundle's readiness refuses, before any traffic or timer: an unknown `PLATFORM_BUNDLE` (resolution itself still falls back to the default); a self-host bundle without `APP_BASE_URL`; and, reported together under `OPENLUP_E_ENV_MISSING`, every selected capability without its settings: the scheduler without `CRON_SECRET`, Node scheduling without `DATABASE_URL` for its cluster lock (never a silent single-instance lock), and the selected blob capability without its settings (see Blob storage). An unknown `PLATFORM_BLOB` is refused too. The Node host checks readiness at boot.
@@ -1283,3 +1342,21 @@ their owner meaning. Contribution descriptors install no routes, handlers,
1283
1342
  schedules or workers. See the
1284
1343
  [reference recipe](../../docs/platform/RUNTIME_AND_SELF_HOSTING.md#opt-in-disposable-subscription-reference)
1285
1344
  for the host's schema and transport obligations.
1345
+
1346
+ ## Operations and diagnostics
1347
+
1348
+ The experimental `./operations` entry contains browser-safe operational schemas,
1349
+ alert projections and `createOperationsClients`, which binds an existing BFF
1350
+ requester. `./operations/contracts` contains DTOs and narrow ports only.
1351
+ `./operations/server` contains settings read/update, pipeline read, alert overview,
1352
+ control-plane handlers and the existing watchdog delivery mechanism. Authorization,
1353
+ SQL execution, evidence evaluation and alert transport are supplied by the host;
1354
+ importing these entries registers no route, schedule or provider.
1355
+
1356
+ `runControlPlaneWatchdogTick` evaluates persisted neutral job failures and records
1357
+ an idempotent heartbeat unless `checkOnly` is true. The richer watchdog accepts a
1358
+ typed evaluator; the public reference binds its maintained domain evaluator.
1359
+ Settings preserve scalar values, and pipeline reads preserve the existing tester
1360
+ and email projection. Identity membership and tracking effects keep their owners.
1361
+ See the [operations architecture](../../docs/platform/ARCHITECTURE_AND_EXTENSIONS.md#operations-and-diagnostics)
1362
+ for refusal behavior, SQL prerequisites and the bounded preview scope.
@@ -88,7 +88,7 @@ export interface ServeNodeResult {
88
88
  bundleId: string;
89
89
  httpRuntime: HttpRuntimePort;
90
90
  registeredJobs: string[];
91
- /** Stop timers and the local listener after a host signal; safe to call repeatedly. */
91
+ /** Fence timers, drain admitted jobs, then close their lock session; also close the local listener. Safe to call repeatedly. */
92
92
  stop(): Promise<void>;
93
93
  }
94
94
  export interface NodeHost {
@@ -133,12 +133,13 @@ export function createNodeHost(deps) {
133
133
  return { assertBundleReady, serveNode };
134
134
  }
135
135
  async function stopNodeHost(scheduler, advisoryLock, httpRuntime) {
136
- const timers = Promise.resolve().then(() => scheduler?.stopAll());
136
+ const timers = scheduler?.stopAll() ?? Promise.resolve();
137
137
  const server = httpRuntime.server;
138
138
  const listener = server
139
139
  ? new Promise((resolveClose, reject) => server.close((error) => error ? reject(error) : resolveClose()))
140
140
  : Promise.resolve();
141
- const results = await Promise.allSettled([timers, advisoryLock?.close(), listener]);
141
+ const lock = timers.then(() => advisoryLock?.close(), () => advisoryLock?.close());
142
+ const results = await Promise.allSettled([timers, lock, listener]);
142
143
  const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
143
144
  if (failures.length > 0)
144
145
  throw new AggregateError(failures, "node_host_shutdown_failed");
@@ -0,0 +1,52 @@
1
+ /** Exact UTF-8 scaffold files; every unlisted path remains application-owned. */
2
+ export interface AppVersionSnapshot {
3
+ version: string;
4
+ schema: {
5
+ min: number;
6
+ max: number;
7
+ };
8
+ files: Readonly<Record<string, string>>;
9
+ }
10
+ export interface AppUpgradeInput {
11
+ /** Absolute canonical path (as returned by realpath) of an existing app directory. */
12
+ root: string;
13
+ from: AppVersionSnapshot;
14
+ to: AppVersionSnapshot;
15
+ /** Observed by the caller; planning and applying execute no database work. */
16
+ schemaVersion: number;
17
+ }
18
+ export type AppUpgradeAction = "create" | "replace" | "remove" | "unchanged" | "preserved" | "already-applied";
19
+ export interface AppUpgradeConflict {
20
+ path: string;
21
+ reason: string;
22
+ }
23
+ export interface AppUpgradePlan {
24
+ fromVersion: string;
25
+ toVersion: string;
26
+ schemaVersion: number;
27
+ files: {
28
+ path: string;
29
+ action: AppUpgradeAction;
30
+ }[];
31
+ conflicts: AppUpgradeConflict[];
32
+ }
33
+ export declare class AppUpgradeConflictError extends Error {
34
+ readonly conflicts: readonly AppUpgradeConflict[];
35
+ constructor(conflicts: readonly AppUpgradeConflict[]);
36
+ }
37
+ /** Read-only comparison of explicit predecessor and candidate snapshots. */
38
+ export declare function planAppUpgrade(input: AppUpgradeInput): Promise<AppUpgradePlan>;
39
+ /**
40
+ * The caller must hold an exclusive maintenance window over the application tree.
41
+ * This is not a lock against concurrent editors or hostile filesystem mutation.
42
+ * All conflicts are checked before any writes. A later I/O failure can leave a
43
+ * partial upgrade: rerun the same snapshots to recognize exact completed bytes.
44
+ * Each replacement is atomic on a local filesystem; the complete upgrade is not.
45
+ * An abrupt process termination can leave a uniquely named temporary file; it is
46
+ * never treated as a managed app file or resumed operation.
47
+ * No SQL, dependency install, version marker, deployment or user hook is executed.
48
+ */
49
+ export declare function applyAppUpgrade(input: AppUpgradeInput): Promise<{
50
+ plan: AppUpgradePlan;
51
+ applied: string[];
52
+ }>;