@tokenoftrust/storefront-runner 7.3.2 → 7.5.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 (415) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +32 -8
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +16 -2
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  17. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  18. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  19. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  20. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  21. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  22. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  23. package/apps/storefront/src/lib/activity/store.ts +9 -3
  24. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  25. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  26. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  27. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  28. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  29. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  30. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  31. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  32. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  33. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  34. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  35. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  36. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  37. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  38. package/apps/storefront/src/middleware/index.ts +7 -3
  39. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  40. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  41. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  42. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  43. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  44. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  45. package/apps/storefront/tsconfig.astro.json +11 -0
  46. package/package.json +1 -1
  47. package/packages/public-runtime/src/activity/README.md +12 -0
  48. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  49. package/packages/public-runtime/src/activity/event.ts +19 -0
  50. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  51. package/packages/public-runtime/src/catalog-files.ts +3 -2
  52. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  53. package/packages/public-runtime/src/checkout.ts +70 -0
  54. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  55. package/packages/public-runtime/src/compliance/index.ts +1 -1
  56. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  57. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  58. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  59. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  60. package/packages/public-runtime/src/product.ts +9 -1
  61. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  62. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  63. package/pnpm-lock.runner.yaml +0 -15
  64. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  65. package/scripts/tenant/validate.mjs +128 -0
  66. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  67. package/apps/storefront/drizzle.config.apps.ts +0 -13
  68. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  69. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  70. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  71. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  72. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  73. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  74. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  75. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  76. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  77. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  78. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  79. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  80. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  81. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  82. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  83. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  84. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  85. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  86. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  87. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  88. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  89. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  90. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  91. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  92. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  93. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  94. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  95. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  96. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  97. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  98. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  99. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  100. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  101. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  102. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  103. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  104. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  105. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  106. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  107. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  108. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  109. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  110. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  111. package/apps/storefront/perf/README.md +0 -64
  112. package/apps/storefront/perf/assert-budgets.ts +0 -159
  113. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  114. package/apps/storefront/playwright.config.ts +0 -23
  115. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  116. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  117. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  118. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  119. package/apps/storefront/public/js/dashboard-team.js +0 -356
  120. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  121. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  122. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  123. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  124. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  125. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  126. package/apps/storefront/src/config/storeName.ts +0 -34
  127. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  128. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  129. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  130. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  131. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  132. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  133. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  134. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  135. package/apps/storefront/src/lib/access/dashboard/agentStoreEntry.ts +0 -253
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -153
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -474
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/agentGrantAttestation.ts +0 -74
  209. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  210. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  211. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  221. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  222. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  223. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  224. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  225. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  226. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  227. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  228. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  229. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  230. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  231. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  232. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  233. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  234. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  235. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  236. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  237. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  238. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  239. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  240. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  242. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  243. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  244. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  245. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  246. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  247. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  248. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  249. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  250. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  251. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  252. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  253. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  254. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  255. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  256. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  257. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  258. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  259. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  260. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  261. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  262. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  263. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  264. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  267. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  268. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  269. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  270. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  271. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  272. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  274. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  275. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  276. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  277. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  278. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  279. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  280. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  281. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  282. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  284. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  285. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  286. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  287. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  288. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  289. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  290. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  291. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  292. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  293. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  294. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  295. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  296. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  297. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  298. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  299. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  300. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  301. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  302. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  303. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  304. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  305. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  306. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  307. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  308. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  310. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  311. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  312. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  313. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  314. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  315. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  316. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  317. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  318. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  319. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  320. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  321. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  322. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  323. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  324. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  325. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  326. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  327. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  328. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  329. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  330. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  331. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  335. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  336. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  337. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  338. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  339. package/apps/storefront/src/pages/api/contact.ts +0 -144
  340. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  341. package/apps/storefront/src/styles/admin.css +0 -1161
  342. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  343. package/apps/storefront/test/pipeline/harness.ts +0 -209
  344. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  345. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  346. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  347. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  348. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  349. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  350. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  351. package/apps/storefront/vitest.config.cts +0 -44
  352. package/apps/storefront/vitest.faults.config.cts +0 -13
  353. package/apps/storefront/vitest.workers.config.cts +0 -7
  354. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  359. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  363. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  367. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  370. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  375. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  379. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  380. package/packages/feedback/package.json +0 -35
  381. package/packages/feedback/scripts/build-player.mjs +0 -28
  382. package/packages/feedback/src/index.ts +0 -1
  383. package/packages/feedback/src/primitives/composer.ts +0 -639
  384. package/packages/feedback/src/primitives/dialog.ts +0 -263
  385. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  386. package/packages/feedback/src/primitives/index.ts +0 -10
  387. package/packages/feedback/src/primitives/launcher.ts +0 -200
  388. package/packages/feedback/src/primitives/picker.ts +0 -663
  389. package/packages/feedback/src/primitives/redaction.ts +0 -204
  390. package/packages/feedback/src/primitives/selection.ts +0 -49
  391. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  392. package/packages/feedback/src/primitives/styles.ts +0 -77
  393. package/packages/feedback/src/primitives/surface.ts +0 -124
  394. package/packages/feedback/src/primitives/target.ts +0 -293
  395. package/packages/feedback/src/tour/canonical.ts +0 -27
  396. package/packages/feedback/src/tour/index.ts +0 -3
  397. package/packages/feedback/src/tour/player/browser.ts +0 -5
  398. package/packages/feedback/src/tour/player/host.ts +0 -12
  399. package/packages/feedback/src/tour/player/index.ts +0 -205
  400. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  401. package/packages/feedback/src/tour/player/player.css +0 -130
  402. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  403. package/packages/feedback/src/tour/player/surface.ts +0 -295
  404. package/packages/feedback/src/tour/player/types.ts +0 -8
  405. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  406. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  407. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  408. package/packages/feedback/src/tour/sanitize.ts +0 -76
  409. package/packages/feedback/src/tour/schema.ts +0 -362
  410. package/packages/feedback/src/v1/guards.ts +0 -335
  411. package/packages/feedback/src/v1/index.ts +0 -3
  412. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  413. package/packages/feedback/src/v1/types.ts +0 -177
  414. package/packages/feedback/tsconfig.json +0 -9
  415. package/packages/feedback/vitest.config.cts +0 -21
@@ -103,18 +103,25 @@ async function previewKindAndRevision(
103
103
  return revision ? { previewKind: "shared", revision } : null;
104
104
  }
105
105
 
106
+ /** Authoritative preview document identity shared by annotations and tours. */
107
+ export async function resolvePreviewAnnotationDocument(
108
+ input: PreviewAnnotationDecoration,
109
+ ): Promise<{ previewKind: PreviewKind; revision: string } | null> {
110
+ if (input.cdnForwarded || input.request.method !== "GET" || input.capture ||
111
+ input.internalPublication || !input.secret) return null;
112
+ const platformSha = input.platformSha === undefined ? renderingPlatformSha() : input.platformSha;
113
+ if (!platformSha || !PLATFORM_SHA_PATTERN.test(platformSha)) return null;
114
+ const identified = await previewKindAndRevision(input);
115
+ return identified && REVISION_PATTERN.test(identified.revision) ? identified : null;
116
+ }
117
+
106
118
  export async function decoratePreviewAnnotations(
107
119
  response: Response,
108
120
  input: PreviewAnnotationDecoration,
109
121
  ): Promise<Response> {
110
- if (input.cdnForwarded) return response;
111
- if (input.request.method !== "GET" || input.capture || input.internalPublication || !input.secret) {
112
- return response;
113
- }
114
- const platformSha = input.platformSha === undefined ? renderingPlatformSha() : input.platformSha;
115
- if (!platformSha || !PLATFORM_SHA_PATTERN.test(platformSha)) return response;
116
- const identified = await previewKindAndRevision(input);
117
- if (!identified || !REVISION_PATTERN.test(identified.revision)) return response;
122
+ const identified = await resolvePreviewAnnotationDocument(input);
123
+ if (!identified || !input.secret) return response;
124
+ const platformSha = (input.platformSha === undefined ? renderingPlatformSha() : input.platformSha)!;
118
125
  let capabilityExpiresAt: number | null = null;
119
126
  if (input.previewToken) {
120
127
  const verified = await verifyPreviewToken(input.secret, input.previewToken, input.nowSeconds);
@@ -32,7 +32,7 @@ export async function getWorkerEnv(): Promise<Record<string, unknown> | null> {
32
32
  }
33
33
 
34
34
  function fromBuild(key: string): string | undefined {
35
- const meta = import.meta.env as Record<string, string | undefined>;
35
+ const meta = (import.meta.env ?? {}) as Record<string, string | undefined>;
36
36
  if (meta[key] != null) return meta[key];
37
37
  if (typeof process !== "undefined" && process.env && process.env[key] != null) {
38
38
  return process.env[key];
@@ -50,6 +50,8 @@ import { resolveAdminTenantMode } from "@/lib/access/shared/adminTenantEnvelope"
50
50
  import { gatedApiResponse, gatedHoldingResponse } from "@/lib/access/auth/gatePage";
51
51
  import { readSession, KvSessionStore, SESSION_COOKIE } from "@/lib/access/auth/session";
52
52
  import { runRenderChain } from "./renderChain.js";
53
+ import { serverActivityFanOut } from "@/lib/activity/serverFanOut";
54
+ import { runWithActivityScope } from "@/lib/activity/activityScope";
53
55
  import { resolveCandidateContentPin } from "./candidatePin.js";
54
56
  import { resolveRequestPreviewContext } from "./previewContext.js";
55
57
  import { timed } from "@/lib/observability/shared/serverTiming";
@@ -78,7 +80,19 @@ export interface ControlPlaneInput {
78
80
  internalContentGrant?: InternalContentGrant;
79
81
  }
80
82
 
81
- export async function serveControlPlane(input: ControlPlaneInput): Promise<Response> {
83
+ export function serveControlPlane(input: ControlPlaneInput): Promise<Response> {
84
+ // The control-plane branch is where a D1 handle is legitimate (ADR 0013), so the server
85
+ // emitter's analytics/timeline sink writer rides THIS request's scope (with its ExecutionContext
86
+ // for waitUntil). There is deliberately no module-level registration: the public render branch
87
+ // never enters this scope, so its emitters stay logs-only at runtime.
88
+ const cfContext = (input.context.locals as { cfContext?: { waitUntil(p: Promise<unknown>): void } } | undefined)?.cfContext;
89
+ return runWithActivityScope(
90
+ { fanOut: serverActivityFanOut, ...(cfContext ? { waitUntil: (p) => cfContext.waitUntil(p) } : {}) },
91
+ () => serveControlPlaneInScope(input),
92
+ );
93
+ }
94
+
95
+ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Response> {
82
96
  const { context, next, host, url, tenant, basePath, renderPath, cache, kv } = input;
83
97
  const { request, locals } = context;
84
98
  // A presented preview context verifies before the gate, the admin landing, the
@@ -123,9 +123,13 @@ async function agentGate(
123
123
  ): Promise<Response | null> {
124
124
  const method = context.request.method;
125
125
  if (branch !== "control-plane" && agentMayReach(method, renderPath)) return null;
126
- // Cookie-less requests (anonymous traffic, the signed sample front door's aliases)
127
- // never touch the cookie jar: the session cookie can only arrive in this header.
128
- if (!(context.request.headers.get("cookie") ?? "").includes(`${SESSION_COOKIE}=`)) return null;
126
+ // Cookie-less requests (anonymous traffic, the signed sample front door's aliases) never
127
+ // touch the cookie jar. This is Astro's own emptiness test: its jar parses nothing when
128
+ // the header is empty. Agent-ness itself is decided from the jar every handler reads,
129
+ // never a substring of the raw header: Astro's parser trims cookie names, so
130
+ // `tot_session =<sid>` or `tot_session\t=<sid>` reaches a handler as the session while
131
+ // missing a test for `tot_session=`.
132
+ if (!context.request.headers.get("cookie")) return null;
129
133
  const sid = context.cookies.get(SESSION_COOKIE)?.value ?? null;
130
134
  if (!sid) return null;
131
135
  const sessionKv = await readKv("SESSION");
@@ -333,24 +333,30 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
333
333
  if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
334
334
  return response;
335
335
  }
336
- // The owning space's content-declared redirects answer before anything renders: a same-origin
337
- // target keeps the path-routing prefix and goes through the shared return-path sanitizer, so no
338
- // request query (a preview capability, a pin token) reaches the Location; an off-site target (the
339
- // root space only) is sent as declared. A pinned render (staged/candidate revision) redirects
340
- // inside the revision it reviews.
341
- const declaredRedirectHeaders = (location: string): HeadersInit => {
342
- if (!location.startsWith("/")) return { location };
336
+ // The owning space's content-declared redirects: a same-origin target keeps the path-routing
337
+ // prefix and goes through the shared return-path sanitizer, so no request query (a preview
338
+ // capability, a pin token) reaches the Location; an off-site target (the root space only) is sent
339
+ // as declared. A pinned render (staged/candidate revision) redirects inside the revision it
340
+ // reviews. A `<dir>/*` rule answers before anything renders. An exact entry yields to a route the
341
+ // release generates at its own path: the page renders first, and the redirect answers only when
342
+ // nothing renders there (the static planes drop such an entry when the release is composed).
343
+ const declaredRedirect = (location: string): Response => {
343
344
  const prefix = candidatePin ? candidatePin.basePath : basePath;
344
- return { location: `${url.origin}${safeReturnPathname(`${prefix}${location}`)}` };
345
+ const response = new Response(null, {
346
+ status: 308,
347
+ headers: {
348
+ location: location.startsWith("/") ? `${url.origin}${safeReturnPathname(`${prefix}${location}`)}` : location,
349
+ },
350
+ });
351
+ applySecurityHeaders(response.headers);
352
+ if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
353
+ return response;
345
354
  };
355
+ let redirectUnlessRendered: string | null = null;
346
356
  if (publicationSource.status === "selected") {
347
- const location = publicationContentRedirectLocationV1(publicationSource.artifact, input.publicationRequestPath);
348
- if (location) {
349
- const response = new Response(null, { status: 308, headers: declaredRedirectHeaders(location) });
350
- applySecurityHeaders(response.headers);
351
- if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
352
- return response;
353
- }
357
+ const match = publicationContentRedirectLocationV1(publicationSource.artifact, input.publicationRequestPath);
358
+ if (match && !match.exact) return declaredRedirect(match.location);
359
+ redirectUnlessRendered = match?.location ?? null;
354
360
  }
355
361
 
356
362
  // The tenant as it renders in THIS environment: its record with the declared
@@ -419,12 +425,9 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
419
425
  // Ordinary host, path-prefixed and pinned previews read the same declarations as their pages.
420
426
  // Public CDN redirects remain precomputed in the publication artifact.
421
427
  if (publicationSource.status === "legacy-root") {
422
- const location = await contentRedirectLocation(locals.content, renderPath);
423
- if (location) {
424
- const response = new Response(null, { status: 308, headers: declaredRedirectHeaders(location) });
425
- applySecurityHeaders(response.headers);
426
- return response;
427
- }
428
+ const match = await contentRedirectLocation(locals.content, renderPath);
429
+ if (match && !match.exact) return declaredRedirect(match.location);
430
+ redirectUnlessRendered = match?.location ?? null;
428
431
  }
429
432
  const publicationTimestamp = publicationSource.status === "selected"
430
433
  ? publicationSource.publicationTimestamp
@@ -484,7 +487,9 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
484
487
  }
485
488
  : {}),
486
489
  })) : null;
487
- if (bundled) return bundled;
490
+ if (bundled) {
491
+ return redirectUnlessRendered !== null && bundled.status === 404 ? declaredRedirect(redirectUnlessRendered) : bundled;
492
+ }
488
493
 
489
494
  // ---- Tenant-local integration materialization (ext-kernel-09) --------------
490
495
  // Resolve a tenant's OWN declared, exact-version integrations into the effective
@@ -856,6 +861,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
856
861
  let response = await timed(timing, "render", () => rewriteTarget !== undefined
857
862
  ? next(rewriteTarget)
858
863
  : next());
864
+ if (redirectUnlessRendered !== null && response.status === 404) return declaredRedirect(redirectUnlessRendered);
859
865
 
860
866
  // A nested pass of this middleware (an in-process `rewrite()`) already decorated
861
867
  // and nonce-stamped the response. Serve it verbatim: decorating again would inject
@@ -875,19 +881,22 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
875
881
  // It polls /api/preview/version and reloads when this tenant's cache-version
876
882
  // bumps on publish/reconcile. Injection happens before the CSP header is set so
877
883
  // the script's per-request nonce (cspNonce) matches the enforced policy.
878
- response = await maybeInjectPreviewReload(response, {
884
+ // Every post-render stage below is timed by name: each may read the whole body or wait on KV/R2,
885
+ // and untimed they showed up only as an unexplained gap between `render` and `total`.
886
+ response = await timed(timing, "decorate", () => maybeInjectPreviewReload(response, {
879
887
  env: customization.env,
880
888
  tenantId: tenant.tenant_id,
881
889
  basePath,
882
890
  nonce: cspNonce,
883
891
  renderPath,
884
- });
892
+ }));
885
893
 
886
894
  // Preview annotations: an authorized interactive preview (shared preview token, or a
887
895
  // pinned candidate) carries the Feedback bootstrap and a signed rendered-context receipt.
888
896
  // Capture, materialization, internal publication and live renders never do; the
889
897
  // decorator marks what it decorates `private, no-store`.
890
- response = await decoratePreviewAnnotations(response, {
898
+ let sharedRevision: Promise<string | null> | undefined;
899
+ const previewDecoration = {
891
900
  request,
892
901
  customizationEnv: customization.env,
893
902
  previewToken,
@@ -904,15 +913,17 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
904
913
  capture: isPublicationCapture(request.headers, await readEnv(MATERIALIZE_MODE_BINDING)),
905
914
  cdnForwarded: locals.cdnForwarded === true,
906
915
  internalPublication: isInternalPublication,
907
- sharedRevision: async () => publicationSource.status === "selected"
908
- ? publicationSource.cacheScope.versionId
909
- : (await resolveServableChannelVersion(kvGet, tenant.tenant_id, "preview")).versionId,
910
- });
916
+ // Annotations and tours both identify the document; one KV read serves both.
917
+ sharedRevision: () => (sharedRevision ??= publicationSource.status === "selected"
918
+ ? Promise.resolve(publicationSource.cacheScope.versionId)
919
+ : resolveServableChannelVersion(kvGet, tenant.tenant_id, "preview").then((v) => v.versionId)),
920
+ } satisfies Parameters<typeof decoratePreviewAnnotations>[1];
921
+ response = await timed(timing, "decorate", () => decoratePreviewAnnotations(response, previewDecoration));
911
922
 
912
923
  // Distinct tenant theme sheets are render-blocking `/tenants/` fetches. Inline
913
924
  // them into this preview document. Publication capture keeps the source links
914
925
  // so the asset pipeline concatenates the same run for both CDNs.
915
- response = await inlinePreviewTenantThemes(response, {
926
+ response = await timed(timing, "themes", () => inlinePreviewTenantThemes(response, {
916
927
  request,
917
928
  customizationEnv: customization.env,
918
929
  tenant,
@@ -922,7 +933,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
922
933
  previewSecret,
923
934
  nowSeconds,
924
935
  pinnedVersionId: cookieRevision,
925
- });
936
+ }));
926
937
 
927
938
  // Baseline security headers on every response — set before the page-cache
928
939
  // store below so cached copies carry them too.
@@ -968,7 +979,8 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
968
979
  embedsForScan.length > 0 &&
969
980
  (response.headers.get("content-type") ?? "").includes("text/html")
970
981
  ) {
971
- embedCsp = embedCspAdditions(embedsForScan, await response.clone().text());
982
+ const scanned = response;
983
+ embedCsp = embedCspAdditions(embedsForScan, await timed(timing, "embed-scan", () => scanned.clone().text()));
972
984
  }
973
985
  const cspOptions = {
974
986
  nonce: cspNonce,
@@ -1057,7 +1069,8 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
1057
1069
  // Stamp a fresh per-response nonce into this cold response's body + CSP header
1058
1070
  // (the warm-hit path above stamps its own). Both paths therefore serve a fresh,
1059
1071
  // matching nonce/CSP pair, and no nonce is reused across responses (ADR 0018).
1060
- return await stampResponseNonce(response, freshNonce());
1072
+ const stamped = response;
1073
+ return await timed(timing, "nonce", () => stampResponseNonce(stamped, freshNonce()));
1061
1074
  }
1062
1075
 
1063
1076
  /**
@@ -0,0 +1,12 @@
1
+ /** Worker-served confirmation of a reviewed cart proposal into the signed cart. */
2
+ import type { APIContext } from "astro";
3
+ import { cartProposalConfirm } from "@/lib/checkout/proposal/proposalRoutes";
4
+ import { pageUrlForm } from "@/lib/content/seo/urlForm";
5
+ import { withBase } from "@/lib/publication/shared/basePath";
6
+
7
+ export const prerender = false;
8
+
9
+ const productPagePath = (context: APIContext, handle: string): string =>
10
+ withBase(context.locals.basePath ?? "", pageUrlForm(`/products/${handle}`, context.locals.tenant.seo));
11
+
12
+ export const POST = (context: APIContext): Promise<Response> => cartProposalConfirm(context, { productPagePath });
@@ -0,0 +1,26 @@
1
+ /** Worker-served review of an assistant's cart proposal. Reads the catalog; changes no cart. */
2
+ import type { APIContext } from "astro";
3
+ import type { CartProposalLine } from "@tot/public-runtime";
4
+ import { cartProposalForm, cartProposalReview, type ProposalCompliance } from "@/lib/checkout/proposal/proposalRoutes";
5
+ import { sharedStorePolicy } from "@/lib/checkout/commerce/sharedStoreAdmission";
6
+ import { evaluatePreflight } from "../compliance/preflight.js";
7
+
8
+ export const prerender = false;
9
+
10
+ /** The compliance status of the reviewed lines. It carries no verification, shopper or destination. */
11
+ async function preflight(context: APIContext, lines: readonly CartProposalLine[]): Promise<ProposalCompliance> {
12
+ const { tenant, commerce, customizationEnv } = context.locals;
13
+ const policy = await sharedStorePolicy(tenant, commerce, customizationEnv);
14
+ const { decision } = await evaluatePreflight(
15
+ context,
16
+ { lines: lines.map((line) => ({ handle: line.productHandle, variantId: line.variantId, sku: line.sku, quantity: line.quantity })) },
17
+ policy ? { verification: policy.verification, rules: policy.rules } : {},
18
+ );
19
+ return {
20
+ status: decision.status,
21
+ blocks: decision.blocks.map((block) => ({ code: block.code, message: block.message })),
22
+ };
23
+ }
24
+
25
+ export const GET = (context: APIContext): Response => cartProposalForm(context);
26
+ export const POST = (context: APIContext): Promise<Response> => cartProposalReview(context, { preflight });
@@ -4,7 +4,7 @@ import { createLocalJWKSet, decodeProtectedHeader, jwtVerify, type JSONWebKeySet
4
4
  import {
5
5
  commerceTenantId, isRegulated, totalsMatch, shippingMinorFor, isContentVersionId, catalogPinDigestFinding, cartLineKey,
6
6
  EXCISE_REASONS, type CallerToken, type CatalogProduct, type CatalogVariant, type CommerceEvidence, type CommerceEvidenceProvenance,
7
- type CommerceProviderCartSnapshot, type ExciseCarrier, type FinalCartBinding, type TenantConfig,
7
+ type CommerceProviderCartSnapshot, type ExciseCarrier, type ExciseEvidenceReason, type FinalCartBinding, type TenantConfig,
8
8
  } from "@tot/public-runtime";
9
9
  import { skuFromToken } from "@tot/public-runtime/sku";
10
10
  import { fromD1 } from "@/lib/catalog/d1/catalog.js";
@@ -35,7 +35,13 @@ const VERIFICATION_REF = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,199}$/;
35
35
  function json(body: unknown, status = 200): Response {
36
36
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
37
37
  }
38
- function deny(finding: string, status = 409, owner?: string): Response { return json({ ok: false, finding, message: refusalSentence(finding), ...(owner ? { owner } : {}) }, status); }
38
+ /**
39
+ * A refusal: the finding, its shopper sentence, and — on an excise refusal — `exciseReason`, the
40
+ * closed reason the excise was unavailable, so the caller words the shopper's message precisely.
41
+ */
42
+ function deny(finding: string, status = 409, owner?: string, exciseReason?: string): Response {
43
+ return json({ ok: false, finding, message: refusalSentence(finding), ...(owner ? { owner } : {}), ...(exciseReason ? { exciseReason } : {}) }, status);
44
+ }
39
45
  /**
40
46
  * Which check refused, and on which cart line (its index in the presented snapshot). Logged on
41
47
  * the decision line only: closed check names and an index, never a SKU, price or cart value.
@@ -107,8 +113,9 @@ function readSnapshot(value: unknown): FinalCartWire | null {
107
113
  Object.keys(line).some(k => !["sku", "quantity", "unitMinor"].includes(k)))) return null;
108
114
  const t = v.totals as Record<string, unknown> | undefined;
109
115
  const totalKeys = ["subtotalMinor", "shippingMinor", "taxMinor", "totalMinor"];
116
+ const optionalTotalKeys = ["exciseMinor", "discountMinor"];
110
117
  if (!t || typeof t !== "object" || Array.isArray(t) ||
111
- Object.keys(t).some(k => !totalKeys.includes(k) && k !== "exciseMinor") ||
118
+ Object.keys(t).some(k => !totalKeys.includes(k) && !optionalTotalKeys.includes(k)) ||
112
119
  totalKeys.some(k => !(k in t)) ||
113
120
  Object.keys(t).some(k => !Number.isSafeInteger(t[k]) || Number(t[k]) < 0)) return null;
114
121
  const d = v.destination as Record<string, unknown> | undefined;
@@ -170,11 +177,19 @@ async function evaluateSeam(context: APIContext, snapshot: CommerceProviderCartS
170
177
  const blocks = decision.blocks;
171
178
  if (blocks.length === 0) return { status: "clear", verified };
172
179
  const flavors = [...new Set(blocks.flatMap(block => block.code === "flavored_prohibited" ? block.flavors ?? [] : []))];
180
+ const hasRuleBlock = blocks.some(
181
+ block =>
182
+ block.code === "flavored_prohibited" ||
183
+ block.code === "cooling_agent_prohibited" ||
184
+ block.code === "region_prohibited" ||
185
+ block.code === "purchase_limit_exceeded",
186
+ );
173
187
  const titleOf = (sku: string) => products.find(p => p.variants.some(v => v.sku === sku))?.title;
174
188
  const seen = new Set<string>();
175
189
  const lines: RefusedLine[] = [];
176
190
  for (const block of blocks) {
177
191
  if (block.failedClosed === true || typeof block.message !== "string" || !block.message) continue;
192
+ if (hasRuleBlock && block.code.startsWith("verification_")) continue;
178
193
  const key = `${block.code}\n${block.sku ?? ""}\n${block.message}`;
179
194
  if (seen.has(key)) continue;
180
195
  seen.add(key);
@@ -217,12 +232,18 @@ export async function POST(context: APIContext): Promise<Response> {
217
232
  let threw = false;
218
233
  try { response = await authorize(context); } catch { threw = true; response = deny("authority-error", 500); }
219
234
  let finding = "approved";
235
+ let exciseReason: string | undefined;
220
236
  if (response.status !== 200 || threw) {
221
- try { finding = String((await response.clone().json() as { finding?: unknown }).finding ?? "unreadable").slice(0, 80); } catch { finding = "unreadable"; }
237
+ try {
238
+ const body = await response.clone().json() as { finding?: unknown; exciseReason?: unknown };
239
+ finding = String(body.finding ?? "unreadable").slice(0, 80);
240
+ if (typeof body.exciseReason === "string") exciseReason = body.exciseReason.slice(0, 80);
241
+ } catch { finding = "unreadable"; }
222
242
  }
223
243
  const detail = refusalDetails.get(response);
224
244
  try {
225
245
  console.info("commerce-final-cart-decision", JSON.stringify({ correlationId, ok: response.status === 200, finding,
246
+ ...(exciseReason ? { exciseReason } : {}),
226
247
  ...(detail ? { check: detail.check, ...(detail.line === undefined ? {} : { line: detail.line }) } : {}),
227
248
  status: response.status, threw, ms: Date.now() - started }));
228
249
  } catch { /* Diagnostic delivery cannot alter the decision. */ }
@@ -372,6 +393,7 @@ async function authorize(context: APIContext): Promise<Response> {
372
393
  const presented: FinalCartBinding = { tenantId: snapshot.tenantId, stage: snapshot.stage, currency: snapshot.currency, lines: snapshot.lines,
373
394
  destinationDigest: snapshot.destinationDigest, verificationExpiresAt: expiresAt, taxExpiresAt: expiresAt };
374
395
  const seamView = await seam(authorityContext, snapshot, selected, policy);
396
+ let taxReason: ExciseEvidenceReason | undefined;
375
397
  if (policy.tax === "required") {
376
398
  const hasProducer = checkoutStoreHasExciseProducer(await resolveTenantCommerce(tenant));
377
399
  const taxResolution = await resolveTaxEvidence({
@@ -385,6 +407,7 @@ async function authorize(context: APIContext): Promise<Response> {
385
407
  });
386
408
  evidence.tax = taxResolution.evidenceState;
387
409
  provenance.tax = taxResolution.provenance;
410
+ taxReason = taxResolution.reason;
388
411
  }
389
412
  if (policy.verification === "required" && seamView.verified) {
390
413
  evidence.verification = "fresh";
@@ -394,14 +417,14 @@ async function authorize(context: APIContext): Promise<Response> {
394
417
  const decision = await evaluateFinalCart({ now, routedTenantId: commerceTenantId(tenant), quoted: presented, presented, evidence,
395
418
  seam: seamView, catalogAvailable: true, browserConfirmed: false, token,
396
419
  trustedIssuers: issuers, expectedAudience: audience, activeKids, stockTracked, authorities,
397
- totals: snapshot.totals, excise: snapshot.excise, exciseRequired });
420
+ totals: snapshot.totals, excise: snapshot.excise, exciseRequired, ...(taxReason ? { taxReason } : {}) });
398
421
  if (!decision.ok) {
399
422
  if (decision.finding.startsWith("verification-refused") && (seamView.flavors || seamView.lines)) {
400
423
  return json({ ok: false, finding: decision.finding, message: refusalSentence(decision.finding),
401
424
  ...(decision.finding === "verification-refused:flavored_prohibited" && seamView.flavors ? { flavors: seamView.flavors } : {}),
402
425
  ...(seamView.lines ? { lines: seamView.lines } : {}) }, 409);
403
426
  }
404
- return deny(decision.finding, 409, decision.owner);
427
+ return deny(decision.finding, 409, decision.owner, decision.exciseReason);
405
428
  }
406
429
  const authorizationId = existing?.authorizationId ?? `a${crypto.randomUUID()}`;
407
430
  // Retries of the same verified provider cart share one reservation, including concurrent callbacks.
@@ -291,7 +291,31 @@ export async function POST(context: APIContext): Promise<Response> {
291
291
  // at all, so a static page never carries a decision frozen at build time.
292
292
  const policy = await sharedStorePolicy(context.locals.tenant, context.locals.commerce, context.locals.customizationEnv);
293
293
  const gate = complianceGateRequiredFor(policy) ? "required" : "not-required";
294
- return json({ ...(await evaluatePreflight(context, body, policy ? { verification: policy.verification, rules: policy.rules } : {})), gate });
294
+ const result = await evaluatePreflight(context, body, policy ? { verification: policy.verification, rules: policy.rules } : {});
295
+ logPreflightDecision(result.decision);
296
+ return json({ ...result, gate });
297
+ }
298
+
299
+ /**
300
+ * One `compliance-preflight-decision` line per refused preflight: each block's code, the
301
+ * declaration that refused it (`rule`), region and SKU. Closed values only — no shopper data.
302
+ */
303
+ function logPreflightDecision(decision: CartComplianceDecision): void {
304
+ if (decision.status === "clear") return;
305
+ try {
306
+ console.info("compliance-preflight-decision", JSON.stringify({
307
+ status: decision.status,
308
+ failedClosed: decision.failedClosed,
309
+ blocks: decision.blocks.map((b) => ({
310
+ code: b.code,
311
+ ...(b.rule ? { rule: b.rule } : {}),
312
+ ...(b.region ? { region: b.region } : {}),
313
+ ...(b.sku ? { sku: b.sku } : {}),
314
+ ...(b.allowedRegions ? { allowedRegions: b.allowedRegions } : {}),
315
+ ...(b.rejectedTokens ? { rejectedTokens: b.rejectedTokens } : {}),
316
+ })),
317
+ }));
318
+ } catch { /* Diagnostic delivery cannot alter the decision. */ }
295
319
  }
296
320
 
297
321
  export interface PreflightOptions {
@@ -13,7 +13,6 @@ import ProductCard from "@/components/catalog/storefront/ProductCard.astro";
13
13
  import Section from "@/components/content/storefront/Section.astro";
14
14
  import ImageGallery, { publicGalleryImages } from "@/components/catalog/storefront/islands/ImageGallery.tsx";
15
15
  import VariantSelector, { publicSelectorVariants } from "@/components/catalog/storefront/islands/VariantSelector.tsx";
16
- import CheckoutComplianceGate from "@/components/compliance/storefront/islands/CheckoutComplianceGate.tsx";
17
16
  import RecentlyViewed from "@/components/catalog/storefront/islands/RecentlyViewed.tsx";
18
17
  import NicotineWarning from "@/components/compliance/storefront/compliance/NicotineWarning.astro";
19
18
  import Prop65Warning from "@/components/compliance/storefront/compliance/Prop65Warning.astro";
@@ -352,7 +351,7 @@ const structuredData = {
352
351
 
353
352
  <div class="container-prose grid gap-10 py-8 md:grid-cols-2 lg:gap-16">
354
353
  {/* Gallery (island) */}
355
- <div>
354
+ <div class="min-w-0">
356
355
  <ImageGallery
357
356
  client:idle
358
357
  images={publicGalleryImages(product.images)}
@@ -362,7 +361,7 @@ const structuredData = {
362
361
  </div>
363
362
 
364
363
  {/* Buy column */}
365
- <div class="md:pt-2">
364
+ <div class="min-w-0 md:pt-2">
366
365
  <div class="flex flex-wrap items-center gap-2">
367
366
  {Astro.locals.features.productBadges && onSale && <Badge variant="sale" label="Sale" />}
368
367
  {Astro.locals.features.productBadges && !onSale && isNew(product) && <Badge variant="new" label="New" />}
@@ -441,18 +440,6 @@ const structuredData = {
441
440
  publicAvailabilityPath(Astro.locals.customizationEnv === "live" ? "publication" : "preview"),
442
441
  )}
443
442
  />
444
- {/* Regulated-tenant checkout ENFORCEMENT gate. Intercepts the
445
- managed-cart handoff to clear age + ship-to compliance server-side
446
- before the external checkout. Mounts when a store is wired and the
447
- tenant is regulated; whether the store's policy asks for the dialog
448
- is answered by preflight at click time, never frozen into this page. */}
449
- {checkoutCart && !sampleHandoff && isRegulatedTenant(tenant) && compliance?.minAge && (
450
- <CheckoutComplianceGate
451
- client:load
452
- preflightUrl={withBase(apiBasePath, "/api/compliance/preflight")}
453
- minAge={compliance.minAge}
454
- />
455
- )}
456
443
  <button
457
444
  type="button"
458
445
  class="wishlist-toggle group mt-3 inline-flex w-full items-center justify-center gap-2 rounded-[var(--radius-md)] border border-[var(--color-border)] py-2.5 font-display text-sm font-medium transition-colors hover:border-[var(--color-sale)] hover:text-[var(--color-sale)] aria-pressed:border-[var(--color-sale)] aria-pressed:text-[var(--color-sale)]"
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "dist",
5
+ "node_modules",
6
+ "**/*.test.ts",
7
+ "**/*.test.tsx",
8
+ "**/*.spec.ts",
9
+ "**/*.spec.tsx"
10
+ ]
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.3.2",
3
+ "version": "7.5.0",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -48,6 +48,18 @@ const { event, report } = createActivityEvent({
48
48
  `v`/`id`/`at` and runs the raw payload through the redaction contract, so you
49
49
  **cannot** produce an event whose payload skipped redaction.
50
50
 
51
+ ### Sponsored agents: `actor.delegation`
52
+
53
+ `actor.kind` `"agent"` means automation with no human viewer. A SPONSORED agent (one acting
54
+ under a tot-mcp agent-sponsorship grant) is also `"agent"`, and additionally carries
55
+ `actor.delegation = { agentId, sponsorHash }`: the `agent:<id>` subject and the lowercase hex
56
+ sha256 of its sponsor's opaque broker subject. It is a field of its own so the two meanings never
57
+ mix. `createActivityEvent()` rebuilds it through `sanitizeDelegation()`: a sponsor that is not a
58
+ sha256 digest (an email, a raw subject) or an agent id that is not an opaque `agent:<id>` handle
59
+ drops the delegation and sets `report.delegationDropped`; the event is still emitted. Only the
60
+ in-process UI emitter sets it (from a verified agent session); ingest never carries a
61
+ client-supplied one through. There is no CLI mirror: the CLI never emits it.
62
+
51
63
  ## The action catalog
52
64
 
53
65
  `action` is never a free string — it is a key of `ACTION_CATALOG`. Each entry
@@ -345,6 +345,13 @@ export const ACTION_CATALOG = {
345
345
  argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
346
346
  desc: "A store's excise setting was saved to a version.",
347
347
  },
348
+ "content.checkout_config.saved": {
349
+ // A store's checkout & payment-provider configuration (Settings → Checkout configuration)
350
+ // was saved to the store's operational selection.
351
+ actors: ["merchant", "admin"], source: "server", sinks: LIFECYCLE,
352
+ argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
353
+ desc: "A store's checkout configuration was saved to a version.",
354
+ },
348
355
  "content.operational_setting.published": {
349
356
  // An operational setting's saved draft (checkout requirements or styling) was made the live
350
357
  // store's value (/api/preview/settings-live). `scope` names the setting.
@@ -56,6 +56,20 @@ export type ActivityStatus = "invoked" | "succeeded" | "failed" | "refused";
56
56
  * `timeline` = low-volume/queryable ops UI. */
57
57
  export type ActivitySink = "logs" | "analytics" | "timeline";
58
58
 
59
+ /**
60
+ * WHO a SPONSORED agent acts for (sponsored-agent identity, ADR capabilities-management §11).
61
+ * A field of its own on {@link ActivityActor}: the `"agent"` KIND already means "no
62
+ * viewer" (headless Bearer/CLI automation) and stays exactly that. Both members are
63
+ * core-zone opaque handles:
64
+ * • `agentId` — the agent subject, `agent:<id>` (an opaque grant handle, never a person);
65
+ * • `sponsorHash` — lowercase hex sha256 of the sponsor's opaque broker subject. Never the
66
+ * subject, never an email; `createActivityEvent` drops anything else.
67
+ */
68
+ export interface ActivityDelegation {
69
+ agentId: string;
70
+ sponsorHash: string;
71
+ }
72
+
59
73
  export interface ActivityActor {
60
74
  kind: ActorKind;
61
75
  /**
@@ -72,6 +86,11 @@ export interface ActivityActor {
72
86
  * dev across CLI + UI). Still core, still MUST be non-reversible / non-PII.
73
87
  */
74
88
  ref?: string;
89
+ /**
90
+ * Present ONLY on an event from a sponsored-agent session: which agent acted and, as a
91
+ * hash, for whom. Absent on every other actor, including a plain `"agent"` (no-viewer).
92
+ */
93
+ delegation?: ActivityDelegation;
75
94
  }
76
95
 
77
96
  export interface ActivityScope {
@@ -36,6 +36,7 @@ import {
36
36
  newEventId,
37
37
  type ActivityEvent,
38
38
  type ActivityActor,
39
+ type ActivityDelegation,
39
40
  type ActivityScope,
40
41
  type ActivityOutcome,
41
42
  type ActivityPayload,
@@ -97,6 +98,11 @@ export interface RedactionReport {
97
98
  hits: RedactionFieldHit[];
98
99
  /** True if any value-canary fired — the signal an alert rule watches. */
99
100
  canaryTripped: boolean;
101
+ /**
102
+ * True when the caller supplied an `actor.delegation` that failed {@link sanitizeDelegation}
103
+ * and was therefore left off the event (the event is still emitted, unattributed).
104
+ */
105
+ delegationDropped?: boolean;
100
106
  }
101
107
 
102
108
  function isPrimitive(v: unknown): v is string | number | boolean {
@@ -146,6 +152,25 @@ export function scanCoreIdentifier(value: string): string | undefined {
146
152
  return undefined;
147
153
  }
148
154
 
155
+ const DELEGATION_AGENT_ID = /^agent:[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
156
+ const DELEGATION_SPONSOR_HASH = /^[0-9a-f]{64}$/;
157
+
158
+ /**
159
+ * Validate a sponsored-agent delegation (`actor.delegation`) for the CORE zone. Pure,
160
+ * deny-by-default: returns a fresh object holding ONLY `agentId` and `sponsorHash`, or
161
+ * undefined when either is not the exact opaque shape. The sponsor must be a sha256 hex
162
+ * digest (so an email or a raw broker subject can never ride in the core zone) and the
163
+ * agent id an `agent:<id>` handle that trips no structured secret/PII canary.
164
+ */
165
+ export function sanitizeDelegation(raw: unknown): ActivityDelegation | undefined {
166
+ if (!raw || typeof raw !== "object") return undefined;
167
+ const { agentId, sponsorHash } = raw as Record<string, unknown>;
168
+ if (typeof agentId !== "string" || !DELEGATION_AGENT_ID.test(agentId)) return undefined;
169
+ if (scanCoreIdentifier(agentId)) return undefined;
170
+ if (typeof sponsorHash !== "string" || !DELEGATION_SPONSOR_HASH.test(sponsorHash)) return undefined;
171
+ return { agentId, sponsorHash };
172
+ }
173
+
149
174
  function redactLane(
150
175
  lane: "args" | "rendered",
151
176
  raw: Record<string, unknown> | undefined,
@@ -247,12 +272,16 @@ export function createActivityEvent(input: CreateActivityEventInput): {
247
272
  } {
248
273
  const spec = getActionSpec(input.action);
249
274
  if (!spec) throw new Error(`activity: unknown action "${input.action}" (not in catalog)`);
250
- const { payload, report } = redactPayload(input.action, input.payload);
275
+ const { payload, report: payloadReport } = redactPayload(input.action, input.payload);
276
+ // The delegation is rebuilt from a validated copy; whatever else the caller put in it is gone.
277
+ const { delegation: rawDelegation, ...actorRest } = input.actor;
278
+ const delegation = rawDelegation === undefined ? undefined : sanitizeDelegation(rawDelegation);
279
+ const report: RedactionReport = { ...payloadReport, delegationDropped: rawDelegation !== undefined && !delegation };
251
280
  const event: ActivityEvent = {
252
281
  v: ACTIVITY_SCHEMA_VERSION,
253
282
  id: input.id ?? newEventId(),
254
283
  at: input.at ?? new Date().toISOString(),
255
- actor: input.actor,
284
+ actor: delegation ? { ...actorRest, delegation } : actorRest,
256
285
  action: input.action,
257
286
  source: input.source,
258
287
  scope: input.scope ?? {},