@knpkv/control-center 0.4.0 → 0.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 (220) hide show
  1. package/README.md +18 -8
  2. package/dist/client/.vite/manifest.json +214 -182
  3. package/dist/client/assets/{ActiveWorkPage-Dd1mxPrq.js → ActiveWorkPage-g2-Jyavo.js} +2 -2
  4. package/dist/client/assets/{ActiveWorkPage-Dd1mxPrq.js.map → ActiveWorkPage-g2-Jyavo.js.map} +1 -1
  5. package/dist/client/assets/AgentPage-B6GQdZAs.css +1 -0
  6. package/dist/client/assets/AgentPage-DmVsEe13.js +6 -0
  7. package/dist/client/assets/AgentPage-DmVsEe13.js.map +1 -0
  8. package/dist/client/assets/AtlassianOAuthCallbackPage-C8u9ItMj.js +2 -0
  9. package/dist/client/assets/{AtlassianOAuthCallbackPage-BPoF6oKf.js.map → AtlassianOAuthCallbackPage-C8u9ItMj.js.map} +1 -1
  10. package/dist/client/assets/{AuthorizedSharePage-jjqu6W_f.js → AuthorizedSharePage-CVBJ1NTm.js} +2 -2
  11. package/dist/client/assets/{AuthorizedSharePage-jjqu6W_f.js.map → AuthorizedSharePage-CVBJ1NTm.js.map} +1 -1
  12. package/dist/client/assets/BrowserCrypto-3BoTVFdl.js +2 -0
  13. package/dist/client/assets/{BrowserCrypto-BMbjhcvP.js.map → BrowserCrypto-3BoTVFdl.js.map} +1 -1
  14. package/dist/client/assets/BrowserSessionHydrator-CpZnNm4X.js +2 -0
  15. package/dist/client/assets/{BrowserSessionHydrator-BC1ymLkL.js.map → BrowserSessionHydrator-CpZnNm4X.js.map} +1 -1
  16. package/dist/client/assets/{CommandSearch-WwAVDrD9.js → CommandSearch-DUeRRbV2.js} +2 -2
  17. package/dist/client/assets/{CommandSearch-WwAVDrD9.js.map → CommandSearch-DUeRRbV2.js.map} +1 -1
  18. package/dist/client/assets/{ItemsPage-CKK_KkJ2.js → ItemsPage-BF2ZkSzh.js} +2 -2
  19. package/dist/client/assets/{ItemsPage-CKK_KkJ2.js.map → ItemsPage-BF2ZkSzh.js.map} +1 -1
  20. package/dist/client/assets/{PairPage-DA6cmyqF.js → PairPage-CkaZltHd.js} +2 -2
  21. package/dist/client/assets/{PairPage-DA6cmyqF.js.map → PairPage-CkaZltHd.js.map} +1 -1
  22. package/dist/client/assets/PortfolioOverview-CEUHJmGC.js +2 -0
  23. package/dist/client/assets/{PortfolioOverview-CEI4gpXi.js.map → PortfolioOverview-CEUHJmGC.js.map} +1 -1
  24. package/dist/client/assets/{PullRequestReviewPanel-D7AKnwL-.js → PullRequestReviewPanel-D1IpvHe2.js} +3 -3
  25. package/dist/client/assets/{PullRequestReviewPanel-D7AKnwL-.js.map → PullRequestReviewPanel-D1IpvHe2.js.map} +1 -1
  26. package/dist/client/assets/{ReleaseRoute-CbPW3qUT.js → ReleaseRoute-BuQybrsg.js} +2 -2
  27. package/dist/client/assets/{ReleaseRoute-CbPW3qUT.js.map → ReleaseRoute-BuQybrsg.js.map} +1 -1
  28. package/dist/client/assets/ReleaseWorkset-BclY0Nvj.js +2 -0
  29. package/dist/client/assets/ReleaseWorkset-BclY0Nvj.js.map +1 -0
  30. package/dist/client/assets/ServicesPage-hw5Ee69-.js +2 -0
  31. package/dist/client/assets/{ServicesPage-_B89DAvG.js.map → ServicesPage-hw5Ee69-.js.map} +1 -1
  32. package/dist/client/assets/{TimelinePage-DvpgD8AY.js → TimelinePage-Cj3V98uI.js} +2 -2
  33. package/dist/client/assets/{TimelinePage-DvpgD8AY.js.map → TimelinePage-Cj3V98uI.js.map} +1 -1
  34. package/dist/client/assets/{WorkspaceEntityLink-DPj6MKI2.js → WorkspaceEntityLink-C_rc8lxi.js} +2 -2
  35. package/dist/client/assets/{WorkspaceEntityLink-DPj6MKI2.js.map → WorkspaceEntityLink-C_rc8lxi.js.map} +1 -1
  36. package/dist/client/assets/WorkspaceEntityRoute-DLLT6fY0.css +1 -0
  37. package/dist/client/assets/WorkspaceEntityRoute-kbnrQ_lY.js +14 -0
  38. package/dist/client/assets/WorkspaceEntityRoute-kbnrQ_lY.js.map +1 -0
  39. package/dist/client/assets/WorkspaceHomeLink-DeYYLEsH.js +2 -0
  40. package/dist/client/assets/{WorkspaceHomeLink-CkJfzO25.js.map → WorkspaceHomeLink-DeYYLEsH.js.map} +1 -1
  41. package/dist/client/assets/WorkspacePullRequestDetails-CizqydjN.js +3 -0
  42. package/dist/client/assets/{WorkspacePullRequestDetails-HwDgp12e.js.map → WorkspacePullRequestDetails-CizqydjN.js.map} +1 -1
  43. package/dist/client/assets/{WorkspaceReleaseLayout-CGHi8eoo.js → WorkspaceReleaseLayout-CXAQUhkh.js} +2 -2
  44. package/dist/client/assets/{WorkspaceReleaseLayout-CGHi8eoo.js.map → WorkspaceReleaseLayout-CXAQUhkh.js.map} +1 -1
  45. package/dist/client/assets/{WorkspaceRichText-D1M637Ff.js → WorkspaceRichText-CCOciILO.js} +2 -2
  46. package/dist/client/assets/WorkspaceRichText-CCOciILO.js.map +1 -0
  47. package/dist/client/assets/WorkspaceSettingsPage-GoBfQzBx.css +1 -0
  48. package/dist/client/assets/WorkspaceSettingsPage-JG-pN_CA.js +2 -0
  49. package/dist/client/assets/WorkspaceSettingsPage-JG-pN_CA.js.map +1 -0
  50. package/dist/client/assets/agent-api-Dl9TuGOJ.js +19 -0
  51. package/dist/client/assets/agent-api-Dl9TuGOJ.js.map +1 -0
  52. package/dist/client/assets/atlassianOAuthSetupIntentStorage-DE4ySCTb.js +2 -0
  53. package/dist/client/assets/atlassianOAuthSetupIntentStorage-DE4ySCTb.js.map +1 -0
  54. package/dist/client/assets/authenticatedMutationClient-DdowMjyo.js +2 -0
  55. package/dist/client/assets/{authenticatedMutationClient-DYaieXUe.js.map → authenticatedMutationClient-DdowMjyo.js.map} +1 -1
  56. package/dist/client/assets/{authorizedShareTransport-cxBoQzQ2.js → authorizedShareTransport-CnclcYai.js} +2 -2
  57. package/dist/client/assets/{authorizedShareTransport-cxBoQzQ2.js.map → authorizedShareTransport-CnclcYai.js.map} +1 -1
  58. package/dist/client/assets/client-Dq_XQE_l.js +5 -0
  59. package/dist/client/assets/client-Dq_XQE_l.js.map +1 -0
  60. package/dist/client/assets/confluenceTasks-DtKq8_eU.js +5 -0
  61. package/dist/client/assets/confluenceTasks-DtKq8_eU.js.map +1 -0
  62. package/dist/client/assets/connectionTestTransport-CPK98z7H.js +2 -0
  63. package/dist/client/assets/connectionTestTransport-CPK98z7H.js.map +1 -0
  64. package/dist/client/assets/{index-C7_FDTU7.js → index-zVjlBm9l.js} +3 -3
  65. package/dist/client/assets/{index-C7_FDTU7.js.map → index-zVjlBm9l.js.map} +1 -1
  66. package/dist/client/assets/{patterns-5N-j-AD2-B9qgekXA.js → patterns-5N-j-AD2-DLfaGePK.js} +2 -2
  67. package/dist/client/assets/{patterns-5N-j-AD2-B9qgekXA.js.map → patterns-5N-j-AD2-DLfaGePK.js.map} +1 -1
  68. package/dist/client/assets/{presentPortfolio-C_JsoSWg.js → presentPortfolio-DLEq-vEz.js} +2 -2
  69. package/dist/client/assets/{presentPortfolio-C_JsoSWg.js.map → presentPortfolio-DLEq-vEz.js.map} +1 -1
  70. package/dist/client/assets/{presentWorkspaceItems-DboAfwGc.js → presentWorkspaceItems-BOY3FbhO.js} +2 -2
  71. package/dist/client/assets/{presentWorkspaceItems-DboAfwGc.js.map → presentWorkspaceItems-BOY3FbhO.js.map} +1 -1
  72. package/dist/client/assets/{pullRequestReviewFailures-DHmYwffV.js → pullRequestReviewFailures-CyjTVnSX.js} +2 -2
  73. package/dist/client/assets/{pullRequestReviewFailures-DHmYwffV.js.map → pullRequestReviewFailures-CyjTVnSX.js.map} +1 -1
  74. package/dist/client/assets/{pullRequestReviewThreadReplay-Vy1k53qE.js → pullRequestReviewThreadReplay-CXHspFTr.js} +2 -2
  75. package/dist/client/assets/{pullRequestReviewThreadReplay-Vy1k53qE.js.map → pullRequestReviewThreadReplay-CXHspFTr.js.map} +1 -1
  76. package/dist/client/assets/releaseAgentTransport-DaO4svPu.js +2 -0
  77. package/dist/client/assets/releaseAgentTransport-DaO4svPu.js.map +1 -0
  78. package/dist/client/assets/releaseRoutes-B4ciNOJj.js +2 -0
  79. package/dist/client/assets/{releaseRoutes-t9uCfs5T.js.map → releaseRoutes-B4ciNOJj.js.map} +1 -1
  80. package/dist/client/assets/{serviceOnboarding-DLINCon7.js → serviceOnboarding-D0FmodRi.js} +2 -2
  81. package/dist/client/assets/{serviceOnboarding-DLINCon7.js.map → serviceOnboarding-D0FmodRi.js.map} +1 -1
  82. package/dist/client/assets/{useWorkspaceDefaultLanding-CC5ImHkL.js → useWorkspaceDefaultLanding-BaQdg0sY.js} +3 -3
  83. package/dist/client/assets/{useWorkspaceDefaultLanding-CC5ImHkL.js.map → useWorkspaceDefaultLanding-BaQdg0sY.js.map} +1 -1
  84. package/dist/client/assets/{useWorkspaceItems-B1X-JNwq.js → useWorkspaceItems-B-7JHtm0.js} +2 -2
  85. package/dist/client/assets/{useWorkspaceItems-B1X-JNwq.js.map → useWorkspaceItems-B-7JHtm0.js.map} +1 -1
  86. package/dist/client/assets/workspaceEntityRoutes-DqqDa0AB.js +2 -0
  87. package/dist/client/assets/workspaceEntityRoutes-DqqDa0AB.js.map +1 -0
  88. package/dist/client/assets/{workspaceScrollCapture-BsjcWVsk.js → workspaceScrollCapture-BYNfR2wo.js} +2 -2
  89. package/dist/client/assets/{workspaceScrollCapture-BsjcWVsk.js.map → workspaceScrollCapture-BYNfR2wo.js.map} +1 -1
  90. package/dist/client/assets/{workspaceSettingsTransport-Dw2hueXv.js → workspaceSettingsTransport-Br4lBmvS.js} +2 -2
  91. package/dist/client/assets/{workspaceSettingsTransport-Dw2hueXv.js.map → workspaceSettingsTransport-Br4lBmvS.js.map} +1 -1
  92. package/dist/client/build-graph.json +98 -0
  93. package/dist/client/index.html +1 -1
  94. package/dist/server/api/agent.d.ts +12 -0
  95. package/dist/server/api/agent.d.ts.map +1 -1
  96. package/dist/server/api/deliveryGraph.d.ts +20 -0
  97. package/dist/server/api/deliveryGraph.d.ts.map +1 -1
  98. package/dist/server/api/index.d.ts +1 -1
  99. package/dist/server/api/index.d.ts.map +1 -1
  100. package/dist/server/api/index.js +3 -3
  101. package/dist/server/api/session.d.ts +23 -1
  102. package/dist/server/api/session.d.ts.map +1 -1
  103. package/dist/server/api/shares.d.ts +2 -0
  104. package/dist/server/api/shares.d.ts.map +1 -1
  105. package/dist/server/assets/{BindConfig-Bj282xDC.js → BindConfig-DAASchDn.js} +315 -36
  106. package/dist/server/assets/BindConfig-DAASchDn.js.map +1 -0
  107. package/dist/server/assets/{agent-ZvwskOQu.js → agent-xQhAQXly.js} +26 -6
  108. package/dist/server/assets/agent-xQhAQXly.js.map +1 -0
  109. package/dist/server/assets/{controlCenterApi-5j3gOXgE.js → controlCenterApi-DNXK7MT1.js} +4 -3
  110. package/dist/server/assets/controlCenterApi-DNXK7MT1.js.map +1 -0
  111. package/dist/server/assets/{manualPluginSynchronization-CzIhZ_Dw.js → manualPluginSynchronization-DFIeUHP9.js} +4 -3
  112. package/dist/server/assets/manualPluginSynchronization-DFIeUHP9.js.map +1 -0
  113. package/dist/server/assets/{readiness-BtntBhDj.js → readiness-31Mqc-9H.js} +2 -2
  114. package/dist/server/assets/{readiness-BtntBhDj.js.map → readiness-31Mqc-9H.js.map} +1 -1
  115. package/dist/server/assets/{relationshipInferenceMaterialization-CR6xyMNL.js → relationshipInferenceMaterialization-Dyix96px.js} +41 -14
  116. package/dist/server/assets/relationshipInferenceMaterialization-Dyix96px.js.map +1 -0
  117. package/dist/server/assets/{workspaceSettings-C2Zsk6RI.js → workspaceSettings-sv8h_h2P.js} +4 -1
  118. package/dist/server/assets/workspaceSettings-sv8h_h2P.js.map +1 -0
  119. package/dist/server/build-graph.json +28 -1
  120. package/dist/server/domain/confluenceTasks.d.ts +27 -0
  121. package/dist/server/domain/confluenceTasks.d.ts.map +1 -0
  122. package/dist/server/domain/deliveryGraph.d.ts +2 -0
  123. package/dist/server/domain/deliveryGraph.d.ts.map +1 -1
  124. package/dist/server/domain/governedAction/bindings.d.ts +2 -0
  125. package/dist/server/domain/governedAction/bindings.d.ts.map +1 -1
  126. package/dist/server/domain/governedAction/model.d.ts +6 -0
  127. package/dist/server/domain/governedAction/model.d.ts.map +1 -1
  128. package/dist/server/domain/index.js +2 -2
  129. package/dist/server/domain/normalizedPage.d.ts +1 -0
  130. package/dist/server/domain/normalizedPage.d.ts.map +1 -1
  131. package/dist/server/domain/releasePipelineApproval.d.ts +31 -0
  132. package/dist/server/domain/releasePipelineApproval.d.ts.map +1 -0
  133. package/dist/server/index.js +5 -5
  134. package/dist/server/server/api/Handlers.d.ts +1 -1
  135. package/dist/server/server/api/Handlers.d.ts.map +1 -1
  136. package/dist/server/server/application/deliveryGraphInspection.d.ts.map +1 -1
  137. package/dist/server/server/application/normalizedPluginPageMaterialization.d.ts.map +1 -1
  138. package/dist/server/server/application/pipelineExecutionProjection.d.ts +1 -0
  139. package/dist/server/server/application/pipelineExecutionProjection.d.ts.map +1 -1
  140. package/dist/server/server/application/portfolioSnapshots.d.ts +4 -0
  141. package/dist/server/server/application/portfolioSnapshots.d.ts.map +1 -1
  142. package/dist/server/server/application/releasePublicationSubmissions.d.ts +32 -1
  143. package/dist/server/server/application/releasePublicationSubmissions.d.ts.map +1 -1
  144. package/dist/server/server/application/releaseRunbookHydration.d.ts +2310 -0
  145. package/dist/server/server/application/releaseRunbookHydration.d.ts.map +1 -0
  146. package/dist/server/server/cli.js +3 -3
  147. package/dist/server/server/governance/governedActionDigests.d.ts +3 -0
  148. package/dist/server/server/governance/governedActionDigests.d.ts.map +1 -1
  149. package/dist/server/server/governance/internal/execution-store/recovery-claim.d.ts +1 -0
  150. package/dist/server/server/governance/internal/execution-store/recovery-claim.d.ts.map +1 -1
  151. package/dist/server/server/index.js +2 -2
  152. package/dist/server/server/persistence/Persistence.d.ts +10 -0
  153. package/dist/server/server/persistence/Persistence.d.ts.map +1 -1
  154. package/dist/server/server/persistence/object-store/BlobPublisher.d.ts.map +1 -1
  155. package/dist/server/server/persistence/object-store/PinnedDirectory.d.ts +2 -2
  156. package/dist/server/server/persistence/object-store/PinnedDirectory.d.ts.map +1 -1
  157. package/dist/server/server/persistence/repositories/delivery-graph/contract.d.ts +10 -0
  158. package/dist/server/server/persistence/repositories/delivery-graph/contract.d.ts.map +1 -1
  159. package/dist/server/server/persistence/repositories/delivery-graph/decode.d.ts +2 -0
  160. package/dist/server/server/persistence/repositories/delivery-graph/decode.d.ts.map +1 -1
  161. package/dist/server/server/persistence/repositories/delivery-graph/read.d.ts +6 -0
  162. package/dist/server/server/persistence/repositories/delivery-graph/read.d.ts.map +1 -1
  163. package/dist/server/server/persistence/repositories/delivery-graph/rows.d.ts +1 -0
  164. package/dist/server/server/persistence/repositories/delivery-graph/rows.d.ts.map +1 -1
  165. package/dist/server/server/persistence/repositories/delivery-graph/write.d.ts +2 -0
  166. package/dist/server/server/persistence/repositories/delivery-graph/write.d.ts.map +1 -1
  167. package/dist/server/server/persistence/repositories/deliveryGraphRepository.d.ts +6 -0
  168. package/dist/server/server/persistence/repositories/deliveryGraphRepository.d.ts.map +1 -1
  169. package/dist/server/server/persistence/repositories/governed-action/codec.d.ts +4 -0
  170. package/dist/server/server/persistence/repositories/governed-action/codec.d.ts.map +1 -1
  171. package/dist/server/server/persistence/repositories/governed-action/contract.d.ts +2 -0
  172. package/dist/server/server/persistence/repositories/governed-action/contract.d.ts.map +1 -1
  173. package/dist/server/server/persistence/repositories/governed-action/read.d.ts +4 -0
  174. package/dist/server/server/persistence/repositories/governed-action/read.d.ts.map +1 -1
  175. package/dist/server/server/persistence/repositories/governed-action/transaction.d.ts +4 -0
  176. package/dist/server/server/persistence/repositories/governed-action/transaction.d.ts.map +1 -1
  177. package/dist/server/server/persistence/repositories/governed-action/write-preparation.d.ts +1 -0
  178. package/dist/server/server/persistence/repositories/governed-action/write-preparation.d.ts.map +1 -1
  179. package/dist/server/server/persistence/repositories/governed-action/write-replay.d.ts +2 -0
  180. package/dist/server/server/persistence/repositories/governed-action/write-replay.d.ts.map +1 -1
  181. package/dist/server/server/persistence/repositories/governed-action/write.d.ts +2 -0
  182. package/dist/server/server/persistence/repositories/governed-action/write.d.ts.map +1 -1
  183. package/dist/server/server/persistence/repositories/governedActionRepository.d.ts +4 -0
  184. package/dist/server/server/persistence/repositories/governedActionRepository.d.ts.map +1 -1
  185. package/package.json +3 -3
  186. package/dist/client/assets/AgentPage-C3LThgPZ.js +0 -3
  187. package/dist/client/assets/AgentPage-C3LThgPZ.js.map +0 -1
  188. package/dist/client/assets/AgentPage-DVSgQgJa.css +0 -1
  189. package/dist/client/assets/AtlassianOAuthCallbackPage-BPoF6oKf.js +0 -2
  190. package/dist/client/assets/BrowserCrypto-BMbjhcvP.js +0 -2
  191. package/dist/client/assets/BrowserSessionHydrator-BC1ymLkL.js +0 -2
  192. package/dist/client/assets/PortfolioOverview-CEI4gpXi.js +0 -2
  193. package/dist/client/assets/ReleaseWorkset-BluAe7Sq.js +0 -2
  194. package/dist/client/assets/ReleaseWorkset-BluAe7Sq.js.map +0 -1
  195. package/dist/client/assets/ServicesPage-_B89DAvG.js +0 -2
  196. package/dist/client/assets/WorkspaceEntityRoute-9iMOV64J.css +0 -1
  197. package/dist/client/assets/WorkspaceEntityRoute-B01fxxB3.js +0 -3
  198. package/dist/client/assets/WorkspaceEntityRoute-B01fxxB3.js.map +0 -1
  199. package/dist/client/assets/WorkspaceHomeLink-CkJfzO25.js +0 -2
  200. package/dist/client/assets/WorkspacePullRequestDetails-HwDgp12e.js +0 -3
  201. package/dist/client/assets/WorkspaceRichText-D1M637Ff.js.map +0 -1
  202. package/dist/client/assets/WorkspaceSettingsPage-DyoGiGJG.js +0 -2
  203. package/dist/client/assets/WorkspaceSettingsPage-DyoGiGJG.js.map +0 -1
  204. package/dist/client/assets/WorkspaceSettingsPage-P6yfac0b.css +0 -1
  205. package/dist/client/assets/agent-api-CeONl_8w.js +0 -19
  206. package/dist/client/assets/agent-api-CeONl_8w.js.map +0 -1
  207. package/dist/client/assets/authenticatedMutationClient-DYaieXUe.js +0 -2
  208. package/dist/client/assets/client-DKS82kT_.js +0 -5
  209. package/dist/client/assets/client-DKS82kT_.js.map +0 -1
  210. package/dist/client/assets/connectionTestTransport-I_Ga9UNs.js +0 -2
  211. package/dist/client/assets/connectionTestTransport-I_Ga9UNs.js.map +0 -1
  212. package/dist/client/assets/releaseRoutes-t9uCfs5T.js +0 -2
  213. package/dist/client/assets/workspaceEntityRoutes-2TejMrzb.js +0 -2
  214. package/dist/client/assets/workspaceEntityRoutes-2TejMrzb.js.map +0 -1
  215. package/dist/server/assets/BindConfig-Bj282xDC.js.map +0 -1
  216. package/dist/server/assets/agent-ZvwskOQu.js.map +0 -1
  217. package/dist/server/assets/controlCenterApi-5j3gOXgE.js.map +0 -1
  218. package/dist/server/assets/manualPluginSynchronization-CzIhZ_Dw.js.map +0 -1
  219. package/dist/server/assets/relationshipInferenceMaterialization-CR6xyMNL.js.map +0 -1
  220. package/dist/server/assets/workspaceSettings-C2Zsk6RI.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manualPluginSynchronization-DFIeUHP9.js","names":[],"sources":["../../../src/server/application/pipelineExecutionProjection.ts","../../../src/server/application/pluginSynchronizationAuthority.ts","../../../src/server/application/normalizedPluginPageMaterialization.ts","../../../src/server/application/manualPluginSynchronization.ts"],"sourcesContent":["import * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport { DeliveryEntityDetails } from \"../../domain/deliveryGraph.js\"\nimport type { NormalizedPluginEventV1 } from \"../../domain/plugins/events.js\"\nimport { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport {\n type CodePipelineCacheSelector,\n MaximumCodePipelineCorrelationExecutions\n} from \"../persistence/repositories/pluginRuntimeModels.js\"\n\ntype EntityUpsert = Extract<NormalizedPluginEventV1, { readonly _tag: \"UpsertEntity\" }>\n\nconst OptionalText = Schema.optionalKey(Schema.NullOr(Schema.String))\nconst OptionalUnknown = Schema.optionalKey(Schema.NullOr(Schema.Unknown))\nconst InputDirection: \"input\" = \"input\"\nconst OutputDirection: \"output\" = \"output\"\nconst ProxyRequired: \"proxy-required\" = \"proxy-required\"\nconst NamedText = Schema.Union([\n Schema.String,\n Schema.Struct({ name: Schema.optionalKey(Schema.NullOr(Schema.String)) })\n])\nconst PipelineSourceRevisionAttributes = Schema.Struct({\n actionName: OptionalText,\n revisionId: OptionalText,\n revisionSummary: OptionalText\n})\nconst PipelineArtifactRevisionAttributes = Schema.Struct({\n name: OptionalText,\n revisionId: OptionalText,\n revisionSummary: OptionalText,\n createdAt: OptionalUnknown\n})\nconst PipelineActionArtifactAttributes = Schema.Struct({\n name: OptionalText,\n access: Schema.optionalKey(Schema.Literal(\"proxy-required\"))\n})\nconst PipelineActionTypeAttributes = Schema.Struct({\n category: OptionalText,\n owner: OptionalText,\n provider: OptionalText,\n version: OptionalText\n})\nconst PipelineDeclarationActionAttributes = Schema.Struct({\n name: OptionalText,\n runOrder: Schema.optionalKey(Schema.NullOr(Schema.Int))\n})\nconst PipelineDeclarationStageAttributes = Schema.Struct({\n name: OptionalText,\n actions: Schema.optionalKey(Schema.Array(PipelineDeclarationActionAttributes))\n})\n\n/** Pipeline fields decoded only inside the CodePipeline projection boundary. */\nconst PipelineEntityAttributeFields = {\n pipelineName: OptionalText,\n pipelineVersion: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n executionId: OptionalText,\n triggerRevision: OptionalText,\n statusSummary: OptionalText,\n startedAt: OptionalUnknown,\n updatedAt: OptionalUnknown,\n sourceRevisions: Schema.optionalKey(Schema.Array(PipelineSourceRevisionAttributes)),\n triggerType: OptionalText,\n triggerDetail: OptionalText,\n executionMode: OptionalText,\n executionType: OptionalText,\n rollbackTargetExecutionId: OptionalText,\n artifactRevisions: Schema.optionalKey(Schema.Array(PipelineArtifactRevisionAttributes)),\n actionCount: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n actionsTruncated: Schema.optionalKey(Schema.Boolean),\n actionPagesRead: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n actionExecutionId: OptionalText,\n stageName: OptionalText,\n actionName: OptionalText,\n actionType: Schema.optionalKey(Schema.NullOr(PipelineActionTypeAttributes)),\n updatedBy: OptionalText,\n actionRegion: OptionalText,\n inputArtifacts: Schema.optionalKey(Schema.Array(PipelineActionArtifactAttributes)),\n outputArtifacts: Schema.optionalKey(Schema.Array(PipelineActionArtifactAttributes)),\n externalExecutionSummary: OptionalText,\n errorCode: OptionalText,\n errorMessage: OptionalText,\n stages: Schema.optionalKey(Schema.Array(PipelineDeclarationStageAttributes))\n}\n\n/** Provider-owned field names that unrelated entity decoders may safely ignore. */\nexport const PipelineEntityAttributeNames: ReadonlySet<string> = new Set(Object.keys(PipelineEntityAttributeFields))\n\nconst PipelineEntityAttributes = Schema.Struct({\n status: Schema.optionalKey(Schema.NullOr(NamedText)),\n ...PipelineEntityAttributeFields\n})\ntype PipelineEntityAttributes = typeof PipelineEntityAttributes.Type\n\n/** Redacted failure raised while correlating one bounded execution page. */\nexport class PipelineExecutionProjectionError extends Schema.TaggedErrorClass<PipelineExecutionProjectionError>()(\n \"PipelineExecutionProjectionError\",\n {\n diagnosticCode: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(100)),\n eventId: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(512))\n }\n) {}\n\nconst malformed = (diagnosticCode: string, eventId: string) =>\n new PipelineExecutionProjectionError({ diagnosticCode, eventId })\n\nconst decodeAttributes = Effect.fn(\"PipelineExecutionProjection.decodeAttributes\")(function*(event: EntityUpsert) {\n return yield* Schema.decodeUnknownEffect(PipelineEntityAttributes)(event.attributes).pipe(\n Effect.mapError(() => malformed(\"normalized-entity-attributes-invalid\", event.eventId))\n )\n})\n\nconst bounded = (value: string | null | undefined, fallback: string, maximum: number): string => {\n const normalized = value?.trim()\n return (normalized === undefined || normalized.length === 0 ? fallback : normalized).slice(0, maximum)\n}\n\nconst optionalBounded = (value: string | null | undefined, maximum: number): string | null => {\n const normalized = value?.trim()\n return normalized === undefined || normalized.length === 0 ? null : normalized.slice(0, maximum)\n}\n\nconst namedText = (value: typeof NamedText.Type | null | undefined): string | null =>\n typeof value === \"string\" ? value : (value?.name ?? null)\n\n/** Collapse provider statuses into the canonical execution state vocabulary. */\nexport const pipelineStatus = (\n value: string | null\n): \"failed\" | \"queued\" | \"running\" | \"stopped\" | \"succeeded\" => {\n switch (value?.toLocaleLowerCase(\"en-US\")) {\n case \"failed\":\n case \"failure\":\n return \"failed\"\n case \"in-progress\":\n case \"inprogress\":\n case \"running\":\n return \"running\"\n case \"succeeded\":\n case \"success\":\n case \"successful\":\n return \"succeeded\"\n case \"stopped\":\n case \"stopping\":\n case \"superseded\":\n case \"abandoned\":\n case \"cancelled\":\n case \"canceled\":\n return \"stopped\"\n default:\n return \"queued\"\n }\n}\n\nconst normalizedTimestamp = Effect.fn(\"PipelineExecutionProjection.normalizeTimestamp\")(function*(\n value: unknown,\n eventId: string\n): Effect.fn.Return<string | null, PipelineExecutionProjectionError> {\n if (value === null || value === undefined) return null\n const timestamp = yield* Schema.decodeUnknownEffect(UtcTimestamp)(value).pipe(\n Effect.mapError(() => malformed(\"normalized-pipeline-timestamp-invalid\", eventId))\n )\n return DateTime.formatIso(timestamp)\n})\n\ninterface PipelineSiblingEvent {\n readonly attributes: PipelineEntityAttributes\n readonly event: EntityUpsert\n}\n\nconst laterSibling = (\n current: PipelineSiblingEvent | undefined,\n candidate: PipelineSiblingEvent\n): PipelineSiblingEvent =>\n current === undefined || DateTime.Order(current.event.observedAt, candidate.event.observedAt) < 0\n ? candidate\n : current\n\nconst aggregateStatus = (\n statuses: ReadonlyArray<ReturnType<typeof pipelineStatus>>\n): ReturnType<typeof pipelineStatus> => {\n if (statuses.includes(\"failed\")) return \"failed\"\n if (statuses.includes(\"running\")) return \"running\"\n if (statuses.includes(\"stopped\")) return \"stopped\"\n if (statuses.length > 0 && statuses.every((status) => status === \"succeeded\")) return \"succeeded\"\n return \"queued\"\n}\n\nconst executionKey = (attributes: PipelineEntityAttributes): string | null => {\n const pipelineName = optionalBounded(attributes.pipelineName, 200)\n const executionId = optionalBounded(attributes.executionId, 512)\n return pipelineName === null || executionId === null ? null : `${pipelineName}\\u0000${executionId}`\n}\n\n/** Derive bounded indexed-cache coordinates from the newly accepted pipeline page. */\nexport const codePipelineCacheSelectors = Effect.fn(\n \"PipelineExecutionProjection.cacheSelectors\"\n)(function*(\n events: ReadonlyArray<NormalizedPluginEventV1>\n): Effect.fn.Return<ReadonlyArray<CodePipelineCacheSelector>, PipelineExecutionProjectionError> {\n const selectors = new Map<string, CodePipelineCacheSelector>()\n for (const event of events) {\n if (\n event._tag !== \"UpsertEntity\" ||\n (event.entityType !== \"aws.codepipeline.pipeline\" &&\n event.entityType !== \"aws.codepipeline.execution\" &&\n event.entityType !== \"aws.codepipeline.stage\" &&\n event.entityType !== \"aws.codepipeline.action\")\n ) continue\n const attributes = yield* decodeAttributes(event)\n const pipelineName = optionalBounded(attributes.pipelineName, 200)\n if (pipelineName === null) continue\n const executionId = event.entityType === \"aws.codepipeline.pipeline\"\n ? null\n : optionalBounded(attributes.executionId, 512)\n if (event.entityType !== \"aws.codepipeline.pipeline\" && executionId === null) continue\n const selector = {\n executionId,\n pipelineName,\n pipelineVersion: attributes.pipelineVersion ?? null\n }\n const key = executionId === null\n ? `${pipelineName}\\u0000declaration\\u0000${String(selector.pipelineVersion ?? \"\")}`\n : `${pipelineName}\\u0000execution\\u0000${executionId}`\n if (!selectors.has(key) && selectors.size >= MaximumCodePipelineCorrelationExecutions) {\n return yield* malformed(\"normalized-pipeline-correlation-scope-exceeded\", event.eventId)\n }\n selectors.set(key, selector)\n }\n return [...selectors.values()]\n})\n\ninterface PipelineDeclarationKey {\n readonly pipelineName: string\n readonly pipelineVersion: number | null\n}\n\nconst declarationKey = (attributes: PipelineEntityAttributes): PipelineDeclarationKey | null => {\n const pipelineName = optionalBounded(attributes.pipelineName, 200)\n return pipelineName === null\n ? null\n : { pipelineName, pipelineVersion: attributes.pipelineVersion ?? null }\n}\n\nconst declarationMatchesExecution = (\n declaration: PipelineDeclarationKey,\n execution: PipelineEntityAttributes\n): boolean => {\n const pipelineName = optionalBounded(execution.pipelineName, 200)\n if (pipelineName !== declaration.pipelineName) return false\n const executionVersion = execution.pipelineVersion ?? null\n return declaration.pipelineVersion === null || executionVersion === null ||\n declaration.pipelineVersion === executionVersion\n}\n\n/** Select cached execution envelopes affected by newly accepted declarations, stages, or actions. */\nexport const affectedPipelineExecutionEvents = Effect.fn(\n \"PipelineExecutionProjection.affectedExecutions\"\n)(function*(\n cachedEvents: ReadonlyArray<NormalizedPluginEventV1>,\n changedEvents: ReadonlyArray<EntityUpsert>\n): Effect.fn.Return<ReadonlyArray<EntityUpsert>, PipelineExecutionProjectionError> {\n const affectedKeys = new Set<string>()\n const acceptedDeclarations: Array<PipelineDeclarationKey> = []\n for (const event of changedEvents) {\n if (event.entityType === \"aws.codepipeline.pipeline\") {\n const key = declarationKey(yield* decodeAttributes(event))\n if (key !== null) acceptedDeclarations.push(key)\n } else if (event.entityType === \"aws.codepipeline.stage\" || event.entityType === \"aws.codepipeline.action\") {\n const key = executionKey(yield* decodeAttributes(event))\n if (key !== null) affectedKeys.add(key)\n }\n }\n if (affectedKeys.size === 0 && acceptedDeclarations.length === 0) return []\n\n const executions: Array<EntityUpsert> = []\n for (const event of cachedEvents) {\n if (event._tag !== \"UpsertEntity\" || event.entityType !== \"aws.codepipeline.execution\") continue\n const attributes = yield* decodeAttributes(event)\n const key = executionKey(attributes)\n if (\n (key !== null && affectedKeys.has(key)) ||\n acceptedDeclarations.some((declaration) => declarationMatchesExecution(declaration, attributes))\n ) executions.push(event)\n }\n return executions\n})\n\n/** Correlate bounded pipeline, stage, and action siblings into one safe execution projection. */\nexport const projectPipelineExecution = Effect.fn(\"PipelineExecutionProjection.project\")(function*(\n event: EntityUpsert,\n siblingEvents: ReadonlyArray<NormalizedPluginEventV1>\n): Effect.fn.Return<DeliveryEntityDetails, PipelineExecutionProjectionError> {\n const attributes = yield* decodeAttributes(event)\n const executionId = bounded(attributes.executionId, event.vendorImmutableId, 512)\n const pipelineName = bounded(attributes.pipelineName, \"unknown\", 200)\n const stageEvents = new Map<string, PipelineSiblingEvent>()\n const actionEvents = new Map<string, PipelineSiblingEvent>()\n let declaration: PipelineSiblingEvent | undefined\n\n for (const sibling of siblingEvents) {\n if (sibling._tag !== \"UpsertEntity\" || sibling.eventId === event.eventId) continue\n if (\n sibling.entityType !== \"aws.codepipeline.pipeline\" &&\n sibling.entityType !== \"aws.codepipeline.stage\" &&\n sibling.entityType !== \"aws.codepipeline.action\"\n ) continue\n const siblingAttributes = yield* decodeAttributes(sibling)\n if (bounded(siblingAttributes.pipelineName, \"unknown\", 200) !== pipelineName) continue\n const candidate = { attributes: siblingAttributes, event: sibling }\n if (sibling.entityType === \"aws.codepipeline.pipeline\") {\n if (\n attributes.pipelineVersion !== null &&\n attributes.pipelineVersion !== undefined &&\n siblingAttributes.pipelineVersion !== null &&\n siblingAttributes.pipelineVersion !== undefined &&\n siblingAttributes.pipelineVersion !== attributes.pipelineVersion\n ) continue\n declaration = laterSibling(declaration, candidate)\n continue\n }\n if (bounded(siblingAttributes.executionId, \"\", 512) !== executionId) continue\n if (sibling.entityType === \"aws.codepipeline.stage\") {\n const stageName = optionalBounded(siblingAttributes.stageName, 200)\n if (stageName !== null) stageEvents.set(stageName, laterSibling(stageEvents.get(stageName), candidate))\n continue\n }\n const actionExecutionId = optionalBounded(siblingAttributes.actionExecutionId, 512)\n if (actionExecutionId !== null) {\n actionEvents.set(actionExecutionId, laterSibling(actionEvents.get(actionExecutionId), candidate))\n }\n }\n\n const declaredStages = (declaration?.attributes.stages ?? []).flatMap((stage) => {\n const name = optionalBounded(stage.name, 200)\n const actionNames = (stage.actions ?? []).flatMap((action, index) => {\n const actionName = optionalBounded(action.name, 200)\n return actionName === null ? [] : [{ index, name: actionName, runOrder: action.runOrder ?? index + 1 }]\n }).sort((left, right) => left.runOrder - right.runOrder || left.index - right.index).map(({ name }) => name)\n return name === null ? [] : [{ actionCount: stage.actions?.length ?? 0, actionNames, name }]\n }).slice(0, 100)\n const stageOrder = new Map(declaredStages.map(({ name }, index) => [name, index]))\n const actionOrder = new Map<string, number>()\n for (const stage of declaredStages) {\n for (let index = 0; index < stage.actionNames.length; index++) {\n const actionName = stage.actionNames[index]\n if (actionName === undefined) continue\n const key = `${stage.name}\\u0000${actionName}`\n if (!actionOrder.has(key)) actionOrder.set(key, index)\n }\n }\n const actions = yield* Effect.forEach(\n [...actionEvents.entries()],\n ([actionExecutionId, sibling]) =>\n Effect.gen(function*() {\n const action = sibling.attributes\n const stageName = bounded(action.stageName, \"Unknown stage\", 200)\n const actionName = bounded(action.actionName, actionExecutionId, 200)\n return {\n actionExecutionId,\n stageName,\n actionName,\n status: pipelineStatus(namedText(action.status)),\n startedAt: yield* normalizedTimestamp(action.startedAt, sibling.event.eventId),\n updatedAt: yield* normalizedTimestamp(action.updatedAt, sibling.event.eventId),\n updatedBy: optionalBounded(action.updatedBy, 512),\n category: optionalBounded(action.actionType?.category, 100),\n provider: optionalBounded(action.actionType?.provider, 100),\n owner: optionalBounded(action.actionType?.owner, 100),\n version: optionalBounded(action.actionType?.version, 100),\n region: optionalBounded(action.actionRegion, 100),\n externalExecutionSummary: optionalBounded(action.externalExecutionSummary, 500),\n errorCode: optionalBounded(action.errorCode, 200),\n errorMessage: optionalBounded(action.errorMessage, 500),\n artifacts: [\n ...(action.inputArtifacts ?? []).map((artifact, index) => ({\n name: bounded(artifact.name, `${actionName} input ${String(index + 1)}`, 200),\n direction: InputDirection,\n access: ProxyRequired\n })),\n ...(action.outputArtifacts ?? []).map((artifact, index) => ({\n name: bounded(artifact.name, `${actionName} output ${String(index + 1)}`, 200),\n direction: OutputDirection,\n access: ProxyRequired\n }))\n ].slice(0, 100)\n }\n }),\n { concurrency: 1 }\n )\n actions.sort((left, right) => {\n const stageComparison = (stageOrder.get(left.stageName) ?? 100) - (stageOrder.get(right.stageName) ?? 100) ||\n left.stageName.localeCompare(right.stageName)\n if (stageComparison !== 0) return stageComparison\n const leftOrder = actionOrder.get(`${left.stageName}\\u0000${left.actionName}`)\n const rightOrder = actionOrder.get(`${right.stageName}\\u0000${right.actionName}`)\n if (leftOrder !== undefined || rightOrder !== undefined) {\n const declaredComparison = (leftOrder ?? Number.MAX_SAFE_INTEGER) - (rightOrder ?? Number.MAX_SAFE_INTEGER)\n if (declaredComparison !== 0) return declaredComparison\n }\n return left.actionName.localeCompare(right.actionName) ||\n left.actionExecutionId.localeCompare(right.actionExecutionId)\n })\n const visibleActions = actions.slice(0, 200)\n const actionCount = Math.max(attributes.actionCount ?? 0, actions.length)\n const actionsTruncated = (attributes.actionsTruncated ?? false) || actionCount > visibleActions.length\n\n const allStageNames = [\n ...declaredStages.map(({ name }) => name),\n ...[...stageEvents.keys()].filter((name) => !stageOrder.has(name)).sort(),\n ...actions.map(({ stageName }) => stageName).filter(\n (name, index, names) => !stageOrder.has(name) && !stageEvents.has(name) && names.indexOf(name) === index\n ).sort()\n ].slice(0, 100)\n const declaredStageByName = new Map(declaredStages.map((stage) => [stage.name, stage]))\n const stages = allStageNames.map((name) => {\n const stage = stageEvents.get(name)?.attributes\n const stageActions = actions.filter((action) => action.stageName === name)\n const visibleStageActionCount = visibleActions.filter((action) => action.stageName === name).length\n const stageActionCount = Math.max(\n stage?.actionCount ?? 0,\n declaredStageByName.get(name)?.actionCount ?? 0,\n stageActions.length\n )\n return {\n name,\n status: stage === undefined\n ? aggregateStatus(stageActions.map(({ status }) => status))\n : pipelineStatus(namedText(stage.status)),\n actionCount: stageActionCount,\n actionsTruncated: (stage?.actionsTruncated ?? false) ||\n (attributes.actionsTruncated ?? false) ||\n stageActionCount > visibleStageActionCount\n }\n })\n const sourceRevision = attributes.sourceRevisions?.find(({ revisionId }) => optionalBounded(revisionId, 512) !== null)\n ?.revisionId\n const sourceRevisions = (attributes.sourceRevisions ?? []).flatMap((source) => {\n const actionName = optionalBounded(source.actionName, 200)\n return actionName === null ? [] : [{\n actionName,\n revisionId: optionalBounded(source.revisionId, 512),\n revisionSummary: optionalBounded(source.revisionSummary, 500)\n }]\n }).filter((source, index, sources) =>\n sources.findIndex(({ actionName }) => actionName === source.actionName) === index\n ).slice(0, 100)\n const sourceArtifacts = yield* Effect.forEach(\n (attributes.artifactRevisions ?? []).slice(0, 100),\n (artifact, index) =>\n Effect.gen(function*() {\n return {\n name: bounded(artifact.name, `Source artifact ${String(index + 1)}`, 200),\n revisionId: optionalBounded(artifact.revisionId, 512),\n revisionSummary: optionalBounded(artifact.revisionSummary, 500),\n createdAt: yield* normalizedTimestamp(artifact.createdAt, event.eventId),\n access: ProxyRequired\n }\n }),\n { concurrency: 1 }\n )\n return yield* Schema.decodeUnknownEffect(DeliveryEntityDetails)({\n _tag: \"pipeline-execution\",\n pipelineName,\n executionId,\n status: pipelineStatus(namedText(attributes.status)),\n triggerRevision: bounded(\n optionalBounded(attributes.triggerRevision, 512) ?? optionalBounded(sourceRevision, 512),\n event.revision,\n 512\n ),\n pipelineVersion: attributes.pipelineVersion ?? null,\n statusSummary: optionalBounded(attributes.statusSummary, 500),\n startedAt: yield* normalizedTimestamp(attributes.startedAt, event.eventId),\n updatedAt: yield* normalizedTimestamp(attributes.updatedAt, event.eventId),\n triggerType: optionalBounded(attributes.triggerType, 100),\n triggerDetail: optionalBounded(attributes.triggerDetail, 500),\n executionMode: optionalBounded(attributes.executionMode, 100),\n executionType: optionalBounded(attributes.executionType, 100),\n rollbackTargetExecutionId: optionalBounded(attributes.rollbackTargetExecutionId, 512),\n sourceRevisions,\n stages,\n actions: visibleActions,\n actionCount,\n actionsTruncated,\n actionPagesRead: Math.max(attributes.actionPagesRead ?? 0, 0),\n sourceArtifacts\n }).pipe(\n Effect.mapError(() => malformed(\"normalized-pipeline-details-invalid\", event.eventId))\n )\n})\n","import * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\n\nimport type { PluginConnectionId, WorkspaceId } from \"../../domain/identifiers.js\"\nimport type { ProviderId } from \"../../domain/sourceRevision.js\"\nimport type { PersistenceOperationFailure, PersistenceService } from \"../persistence/Persistence.js\"\nimport type { PluginConnectionRecord } from \"../persistence/repositories/models.js\"\nimport { PluginConflictFailure } from \"../plugins/failures.js\"\n\n/** Exact mutable host state that authorized one manual synchronization runtime. */\nexport interface PluginSynchronizationAuthority {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly connectionRevision: number\n readonly configurationRevision: number | null\n}\n\nconst conflict = () =>\n new PluginConflictFailure({\n operation: \"manual-sync\",\n diagnosticCode: \"manual-sync-runtime-authority-changed\"\n })\n\nconst authorityFor = Effect.fn(\"PluginSynchronizationAuthority.forConnection\")(function*(\n persistence: PersistenceService,\n connection: PluginConnectionRecord\n) {\n const configuration = yield* persistence.pluginConfigurations.get(\n connection.workspaceId,\n connection.pluginConnectionId\n )\n return {\n workspaceId: connection.workspaceId,\n pluginConnectionId: connection.pluginConnectionId,\n providerId: connection.providerId,\n connectionRevision: connection.revision,\n configurationRevision: Option.isSome(configuration) ? configuration.value.revision : null\n } satisfies PluginSynchronizationAuthority\n})\n\n/** Capture connection and configuration revisions in one durable read transaction. */\nexport const capturePluginSynchronizationAuthority = Effect.fn(\n \"PluginSynchronizationAuthority.capture\"\n)(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n): Effect.fn.Return<\n { readonly connection: PluginConnectionRecord; readonly authority: PluginSynchronizationAuthority },\n PersistenceOperationFailure\n> {\n return yield* persistence.transact(Effect.gen(function*() {\n const connection = yield* persistence.pluginConnections.get(workspaceId, pluginConnectionId)\n const authority = yield* authorityFor(persistence, connection)\n return { connection, authority }\n }))\n})\n\n/** Reject a write transaction when its runtime no longer owns current connection authority. */\nexport const verifyPluginSynchronizationAuthority = Effect.fn(\n \"PluginSynchronizationAuthority.verify\"\n)(function*(\n persistence: PersistenceService,\n expected: PluginSynchronizationAuthority\n): Effect.fn.Return<void, PluginConflictFailure | PersistenceOperationFailure> {\n const connection = yield* persistence.pluginConnections.get(\n expected.workspaceId,\n expected.pluginConnectionId\n ).pipe(\n Effect.catchTag(\"RecordNotFoundError\", () => conflict())\n )\n const current = yield* authorityFor(persistence, connection)\n if (\n !connection.isEnabled ||\n current.providerId !== expected.providerId ||\n current.connectionRevision !== expected.connectionRevision ||\n current.configurationRevision !== expected.configurationRevision\n ) {\n return yield* conflict()\n }\n})\n","import * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { derivePersonInitials, Person, RoleAssignment } from \"../../domain/actors.js\"\nimport {\n DeliveryEntityDetails,\n type DeliveryEntityKind,\n type DeliveryNode,\n type DeliveryRelationship,\n EvidencePredicate,\n EvidenceValue,\n LedgerRevision,\n RelationshipKind\n} from \"../../domain/deliveryGraph.js\"\nimport type { Freshness, PluginHealth } from \"../../domain/freshness.js\"\nimport {\n EntityId,\n EnvironmentId,\n EvidenceClaimId,\n EvidenceId,\n GraphNodeId,\n PersonId,\n type PluginConnectionId,\n RelationshipId,\n ReleaseId,\n RoleAssignmentId,\n type WorkspaceId\n} from \"../../domain/identifiers.js\"\nimport { NormalizedIssueAttributes } from \"../../domain/normalizedIssue.js\"\nimport { NormalizedPluginEventV1, PluginEventId, type PluginSyncPageV1 } from \"../../domain/plugins/events.js\"\nimport { Release } from \"../../domain/release.js\"\nimport { deriveReleaseRelay } from \"../../domain/releaseRelay.js\"\nimport { NormalizationSchemaVersion, type ProviderId, VendorImmutableId } from \"../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport type { WorkspaceSettingsV1 } from \"../../domain/workspaceSettings.js\"\nimport type { PersistenceOperationFailure, PersistenceService } from \"../persistence/Persistence.js\"\nimport { Persistence } from \"../persistence/Persistence.js\"\nimport { DeliveryGraphWriteBatch } from \"../persistence/repositories/deliveryGraphRepository.js\"\nimport type { EntityRecord, RoleAssignmentRecord } from \"../persistence/repositories/models.js\"\nimport { type PluginCacheRecord, type PluginStreamKey } from \"../persistence/repositories/pluginRuntimeModels.js\"\nimport type { WorkspaceSettingsRecord } from \"../persistence/repositories/workspaceSettingsRepository.js\"\nimport { ConfluencePageAttributesV1 } from \"../plugins/confluence/ConfluencePageSchemas.js\"\nimport type { PluginConflictFailure } from \"../plugins/failures.js\"\nimport {\n affectedPipelineExecutionEvents,\n codePipelineCacheSelectors,\n PipelineEntityAttributeNames,\n pipelineStatus,\n projectPipelineExecution\n} from \"./pipelineExecutionProjection.js\"\nimport {\n type PluginSynchronizationAuthority,\n verifyPluginSynchronizationAuthority\n} from \"./pluginSynchronizationAuthority.js\"\nimport { materializeRelationshipInference } from \"./relationshipInferenceMaterialization.js\"\n\ntype EntityUpsert = Extract<NormalizedPluginEventV1, { readonly _tag: \"UpsertEntity\" }>\ntype PageDetails = Extract<DeliveryEntityDetails, { readonly _tag: \"page\" }>\ntype EntityTombstone = Extract<NormalizedPluginEventV1, { readonly _tag: \"TombstoneEntity\" }>\ntype EvidenceAppend = Extract<NormalizedPluginEventV1, { readonly _tag: \"AppendEvidence\" }>\ntype PersonUpsert = Extract<NormalizedPluginEventV1, { readonly _tag: \"UpsertPerson\" }>\ntype RelationshipProposal = Extract<NormalizedPluginEventV1, { readonly _tag: \"ProposeRelationship\" }>\n\nconst isCodePipelineEntityType = (entityType: string): boolean =>\n entityType === \"aws.codepipeline.pipeline\" ||\n entityType === \"aws.codepipeline.execution\" ||\n entityType === \"aws.codepipeline.stage\" ||\n entityType === \"aws.codepipeline.action\"\n\nconst isCodePipelineUpsert = (event: NormalizedPluginEventV1): event is EntityUpsert =>\n event._tag === \"UpsertEntity\" && isCodePipelineEntityType(event.entityType)\n\nconst isCodePipelineTombstone = (event: NormalizedPluginEventV1): event is EntityTombstone =>\n event._tag === \"TombstoneEntity\" && isCodePipelineEntityType(event.entityType)\n\nconst pipelineEntityIdentity = (event: EntityUpsert | EntityTombstone): string =>\n `${event.entityType}\\u0000${event.vendorImmutableId}`\n\ninterface RelationshipEndpointResolution {\n readonly entity: EntityRecord | null\n readonly kind: DeliveryRelationship[\"sourceNodeKind\"]\n readonly node: DeliveryNode | null\n readonly nodeId: GraphNodeId\n readonly releaseId: ReleaseId | null\n}\n\nconst OptionalText = Schema.optionalKey(Schema.NullOr(Schema.String))\nconst OptionalUnknown = Schema.optionalKey(Schema.NullOr(Schema.Unknown))\nconst NamedText = Schema.Union([\n Schema.String,\n Schema.Struct({ name: Schema.optionalKey(Schema.NullOr(Schema.String)) })\n])\nconst EntityAttributes = Schema.Struct({\n key: OptionalText,\n status: Schema.optionalKey(Schema.NullOr(NamedText)),\n priority: Schema.optionalKey(Schema.NullOr(NamedText)),\n estimatePoints: Schema.optionalKey(Schema.NullOr(Schema.Number)),\n repository: OptionalText,\n sourceBranch: OptionalText,\n targetBranch: OptionalText,\n headRevision: OptionalText,\n baseRevision: OptionalText,\n mergeBase: OptionalText,\n description: OptionalText,\n authorArn: OptionalText,\n creationDate: OptionalUnknown,\n lastActivityDate: OptionalUnknown,\n reviewState: OptionalText,\n spaceKey: OptionalText,\n spaceId: OptionalText,\n currentVersion: Schema.optionalKey(Schema.NullOr(Schema.Number)),\n linkedIssueKeys: Schema.optionalKey(Schema.Array(Schema.String)),\n linkedReleaseVersions: Schema.optionalKey(Schema.Array(Schema.String)),\n environmentId: OptionalText,\n revision: OptionalText,\n durationMinutes: Schema.optionalKey(Schema.NullOr(Schema.Number)),\n billable: Schema.optionalKey(Schema.Boolean),\n locked: Schema.optionalKey(Schema.Boolean),\n approvalState: OptionalText,\n userId: OptionalText,\n projectId: OptionalText,\n interval: Schema.optionalKey(Schema.Struct({\n duration: OptionalText,\n state: OptionalText,\n start: OptionalUnknown,\n end: OptionalUnknown\n }))\n})\nconst LegacyIssueAttributes = Schema.Struct({\n key: OptionalText,\n status: Schema.optionalKey(Schema.NullOr(NamedText)),\n priority: Schema.optionalKey(Schema.NullOr(NamedText)),\n estimatePoints: Schema.optionalKey(Schema.NullOr(Schema.Number))\n})\nconst LegacyIssueAttributeKeys: ReadonlySet<string> = new Set([\n \"key\",\n \"status\",\n \"priority\",\n \"estimatePoints\",\n \"schemaVersion\",\n \"summary\"\n])\nconst CanonicalIssueAttributeKeys: ReadonlySet<string> = new Set(Object.keys(NormalizedIssueAttributes.fields))\nconst ReleaseAttributes = Schema.Struct({\n serviceName: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200)),\n version: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(100)),\n lifecycle: Schema.Literals([\"assembling\", \"candidate\", \"deploying\", \"released\", \"cancelled\"])\n})\nconst JiraIssueRelationshipSnapshot = Schema.Struct({\n fixVersions: Schema.Array(Schema.Struct({\n sourceId: Schema.NullOr(Schema.String)\n })),\n truncatedFields: Schema.Array(Schema.String)\n})\nconst EvidenceData = Schema.Struct({\n predicate: Schema.optionalKey(EvidencePredicate),\n value: Schema.optionalKey(EvidenceValue)\n})\n/** Redacted failure raised before a normalized page can become a canonical projection. */\nexport class NormalizedPluginPageMaterializationError extends Schema.TaggedErrorClass<\n NormalizedPluginPageMaterializationError\n>()(\"NormalizedPluginPageMaterializationError\", {\n diagnosticCode: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(100)),\n eventId: Schema.NullOr(Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(512)))\n}) {}\n\nconst malformed = (diagnosticCode: string, eventId: string | null = null) =>\n new NormalizedPluginPageMaterializationError({ diagnosticCode, eventId })\n\nconst decodedAttributes = Effect.fn(\"NormalizedPluginPageMaterialization.decodeAttributes\")(function*(\n event: EntityUpsert\n) {\n return yield* Schema.decodeUnknownEffect(EntityAttributes)(event.attributes).pipe(\n Effect.mapError(() => malformed(\"normalized-entity-attributes-invalid\", event.eventId))\n )\n})\n\nconst bounded = (value: string | null | undefined, fallback: string, maximum: number): string => {\n const normalized = value?.trim()\n return (normalized === undefined || normalized.length === 0 ? fallback : normalized).slice(0, maximum)\n}\n\nconst optionalBounded = (value: string | null | undefined, maximum: number): string | null => {\n const normalized = value?.trim()\n return normalized === undefined || normalized.length === 0 ? null : normalized.slice(0, maximum)\n}\n\nconst namedText = (value: typeof NamedText.Type | null | undefined): string | null =>\n typeof value === \"string\" ? value : (value?.name ?? null)\n\nconst decodedOptionalEntityTimestamp = Effect.fn(\n \"NormalizedPluginPageMaterialization.decodeOptionalEntityTimestamp\"\n)(function*(\n value: unknown,\n eventId: string,\n diagnosticCode: string\n): Effect.fn.Return<UtcTimestamp | null, NormalizedPluginPageMaterializationError> {\n if (value === null || value === undefined) return null\n return yield* Schema.decodeUnknownEffect(UtcTimestamp)(value).pipe(\n Effect.mapError(() => malformed(diagnosticCode, eventId))\n )\n})\n\nconst decodedIssueAttributes = Effect.fn(\"NormalizedPluginPageMaterialization.decodeIssueAttributes\")(function*(\n event: EntityUpsert\n) {\n const normalized = Schema.decodeUnknownResult(NormalizedIssueAttributes)(event.attributes)\n if (Result.isSuccess(normalized)) return normalized.success\n if (\n Object.keys(event.attributes).some((key) =>\n !LegacyIssueAttributeKeys.has(key) &&\n (!PipelineEntityAttributeNames.has(key) || CanonicalIssueAttributeKeys.has(key))\n )\n ) {\n return yield* malformed(\"normalized-issue-attributes-invalid\", event.eventId)\n }\n\n const legacy = yield* Schema.decodeUnknownEffect(LegacyIssueAttributes)(event.attributes).pipe(\n Effect.mapError(() => malformed(\"normalized-issue-attributes-invalid\", event.eventId))\n )\n const key = bounded(legacy.key, event.vendorImmutableId, 100)\n return yield* Schema.decodeUnknownEffect(NormalizedIssueAttributes)({\n key,\n status: bounded(namedText(legacy.status), \"unknown\", 100),\n priority: legacy.priority === null || legacy.priority === undefined\n ? null\n : bounded(namedText(legacy.priority), \"unknown\", 100),\n estimatePoints: legacy.estimatePoints ?? null\n }).pipe(Effect.mapError(() => malformed(\"normalized-issue-attributes-invalid\", event.eventId)))\n})\n\nconst decodedPageTimestamp = Effect.fn(\"NormalizedPluginPageMaterialization.decodePageTimestamp\")(function*(\n value: string,\n eventId: string\n) {\n return yield* Schema.decodeUnknownEffect(UtcTimestamp)(value).pipe(\n Effect.mapError(() => malformed(\"normalized-page-timestamp-invalid\", eventId))\n )\n})\n\nconst decodedConfluencePageAttributes = Effect.fn(\n \"NormalizedPluginPageMaterialization.decodeConfluencePageAttributes\"\n)(function*(event: EntityUpsert) {\n if (event.entityType !== \"confluence-page\") return null\n const decoded = Schema.decodeUnknownResult(ConfluencePageAttributesV1)(event.attributes)\n if (Result.isFailure(decoded)) {\n if (Object.hasOwn(event.attributes, \"schemaVersion\")) {\n return yield* malformed(\"normalized-confluence-page-attributes-invalid\", event.eventId)\n }\n return null\n }\n const attributes = decoded.success\n const versions = yield* Effect.forEach(attributes.versions, (version) =>\n Effect.gen(function*() {\n return {\n number: version.number,\n createdAt: yield* decodedPageTimestamp(version.createdAt, event.eventId),\n message: version.message,\n minorEdit: version.minorEdit,\n authorSourcePersonId: version.authorId\n }\n }))\n const attachments = attributes.attachments === undefined\n ? undefined\n : yield* Effect.forEach(attributes.attachments, (attachment) =>\n Effect.gen(function*() {\n return {\n ...attachment,\n createdAt: yield* decodedPageTimestamp(attachment.createdAt, event.eventId)\n }\n }))\n const contentState: \"lazy\" | \"loaded\" = attributes.contentState ?? \"loaded\"\n return {\n sourceSpaceId: attributes.spaceId,\n parentSourceId: attributes.parentId,\n createdAt: yield* decodedPageTimestamp(attributes.createdAt, event.eventId),\n updatedAt: yield* decodedPageTimestamp(attributes.updatedAt, event.eventId),\n content: attributes.content,\n contentState,\n taskUpdatesSafe: attributes.taskUpdatesSafe ?? false,\n versions,\n versionHistory: attributes.versionHistory,\n contributors: attributes.contributors.map((contributor) => ({\n sourcePersonId: contributor.accountId,\n displayName: contributor.displayName,\n active: contributor.active,\n external: contributor.external,\n resolved: contributor.resolved,\n roles: contributor.roles\n })),\n ...(attachments === undefined ? {} : { attachments }),\n ...(attributes.attachmentInventory === undefined ? {} : {\n attachmentInventory: attributes.attachmentInventory\n }),\n ...(attributes.watcherInventory === undefined ? {} : { watcherInventory: attributes.watcherInventory })\n }\n})\n\nconst canonicalKind = (entityType: string): typeof DeliveryEntityKind.Type | null => {\n switch (entityType) {\n case \"issue\":\n case \"jira.issue\":\n return \"issue\"\n case \"pull-request\":\n return \"pull-request\"\n case \"page\":\n case \"confluence-page\":\n return \"page\"\n case \"pipeline-execution\":\n case \"aws.codepipeline.execution\":\n return \"pipeline-execution\"\n case \"deployment\":\n return \"deployment\"\n case \"time-entry\":\n case \"clockify.time-entry\":\n return \"time-entry\"\n default:\n return null\n }\n}\n\nconst reviewState = (\n value: string | null | undefined\n): \"approved\" | \"changes-requested\" | \"merged\" | \"not-requested\" | \"requested\" => {\n switch (value?.toLowerCase()) {\n case \"requested\":\n return \"requested\"\n case \"changes-requested\":\n case \"changes requested\":\n return \"changes-requested\"\n case \"approved\":\n return \"approved\"\n case \"merged\":\n return \"merged\"\n default:\n return \"not-requested\"\n }\n}\n\nconst pullRequestLifecycle = (value: string | null | undefined): \"closed\" | \"merged\" | \"open\" | null => {\n switch (value?.toLowerCase()) {\n case \"open\":\n return \"open\"\n case \"closed\":\n return \"closed\"\n case \"merged\":\n return \"merged\"\n default:\n return null\n }\n}\n\nconst isoDurationMinutes = (value: string | null | undefined): number => {\n if (value === null || value === undefined) return 0\n const match = /^PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?$/u.exec(value)\n if (match === null) return 0\n const hours = Number(match[1] ?? 0)\n const minutes = Number(match[2] ?? 0)\n const seconds = Number(match[3] ?? 0)\n return Math.max(0, Math.round(hours * 60 + minutes + seconds / 60))\n}\n\nconst entityPresentation = Effect.fn(\"NormalizedPluginPageMaterialization.entityPresentation\")(function*(\n event: EntityUpsert,\n kind: typeof DeliveryEntityKind.Type,\n siblingEvents: ReadonlyArray<NormalizedPluginEventV1>\n): Effect.fn.Return<\n { readonly details: DeliveryEntityDetails; readonly displayKey: string },\n NormalizedPluginPageMaterializationError\n> {\n const attributes = yield* decodedAttributes(event)\n switch (kind) {\n case \"issue\": {\n const issueAttributes = yield* decodedIssueAttributes(event)\n return {\n displayKey: issueAttributes.key,\n details: {\n _tag: \"issue\",\n ...issueAttributes\n }\n }\n }\n case \"pull-request\": {\n const creationDate = yield* decodedOptionalEntityTimestamp(\n attributes.creationDate,\n event.eventId,\n \"normalized-pull-request-timestamp-invalid\"\n )\n const lastActivityDate = yield* decodedOptionalEntityTimestamp(\n attributes.lastActivityDate,\n event.eventId,\n \"normalized-pull-request-timestamp-invalid\"\n )\n const status = namedText(attributes.status)\n return {\n displayKey: bounded(event.vendorImmutableId, event.vendorImmutableId, 200),\n details: {\n _tag: \"pull-request\",\n repository: bounded(attributes.repository, \"unknown\", 200),\n sourceBranch: bounded(attributes.sourceBranch, \"unknown\", 500),\n targetBranch: bounded(attributes.targetBranch, \"unknown\", 500),\n headRevision: bounded(attributes.headRevision, event.revision, 512),\n reviewState: reviewState(attributes.reviewState ?? (pullRequestLifecycle(status) === null ? status : null)),\n lifecycle: pullRequestLifecycle(status),\n description: optionalBounded(attributes.description, 50_000),\n authorReference: optionalBounded(attributes.authorArn, 512),\n baseRevision: optionalBounded(attributes.baseRevision, 512),\n mergeBaseRevision: optionalBounded(attributes.mergeBase, 512),\n createdAt: creationDate === null ? null : DateTime.formatIso(creationDate),\n updatedAt: lastActivityDate === null ? null : DateTime.formatIso(lastActivityDate)\n }\n }\n }\n case \"page\": {\n const normalizedPage = yield* decodedConfluencePageAttributes(event)\n return {\n displayKey: bounded(event.vendorImmutableId, event.vendorImmutableId, 200),\n details: {\n _tag: \"page\",\n spaceKey: bounded(attributes.spaceKey ?? attributes.spaceId, \"unknown\", 100),\n revision: bounded(\n attributes.currentVersion === null || attributes.currentVersion === undefined\n ? attributes.revision\n : String(attributes.currentVersion),\n event.revision,\n 512\n ),\n status: namedText(attributes.status)?.toLowerCase() === \"superseded\" ? \"superseded\" : \"current\",\n ...(attributes.linkedIssueKeys === undefined ? {} : {\n linkedIssueKeys: attributes.linkedIssueKeys\n .map((key) => key.trim())\n .filter((key, index, keys) => key.length > 0 && key.length <= 100 && keys.indexOf(key) === index)\n .slice(0, 100)\n }),\n ...(attributes.linkedReleaseVersions === undefined ? {} : {\n linkedReleaseVersions: attributes.linkedReleaseVersions\n .map((version) => version.trim())\n .filter(\n (version, index, versions) =>\n version.length > 0 && version.length <= 100 && versions.indexOf(version) === index\n )\n .slice(0, 100)\n }),\n ...(normalizedPage ?? {})\n }\n }\n }\n case \"pipeline-execution\": {\n const details = yield* projectPipelineExecution(event, siblingEvents).pipe(\n Effect.mapError((error) => malformed(error.diagnosticCode, error.eventId))\n )\n if (details._tag !== \"pipeline-execution\") {\n return yield* malformed(\"normalized-pipeline-details-kind-invalid\", event.eventId)\n }\n return {\n displayKey: bounded(`${details.pipelineName}/${details.executionId}`, details.executionId, 200),\n details\n }\n }\n case \"deployment\": {\n const environmentId = yield* Schema.decodeUnknownEffect(EnvironmentId)(attributes.environmentId).pipe(\n Effect.mapError(() => malformed(\"normalized-deployment-environment-invalid\", event.eventId))\n )\n const status = pipelineStatus(namedText(attributes.status))\n return {\n displayKey: bounded(event.vendorImmutableId, event.vendorImmutableId, 200),\n details: {\n _tag: \"deployment\",\n environmentId,\n revision: bounded(attributes.revision, event.revision, 512),\n status: status === \"queued\" ? \"pending\" : status === \"running\" ?\n \"deploying\" :\n status === \"stopped\"\n ? \"rolled-back\"\n : status\n }\n }\n }\n case \"time-entry\": {\n const startedAt = yield* decodedOptionalEntityTimestamp(\n attributes.interval?.start,\n event.eventId,\n \"normalized-time-entry-timestamp-invalid\"\n )\n const endedAt = yield* decodedOptionalEntityTimestamp(\n attributes.interval?.end,\n event.eventId,\n \"normalized-time-entry-timestamp-invalid\"\n )\n if (\n startedAt !== null &&\n endedAt !== null &&\n DateTime.Order(endedAt, startedAt) < 0\n ) return yield* malformed(\"normalized-time-entry-timestamp-invalid\", event.eventId)\n const userId = optionalBounded(attributes.userId, 512)\n const projectId = optionalBounded(attributes.projectId, 512)\n const intervalMinutes = startedAt === null || endedAt === null\n ? 0\n : (DateTime.toEpochMillis(endedAt) - DateTime.toEpochMillis(startedAt)) / 60_000\n const reportedMinutes = attributes.durationMinutes ?? (\n attributes.interval?.duration === null || attributes.interval?.duration === undefined\n ? intervalMinutes\n : isoDurationMinutes(attributes.interval.duration)\n )\n return {\n displayKey: bounded(event.vendorImmutableId, event.vendorImmutableId, 200),\n details: {\n _tag: \"time-entry\",\n durationMinutes: Math.max(\n 0,\n Math.round(reportedMinutes)\n ),\n billable: attributes.billable ?? false,\n approvalState: attributes.approvalState === \"approved\" || attributes.approvalState === \"rejected\"\n ? attributes.approvalState\n : attributes.interval?.state === \"running\"\n ? \"pending\"\n : \"not-required\",\n ...(typeof attributes.locked === \"boolean\" ? { locked: attributes.locked } : {}),\n description: optionalBounded(attributes.description, 4_000),\n projectId,\n ...(userId === null ? {} : { userId }),\n ...(startedAt === null ? {} : { startedAt }),\n endedAt\n }\n }\n }\n }\n})\n\nconst stableUuid = Effect.fn(\"NormalizedPluginPageMaterialization.stableUuid\")(function*(\n cryptoService: Crypto.Crypto,\n identity: string,\n eventId: string\n) {\n const bytes = yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(identity))).pipe(\n Effect.mapError(() => malformed(\"normalized-identity-encoding-failed\", eventId))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => malformed(\"normalized-identity-digest-failed\", eventId))\n )\n const hex = Encoding.encodeHex(digest)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n})\n\nconst sourceIdentity = (\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: typeof VendorImmutableId.Type\n) => ({\n pluginConnectionId: scope.pluginConnectionId,\n providerId: scope.providerId,\n vendorImmutableId\n})\n\nconst findEntity = Effect.fn(\"NormalizedPluginPageMaterialization.findEntity\")(function*(\n persistence: PersistenceService,\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: typeof VendorImmutableId.Type\n) {\n const found = yield* persistence.entities.findBySourceIdentity(\n scope.workspaceId,\n sourceIdentity(scope, vendorImmutableId)\n ).pipe(Effect.result)\n if (Result.isSuccess(found)) return found.success\n if (found.failure._tag === \"RecordNotFoundError\") return null\n return yield* found.failure\n})\n\nconst readProjection = Effect.fn(\"NormalizedPluginPageMaterialization.readProjection\")(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n entityId: EntityId\n) {\n const found = yield* persistence.deliveryGraph.read(workspaceId, {\n _tag: \"entityProjection\",\n entityId,\n revision: null\n }).pipe(Effect.result)\n if (Result.isSuccess(found)) {\n return found.success._tag === \"entityProjection\" ? found.success.value : null\n }\n if (found.failure._tag === \"RecordNotFoundError\") return null\n return yield* found.failure\n})\n\nconst materializationKey = (\n scope: NormalizedPluginPageMaterializationScope,\n kind: string,\n externalId: string\n) => `${scope.workspaceId}\\u0000${scope.pluginConnectionId}\\u0000${scope.providerId}\\u0000${kind}\\u0000${externalId}`\n\nconst entityIdFor = Effect.fn(\"NormalizedPluginPageMaterialization.entityIdFor\")(function*(\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: string,\n eventId: string\n) {\n return EntityId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"entity\", vendorImmutableId),\n eventId\n )\n )\n})\n\nconst nodeIdFor = Effect.fn(\"NormalizedPluginPageMaterialization.nodeIdFor\")(function*(\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: string,\n eventId: string\n) {\n return GraphNodeId.make(\n yield* stableUuid(cryptoService, materializationKey(scope, \"entity-node\", vendorImmutableId), eventId)\n )\n})\n\nconst releaseIdFor = Effect.fn(\"NormalizedPluginPageMaterialization.releaseIdFor\")(function*(\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: string,\n eventId: string\n) {\n return ReleaseId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"release\", vendorImmutableId),\n eventId\n )\n )\n})\n\nconst releaseNodeIdFor = Effect.fn(\"NormalizedPluginPageMaterialization.releaseNodeIdFor\")(function*(\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n vendorImmutableId: string,\n eventId: string\n) {\n return GraphNodeId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"release-node\", vendorImmutableId),\n eventId\n )\n )\n})\n\nconst sourceRevision = (\n scope: NormalizedPluginPageMaterializationScope,\n event: EntityUpsert | EntityTombstone,\n firstObservedAt: UtcTimestamp,\n sourceUrl: EntityUpsert[\"sourceUrl\"]\n) => ({\n ...sourceIdentity(scope, event.vendorImmutableId),\n revision: event.revision,\n sourceUrl,\n firstObservedAt,\n lastObservedAt: event.observedAt,\n synchronizedAt: scope.committedAt,\n normalizationSchemaVersion: NormalizationSchemaVersion.make(1)\n})\n\nconst laterTimestamp = (left: UtcTimestamp, right: UtcTimestamp): UtcTimestamp =>\n DateTime.Order(left, right) >= 0 ? left : right\n\nconst sameSourceUrl = (\n left: EntityUpsert[\"sourceUrl\"],\n right: EntityUpsert[\"sourceUrl\"]\n): boolean => left?.href === right?.href\n\nconst materializePipelineAuthority = Effect.fn(\n \"NormalizedPluginPageMaterialization.pipelineAuthority\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n event: EntityUpsert\n) {\n const existing = yield* findEntity(persistence, scope, event.vendorImmutableId)\n const entityId = existing?.entityId ??\n (yield* entityIdFor(cryptoService, scope, event.vendorImmutableId, event.eventId))\n const pipelineSourceRevision = {\n ...sourceRevision(scope, event, existing?.sourceRevision.firstObservedAt ?? event.observedAt, event.sourceUrl),\n synchronizedAt: laterTimestamp(scope.committedAt, event.observedAt)\n }\n if (existing === null) {\n yield* persistence.entities.create(scope.workspaceId, {\n entityId,\n entityType: \"pipeline\",\n sourceRevision: pipelineSourceRevision,\n createdAt: scope.committedAt\n })\n return\n }\n if (existing.entityType !== \"pipeline\") {\n return yield* malformed(\"normalized-pipeline-authority-kind-conflict\", event.eventId)\n }\n const refreshed = {\n ...pipelineSourceRevision,\n lastObservedAt: laterTimestamp(existing.sourceRevision.lastObservedAt, event.observedAt),\n synchronizedAt: laterTimestamp(existing.sourceRevision.synchronizedAt, pipelineSourceRevision.synchronizedAt)\n }\n if (\n existing.sourceRevision.revision === refreshed.revision &&\n sameSourceUrl(existing.sourceRevision.sourceUrl, refreshed.sourceUrl) &&\n DateTime.Equivalence(existing.sourceRevision.lastObservedAt, refreshed.lastObservedAt) &&\n DateTime.Equivalence(existing.sourceRevision.synchronizedAt, refreshed.synchronizedAt)\n ) return\n yield* persistence.entities.updateSourceRevision(scope.workspaceId, entityId, {\n sourceRevision: refreshed,\n expectedRevision: existing.revision,\n updatedAt: scope.committedAt\n })\n})\n\nconst projectionSchemaVersion = (kind: DeliveryEntityKind): number =>\n kind === \"time-entry\" ? 4 : kind === \"page\" || kind === \"pipeline-execution\" || kind === \"pull-request\" ? 2 : 1\n\nconst requiresMaterializationBackfill = Effect.fn(\n \"NormalizedPluginPageMaterialization.requiresMaterializationBackfill\"\n)(function*(\n persistence: PersistenceService,\n scope: NormalizedPluginPageMaterializationScope,\n event: EntityUpsert\n) {\n if (event.entityType === \"aws.codepipeline.pipeline\") {\n return (yield* findEntity(persistence, scope, event.vendorImmutableId)) === null\n }\n const kind = canonicalKind(event.entityType)\n if (kind !== \"time-entry\") return false\n const existing = yield* findEntity(persistence, scope, event.vendorImmutableId)\n if (existing === null || existing.sourceRevision.revision !== event.revision) return false\n const currentProjection = yield* readProjection(persistence, scope.workspaceId, existing.entityId)\n return currentProjection?.projection.entityState === \"present\" &&\n currentProjection.projection.projectionSchemaVersion < projectionSchemaVersion(kind)\n})\n\nconst mergedPageContributors = (\n current: PageDetails[\"contributors\"],\n incoming: PageDetails[\"contributors\"],\n incomingWatchersComplete: boolean\n): {\n readonly contributors: PageDetails[\"contributors\"]\n readonly watcherCoverageTruncated: boolean\n} => {\n if (current === undefined && incoming === undefined) {\n return { contributors: undefined, watcherCoverageTruncated: false }\n }\n const contributors = new Map<string, NonNullable<PageDetails[\"contributors\"]>[number]>()\n const merge = (contributor: NonNullable<PageDetails[\"contributors\"]>[number]): void => {\n const previous = contributors.get(contributor.sourcePersonId)\n const roles = previous === undefined\n ? contributor.roles\n : [...new Set([...previous.roles, ...contributor.roles])]\n const identity = previous?.resolved === true && !contributor.resolved ? previous : contributor\n contributors.set(\n contributor.sourcePersonId,\n { ...identity, roles }\n )\n }\n for (const contributor of current ?? []) {\n const roles = incomingWatchersComplete\n ? contributor.roles.filter((role) => role !== \"watcher\")\n : contributor.roles\n if (roles.length > 0) merge({ ...contributor, roles })\n }\n for (const contributor of incoming ?? []) merge(contributor)\n const prioritized = [...contributors.values()].sort((left, right) => {\n const leftWatcherOnly = left.roles.every((role) => role === \"watcher\")\n const rightWatcherOnly = right.roles.every((role) => role === \"watcher\")\n return Number(leftWatcherOnly) - Number(rightWatcherOnly)\n })\n const dropped = prioritized.slice(502)\n return {\n contributors: prioritized.slice(0, 502),\n watcherCoverageTruncated: dropped.some(({ roles }) => roles.every((role) => role === \"watcher\"))\n }\n}\n\nconst mergePartialPageAttachments = (\n current: PageDetails[\"attachments\"],\n incoming: PageDetails[\"attachments\"]\n): PageDetails[\"attachments\"] => {\n if (current === undefined) return incoming\n if (incoming === undefined) return current\n const incomingIds = new Set(incoming.map(({ id }) => id))\n return [...incoming, ...current.filter(({ id }) => !incomingIds.has(id))].slice(0, 50)\n}\n\nconst mergePartialPageVersions = (\n current: PageDetails[\"versions\"],\n incoming: PageDetails[\"versions\"]\n): PageDetails[\"versions\"] => {\n if (current === undefined) return incoming\n if (incoming === undefined) return current\n const versions = new Map(current.map((version) => [version.number, version]))\n for (const version of incoming) versions.set(version.number, version)\n return [...versions.values()].sort((left, right) => right.number - left.number).slice(0, 500)\n}\n\nconst pageRevisionNumber = (revision: PageDetails[\"revision\"]): number | null => {\n const versionNumber = Number(revision)\n return Number.isSafeInteger(versionNumber) && versionNumber > 0 ? versionNumber : null\n}\n\nconst accuratePageVersionHistory = (details: PageDetails): PageDetails => {\n if (details.versionHistory?.complete !== true) return details\n const currentVersionNumber = pageRevisionNumber(details.revision)\n if (\n currentVersionNumber === null ||\n details.versions?.some(({ number }) => number === currentVersionNumber) === true\n ) return details\n return { ...details, versionHistory: { ...details.versionHistory, complete: false } }\n}\n\nconst mergeCompletePageVersions = (\n current: PageDetails[\"versions\"],\n incoming: PageDetails[\"versions\"],\n versionHistory: PageDetails[\"versionHistory\"],\n currentRevision: PageDetails[\"revision\"]\n): {\n readonly versions: PageDetails[\"versions\"]\n readonly versionHistory: PageDetails[\"versionHistory\"]\n} => {\n if (current === undefined || incoming === undefined) return { versions: incoming, versionHistory }\n const currentVersionNumber = pageRevisionNumber(currentRevision)\n if (currentVersionNumber === null || incoming.some(({ number }) => number === currentVersionNumber)) {\n return { versions: incoming, versionHistory }\n }\n const currentVersion = current.find(({ number }) => number === currentVersionNumber)\n if (currentVersion === undefined) {\n return {\n versions: incoming,\n versionHistory: versionHistory === undefined ? undefined : { ...versionHistory, complete: false }\n }\n }\n const overflowed = incoming.length >= 500\n const versions = overflowed\n ? [\n currentVersion,\n ...[...incoming]\n .sort((left, right) => right.number - left.number)\n .slice(0, 499)\n ].sort((left, right) => right.number - left.number)\n : mergePartialPageVersions([currentVersion], incoming)\n return {\n versions,\n versionHistory: overflowed && versionHistory !== undefined\n ? { ...versionHistory, complete: false }\n : versionHistory\n }\n}\n\nconst mergeSameRevisionPageDetails = (current: PageDetails, incoming: PageDetails): PageDetails => {\n const contributorMerge = mergedPageContributors(\n current.contributors,\n incoming.contributors,\n incoming.watcherInventory?.complete === true\n )\n const preserveLoadedContent = current.contentState === \"loaded\" &&\n (incoming.contentState === \"lazy\" || incoming.content === null)\n const attachments = incoming.attachmentInventory?.complete === false\n ? mergePartialPageAttachments(current.attachments, incoming.attachments)\n : incoming.attachments\n const versionMerge = incoming.versionHistory?.complete === false\n ? {\n versions: mergePartialPageVersions(current.versions, incoming.versions),\n versionHistory: incoming.versionHistory\n }\n : mergeCompletePageVersions(\n current.versions,\n incoming.versions,\n incoming.versionHistory,\n incoming.revision\n )\n const watcherInventory = contributorMerge.watcherCoverageTruncated\n ? {\n complete: false,\n pagesFetched: incoming.watcherInventory?.pagesFetched ?? current.watcherInventory?.pagesFetched ?? 0\n }\n : incoming.watcherInventory\n const merged: PageDetails = {\n ...current,\n ...incoming,\n ...(contributorMerge.contributors === undefined ? {} : { contributors: contributorMerge.contributors }),\n ...(attachments === undefined ? {} : { attachments }),\n ...(versionMerge.versions === undefined ? {} : { versions: versionMerge.versions }),\n ...(versionMerge.versionHistory === undefined ? {} : { versionHistory: versionMerge.versionHistory }),\n ...(watcherInventory === undefined ? {} : { watcherInventory })\n }\n return preserveLoadedContent ? { ...merged, content: current.content ?? null, contentState: \"loaded\" } : merged\n}\n\nconst equivalentPageDetails = (left: PageDetails, right: PageDetails): boolean =>\n JSON.stringify(Schema.encodeSync(DeliveryEntityDetails)(left)) ===\n JSON.stringify(Schema.encodeSync(DeliveryEntityDetails)(right))\n\nconst CachedNormalizedPluginEvent = Schema.fromJsonString(NormalizedPluginEventV1)\n\nconst pipelineEventsFromCacheRecords = Effect.fn(\n \"NormalizedPluginPageMaterialization.pipelineEventsFromCacheRecords\"\n)(function*(\n records: ReadonlyArray<PluginCacheRecord>,\n eventId: string\n) {\n const groups = yield* Effect.forEach(\n records,\n (record) =>\n Effect.gen(function*() {\n if (record.state !== \"present\" || record.payloadJson === null) return []\n const cached = yield* Schema.decodeUnknownEffect(CachedNormalizedPluginEvent)(record.payloadJson).pipe(\n Effect.mapError(() => malformed(\"normalized-pipeline-cache-event-invalid\", eventId))\n )\n if (\n cached._tag !== \"UpsertEntity\" ||\n (cached.entityType !== \"aws.codepipeline.pipeline\" &&\n cached.entityType !== \"aws.codepipeline.execution\" &&\n cached.entityType !== \"aws.codepipeline.stage\" &&\n cached.entityType !== \"aws.codepipeline.action\")\n ) return []\n return [cached]\n }),\n { concurrency: 1 }\n )\n return groups.flat()\n})\n\nconst currentPipelineEvents = Effect.fn(\"NormalizedPluginPageMaterialization.currentPipelineEvents\")(function*(\n persistence: PersistenceService,\n scope: NormalizedPluginPageMaterializationScope,\n eventId: string,\n selectors: Parameters<PersistenceService[\"pluginRuntime\"][\"getCodePipelineCache\"]>[3]\n) {\n const records = yield* persistence.pluginRuntime.getCodePipelineCache(\n scope.workspaceId,\n scope.pluginConnectionId,\n scope.streamKey,\n selectors\n )\n return yield* pipelineEventsFromCacheRecords(records, eventId)\n})\n\nconst writeGraph = Effect.fn(\"NormalizedPluginPageMaterialization.writeGraph\")(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n batch: typeof DeliveryGraphWriteBatch.Type,\n eventId: string\n) {\n const encoded = yield* Schema.encodeEffect(DeliveryGraphWriteBatch)(batch).pipe(\n Effect.mapError(() => malformed(\"normalized-delivery-graph-batch-invalid\", eventId))\n )\n return yield* persistence.deliveryGraph.write(workspaceId, encoded)\n})\n\nconst reconcileTimeEntryContributor = Effect.fn(\n \"NormalizedPluginPageMaterialization.reconcileTimeEntryContributor\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n entityId: EntityId,\n userId: string,\n eventId: string,\n roleAssignments: Map<RoleAssignmentId, RoleAssignmentRecord>\n) {\n const identity = {\n pluginConnectionId: scope.pluginConnectionId,\n providerId: scope.providerId,\n vendorPersonId: VendorImmutableId.make(userId)\n }\n const person = yield* persistence.people.findPersonBySourceIdentity(scope.workspaceId, identity).pipe(Effect.result)\n if (Result.isFailure(person) && person.failure._tag !== \"RecordNotFoundError\") return yield* person.failure\n for (const record of roleAssignments.values()) {\n const assignment = record.assignment\n if (\n assignment.role !== \"contributor\" ||\n assignment.scope._tag !== \"entity\" ||\n assignment.scope.entityId !== entityId ||\n assignment.lifecycle._tag !== \"active\" ||\n assignment.actor._tag !== \"human\" ||\n (Result.isSuccess(person) &&\n person.success.person.isActive &&\n assignment.actor.personId === person.success.person.personId)\n ) continue\n const providerManagedAssignmentId = RoleAssignmentId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"role-assignment\", `${entityId}:contributor:${assignment.actor.personId}`),\n eventId\n )\n )\n if (assignment.assignmentId !== providerManagedAssignmentId) continue\n const updated = yield* persistence.people.updateRoleAssignment(\n scope.workspaceId,\n {\n ...assignment,\n lifecycle: {\n _tag: \"ended\",\n assignedAt: assignment.lifecycle.assignedAt,\n endedAt: laterTimestamp(assignment.lifecycle.assignedAt, scope.committedAt)\n }\n },\n record.revision,\n scope.committedAt\n )\n roleAssignments.set(updated.assignment.assignmentId, updated)\n }\n if (Result.isFailure(person) || !person.success.person.isActive) return\n const assignmentId = RoleAssignmentId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"role-assignment\", `${entityId}:contributor:${person.success.person.personId}`),\n eventId\n )\n )\n const existingAssignment = yield* persistence.people.getRoleAssignment(scope.workspaceId, assignmentId).pipe(\n Effect.result\n )\n if (Result.isFailure(existingAssignment) && existingAssignment.failure._tag !== \"RecordNotFoundError\") {\n return yield* existingAssignment.failure\n }\n if (Result.isSuccess(existingAssignment) && existingAssignment.success.assignment.lifecycle._tag !== \"active\") {\n const updated = yield* persistence.people.updateRoleAssignment(\n scope.workspaceId,\n {\n ...existingAssignment.success.assignment,\n lifecycle: { _tag: \"active\", assignedAt: scope.committedAt }\n },\n existingAssignment.success.revision,\n scope.committedAt\n )\n roleAssignments.set(updated.assignment.assignmentId, updated)\n } else if (Result.isFailure(existingAssignment)) {\n const assignment = yield* Schema.decodeUnknownEffect(Schema.toType(RoleAssignment))({\n actor: { _tag: \"human\", personId: person.success.person.personId },\n assignmentId,\n lifecycle: { _tag: \"active\", assignedAt: scope.committedAt },\n role: \"contributor\",\n scope: { _tag: \"entity\", entityId, workspaceId: scope.workspaceId }\n }).pipe(Effect.mapError(() => malformed(\"normalized-time-entry-contributor-invalid\", eventId)))\n const created = yield* persistence.people.createRoleAssignment(scope.workspaceId, assignment, scope.committedAt)\n roleAssignments.set(created.assignment.assignmentId, created)\n }\n})\n\nconst materializeUpsertEntity = Effect.fn(\n \"NormalizedPluginPageMaterialization.upsertEntity\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n event: EntityUpsert,\n siblingEvents: ReadonlyArray<NormalizedPluginEventV1>,\n forceProjection: boolean,\n preserveSourceRevision: boolean,\n roleAssignments: Map<RoleAssignmentId, RoleAssignmentRecord>\n) {\n const kind = canonicalKind(event.entityType)\n if (kind === null) return { entityProjectionCount: 0, nodeCount: 0, skippedEntityCount: 1 }\n const existing = yield* findEntity(persistence, scope, event.vendorImmutableId)\n const presentation = yield* entityPresentation(event, kind, siblingEvents)\n const entityId = existing?.entityId ??\n (yield* entityIdFor(cryptoService, scope, event.vendorImmutableId, event.eventId))\n const currentProjection = existing === null\n ? null\n : yield* readProjection(persistence, scope.workspaceId, entityId)\n const currentDetails = currentProjection?.projection.details\n const sameRevisionPage = existing?.sourceRevision.revision === event.revision &&\n presentation.details._tag === \"page\" &&\n currentDetails?._tag === \"page\" &&\n currentProjection?.projection.entityState === \"present\"\n const effectivePresentation =\n sameRevisionPage && currentDetails?._tag === \"page\" && presentation.details._tag === \"page\"\n ? { ...presentation, details: mergeSameRevisionPageDetails(currentDetails, presentation.details) }\n : presentation.details._tag === \"page\"\n ? { ...presentation, details: accuratePageVersionHistory(presentation.details) }\n : presentation\n const pageEnrichment = sameRevisionPage &&\n currentDetails?._tag === \"page\" &&\n effectivePresentation.details._tag === \"page\" &&\n !equivalentPageDetails(currentDetails, effectivePresentation.details)\n const effectiveForceProjection = forceProjection || pageEnrichment\n const schemaVersion = projectionSchemaVersion(kind)\n const refreshedSource = existing === null\n ? null\n : {\n ...sourceRevision(\n scope,\n event,\n existing.sourceRevision.firstObservedAt,\n event.sourceUrl\n ),\n lastObservedAt: laterTimestamp(existing.sourceRevision.lastObservedAt, event.observedAt),\n synchronizedAt: laterTimestamp(existing.sourceRevision.synchronizedAt, scope.committedAt)\n }\n const sourceMetadataChanged = existing !== null && refreshedSource !== null && (\n !sameSourceUrl(existing.sourceRevision.sourceUrl, refreshedSource.sourceUrl) ||\n !DateTime.Equivalence(existing.sourceRevision.lastObservedAt, refreshedSource.lastObservedAt) ||\n !DateTime.Equivalence(existing.sourceRevision.synchronizedAt, refreshedSource.synchronizedAt)\n )\n if (\n existing !== null &&\n existing.sourceRevision.revision === event.revision &&\n currentProjection?.projection.entityState === \"present\" &&\n currentProjection.projection.projectionSchemaVersion === schemaVersion &&\n !sourceMetadataChanged &&\n !effectiveForceProjection\n ) {\n if (effectivePresentation.details._tag === \"time-entry\" && effectivePresentation.details.userId !== undefined) {\n yield* reconcileTimeEntryContributor(\n persistence,\n cryptoService,\n scope,\n entityId,\n effectivePresentation.details.userId,\n event.eventId,\n roleAssignments\n )\n }\n return { entityProjectionCount: 0, nodeCount: 0, skippedEntityCount: 0 }\n }\n\n const persisted = existing === null\n ? yield* persistence.entities.create(scope.workspaceId, {\n entityId,\n entityType: kind,\n sourceRevision: sourceRevision(scope, event, event.observedAt, event.sourceUrl),\n createdAt: scope.committedAt\n })\n : preserveSourceRevision && existing.sourceRevision.revision === event.revision\n ? existing\n : effectiveForceProjection && existing.sourceRevision.revision === event.revision && !sourceMetadataChanged\n ? existing\n : yield* persistence.entities.updateSourceRevision(scope.workspaceId, entityId, {\n sourceRevision: refreshedSource ?? sourceRevision(\n scope,\n event,\n existing.sourceRevision.firstObservedAt,\n event.sourceUrl\n ),\n expectedRevision: existing.revision,\n updatedAt: scope.committedAt\n })\n const projectionRevision = LedgerRevision.make((currentProjection?.projection.projectionRevision ?? 0) + 1)\n const nodeId = yield* nodeIdFor(cryptoService, scope, event.vendorImmutableId, event.eventId)\n const batch = {\n entityProjections: [{\n projection: {\n workspaceId: scope.workspaceId,\n entityId,\n projectionRevision,\n sourceEntityRevision: LedgerRevision.make(persisted.revision),\n supersedesProjectionRevision: currentProjection?.projection.projectionRevision ?? null,\n projectionSchemaVersion: schemaVersion,\n entityState: \"present\",\n entityType: kind,\n displayKey: effectivePresentation.displayKey,\n title: event.title,\n details: effectivePresentation.details\n },\n recordedAt: scope.committedAt\n }],\n nodes: currentProjection === null\n ? [{\n workspaceId: scope.workspaceId,\n nodeId,\n endpointKind: kind,\n resolution: { _tag: \"resolved\", target: { _tag: \"entity\", entityId, entityKind: kind } },\n createdAt: scope.committedAt\n }]\n : [],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: []\n } satisfies typeof DeliveryGraphWriteBatch.Type\n const receipt = yield* writeGraph(persistence, scope.workspaceId, batch, event.eventId)\n if (effectivePresentation.details._tag === \"time-entry\" && effectivePresentation.details.userId !== undefined) {\n yield* reconcileTimeEntryContributor(\n persistence,\n cryptoService,\n scope,\n entityId,\n effectivePresentation.details.userId,\n event.eventId,\n roleAssignments\n )\n }\n return { ...receipt, skippedEntityCount: 0 }\n})\n\nconst materializeRelease = Effect.fn(\"NormalizedPluginPageMaterialization.upsertRelease\")(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n settings: WorkspaceSettingsV1,\n event: EntityUpsert\n) {\n const attributes = yield* Schema.decodeUnknownEffect(ReleaseAttributes)(event.attributes).pipe(\n Effect.mapError(() => malformed(\"normalized-release-attributes-invalid\", event.eventId))\n )\n const releaseId = yield* releaseIdFor(cryptoService, scope, event.vendorImmutableId, event.eventId)\n const existing = yield* persistence.releases.get(scope.workspaceId, releaseId).pipe(Effect.result)\n if (Result.isFailure(existing) && existing.failure._tag !== \"RecordNotFoundError\") {\n return yield* existing.failure\n }\n const previous = Result.isSuccess(existing) ? existing.success : null\n const previousSource = previous?.release.sourceRevisions.find(\n ({ pluginConnectionId, providerId, vendorImmutableId }) =>\n pluginConnectionId === scope.pluginConnectionId &&\n providerId === scope.providerId &&\n vendorImmutableId === event.vendorImmutableId\n )\n const observedAt = previousSource === undefined\n ? event.observedAt\n : laterTimestamp(previousSource.lastObservedAt, event.observedAt)\n const source = sourceRevision(\n scope,\n event,\n previousSource?.firstObservedAt ?? event.observedAt,\n event.sourceUrl\n )\n const refreshedSource = { ...source, lastObservedAt: observedAt }\n const sourceAgeSeconds = Math.max(\n 0,\n (DateTime.toEpochMillis(scope.committedAt) - DateTime.toEpochMillis(observedAt)) / 1_000\n )\n const staleAfterSeconds = settings.synchronization.staleAfterMinutes * 60\n const freshness: Freshness = sourceAgeSeconds < staleAfterSeconds\n ? {\n _tag: \"current\",\n evaluatedAt: scope.committedAt,\n pluginHealth: scope.successfulHealth,\n provenance: { _tag: \"provider\", sourceRevision: refreshedSource },\n sourceObservedAt: observedAt,\n staleAfterSeconds,\n synchronizedAt: scope.committedAt\n }\n : {\n _tag: \"stale\",\n evaluatedAt: scope.committedAt,\n pluginHealth: scope.successfulHealth,\n provenance: {\n _tag: \"cache\",\n cachedAt: refreshedSource.synchronizedAt,\n sourceRevision: refreshedSource\n },\n sourceObservedAt: observedAt,\n staleAfterSeconds,\n synchronizedAt: scope.committedAt\n }\n const release = yield* Schema.decodeUnknownEffect(Schema.toType(Release))({\n createdAt: previous?.release.createdAt ?? event.observedAt,\n freshness,\n id: releaseId,\n lifecycle: attributes.lifecycle,\n relay: deriveReleaseRelay(releaseId),\n roleAssignments: previous?.release.roleAssignments ?? [],\n serviceName: attributes.serviceName,\n sourceRevisions: [\n ...(previous?.release.sourceRevisions.filter(\n ({ pluginConnectionId, providerId, vendorImmutableId }) =>\n pluginConnectionId !== scope.pluginConnectionId ||\n providerId !== scope.providerId ||\n vendorImmutableId !== event.vendorImmutableId\n ) ?? []),\n refreshedSource\n ],\n targetEnvironmentIds: previous?.release.targetEnvironmentIds ?? [],\n updatedAt: scope.committedAt,\n version: attributes.version,\n workspaceId: scope.workspaceId\n }).pipe(Effect.mapError(() => malformed(\"normalized-release-invalid\", event.eventId)))\n if (previous === null) {\n yield* persistence.releases.create(scope.workspaceId, release)\n } else if (\n previousSource === undefined ||\n previousSource.revision !== refreshedSource.revision ||\n !sameSourceUrl(previousSource.sourceUrl, refreshedSource.sourceUrl) ||\n !DateTime.Equivalence(previousSource.lastObservedAt, refreshedSource.lastObservedAt) ||\n !DateTime.Equivalence(previousSource.synchronizedAt, refreshedSource.synchronizedAt) ||\n previous.release.serviceName !== release.serviceName ||\n previous.release.version !== release.version ||\n previous.release.lifecycle !== release.lifecycle\n ) {\n yield* persistence.releases.append(scope.workspaceId, release, previous.revision)\n }\n const nodeId = yield* releaseNodeIdFor(cryptoService, scope, event.vendorImmutableId, event.eventId)\n const existingNode = yield* persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"node\",\n nodeId\n }).pipe(Effect.result)\n if (Result.isSuccess(existingNode)) return { nodeCount: 0 }\n if (existingNode.failure._tag !== \"RecordNotFoundError\") return yield* existingNode.failure\n const receipt = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: [{\n workspaceId: scope.workspaceId,\n nodeId,\n endpointKind: \"release\",\n resolution: { _tag: \"resolved\", target: { _tag: \"release\", releaseId } },\n createdAt: scope.committedAt\n }],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: []\n }, event.eventId)\n return { nodeCount: receipt.nodeCount }\n})\n\nconst materializeTombstoneEntity = Effect.fn(\n \"NormalizedPluginPageMaterialization.tombstoneEntity\"\n)(function*(\n persistence: PersistenceService,\n scope: NormalizedPluginPageMaterializationScope,\n event: EntityTombstone\n) {\n const existing = yield* findEntity(persistence, scope, event.vendorImmutableId)\n if (existing === null) return { entityProjectionCount: 0 }\n const current = yield* readProjection(persistence, scope.workspaceId, existing.entityId)\n if (current === null) return yield* malformed(\"normalized-tombstone-projection-missing\", event.eventId)\n if (existing.sourceRevision.revision === event.revision && current.projection.entityState === \"deleted\") {\n return { entityProjectionCount: 0 }\n }\n const persisted = existing.sourceRevision.revision === event.revision\n ? existing\n : yield* persistence.entities.updateSourceRevision(scope.workspaceId, existing.entityId, {\n sourceRevision: sourceRevision(\n scope,\n event,\n existing.sourceRevision.firstObservedAt,\n existing.sourceRevision.sourceUrl\n ),\n expectedRevision: existing.revision,\n updatedAt: scope.committedAt\n })\n const projectionRevision = LedgerRevision.make(current.projection.projectionRevision + 1)\n const receipt = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [{\n projection: {\n ...current.projection,\n projectionRevision,\n sourceEntityRevision: LedgerRevision.make(persisted.revision),\n supersedesProjectionRevision: current.projection.projectionRevision,\n entityState: \"deleted\"\n },\n recordedAt: scope.committedAt\n }],\n nodes: [],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: []\n }, event.eventId)\n return { entityProjectionCount: receipt.entityProjectionCount }\n})\n\nconst materializePerson = Effect.fn(\"NormalizedPluginPageMaterialization.upsertPerson\")(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n event: PersonUpsert\n) {\n const identity = {\n pluginConnectionId: scope.pluginConnectionId,\n providerId: scope.providerId,\n vendorPersonId: VendorImmutableId.make(event.vendorPersonId)\n }\n const existing = yield* persistence.people.findPersonBySourceIdentity(scope.workspaceId, identity).pipe(\n Effect.result\n )\n if (Result.isFailure(existing) && existing.failure._tag !== \"RecordNotFoundError\") {\n return yield* existing.failure\n }\n const personId = Result.isSuccess(existing)\n ? existing.success.person.personId\n : PersonId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"person\", event.vendorPersonId),\n event.eventId\n )\n )\n const avatar = event.avatarUrl !== null && event.avatarUrl.toString().length <= 500\n ? { _tag: \"reference\", reference: event.avatarUrl.toString() }\n : { _tag: \"initials\", text: derivePersonInitials(event.displayName) }\n const person = yield* Schema.decodeUnknownEffect(Schema.toType(Person))({\n personId,\n displayName: event.displayName,\n avatar,\n isActive: event.active,\n sourceIdentities: Result.isSuccess(existing) ? existing.success.person.sourceIdentities : [identity]\n }).pipe(Effect.mapError(() => malformed(\"normalized-person-invalid\", event.eventId)))\n if (\n Result.isSuccess(existing) &&\n existing.success.person.displayName === person.displayName &&\n existing.success.person.isActive === person.isActive &&\n existing.success.person.avatar._tag === person.avatar._tag &&\n (existing.success.person.avatar._tag === \"initials\"\n ? existing.success.person.avatar.text === (person.avatar._tag === \"initials\" ? person.avatar.text : \"\")\n : existing.success.person.avatar.reference ===\n (person.avatar._tag === \"reference\" ? person.avatar.reference : \"\"))\n ) {\n return 0\n }\n if (Result.isSuccess(existing)) {\n yield* persistence.people.updatePerson(\n scope.workspaceId,\n person,\n existing.success.revision,\n scope.committedAt\n )\n } else {\n yield* persistence.people.createPerson(scope.workspaceId, person, scope.committedAt)\n }\n return 1\n})\n\nconst sequenceClockifyPersonEvents = Effect.fn(\n \"NormalizedPluginPageMaterialization.sequenceClockifyPersonEvents\"\n)(function*(\n persistence: PersistenceService,\n scope: NormalizedPluginPageMaterializationScope,\n page: PluginSyncPageV1\n) {\n if (scope.providerId !== \"clockify\") return page\n const events = yield* Effect.forEach(\n page.events,\n (event) =>\n Effect.gen(function*() {\n if (event._tag !== \"UpsertPerson\") return event\n const existing = yield* persistence.people.findPersonBySourceIdentity(scope.workspaceId, {\n pluginConnectionId: scope.pluginConnectionId,\n providerId: scope.providerId,\n vendorPersonId: VendorImmutableId.make(event.vendorPersonId)\n }).pipe(Effect.result)\n if (Result.isFailure(existing) && existing.failure._tag !== \"RecordNotFoundError\") {\n return yield* existing.failure\n }\n const nextRevision = Result.isFailure(existing)\n ? 1\n : existing.success.revision + (\n existing.success.person.displayName === event.displayName &&\n existing.success.person.isActive === event.active\n ? 0\n : 1\n )\n const eventId = yield* Schema.decodeUnknownEffect(PluginEventId)(\n `${event.eventId}:person-revision:${nextRevision}`\n ).pipe(Effect.mapError(() => malformed(\"normalized-clockify-person-event-id-invalid\", event.eventId)))\n return { ...event, eventId }\n }),\n { concurrency: 1 }\n )\n return { ...page, events }\n})\n\nconst evidencePredicate = (event: EvidenceAppend): typeof EvidencePredicate.Type => {\n const decoded = Schema.decodeUnknownResult(EvidencePredicate)(event.evidenceType)\n if (Result.isSuccess(decoded)) return decoded.success\n return \"status-observed\"\n}\n\nconst materializeEvidence = Effect.fn(\"NormalizedPluginPageMaterialization.appendEvidence\")(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n settings: WorkspaceSettingsV1,\n event: EvidenceAppend\n) {\n const subject = yield* findEntity(persistence, scope, event.subject.vendorImmutableId)\n if (subject === null) return yield* malformed(\"normalized-evidence-subject-missing\", event.eventId)\n const subjectKind = canonicalKind(event.subject.entityType)\n if (subjectKind === null) return yield* malformed(\"normalized-evidence-subject-unsupported\", event.eventId)\n const nodeId = yield* nodeIdFor(cryptoService, scope, event.subject.vendorImmutableId, event.eventId)\n const evidenceId = EvidenceId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"evidence\", event.evidenceId),\n event.eventId\n )\n )\n const evidenceClaimId = EvidenceClaimId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"evidence-claim\", event.evidenceId),\n event.eventId\n )\n )\n const decodedData = Schema.decodeUnknownResult(EvidenceData)(event.data)\n const predicate = Result.isSuccess(decodedData) && decodedData.success.predicate !== undefined\n ? decodedData.success.predicate\n : evidencePredicate(event)\n const value: typeof EvidenceValue.Type = Result.isSuccess(decodedData) && decodedData.success.value !== undefined\n ? decodedData.success.value\n : { _tag: \"state\", value: event.summary }\n const source = subject.sourceRevision\n const ageSeconds = Math.max(\n 0,\n (DateTime.toEpochMillis(scope.committedAt) - DateTime.toEpochMillis(source.lastObservedAt)) / 1_000\n )\n const health: Extract<PluginHealth, { readonly _tag: \"degraded\" | \"healthy\" }> =\n scope.successfulHealth._tag === \"healthy\"\n ? { _tag: \"healthy\", checkedAt: scope.committedAt }\n : { ...scope.successfulHealth, checkedAt: scope.committedAt }\n const staleAfterSeconds = settings.synchronization.staleAfterMinutes * 60\n const freshness: Freshness = ageSeconds < staleAfterSeconds\n ? {\n _tag: \"current\",\n evaluatedAt: scope.committedAt,\n pluginHealth: health,\n provenance: { _tag: \"provider\", sourceRevision: source },\n sourceObservedAt: source.lastObservedAt,\n staleAfterSeconds,\n synchronizedAt: scope.committedAt\n }\n : {\n _tag: \"stale\",\n evaluatedAt: scope.committedAt,\n pluginHealth: health,\n provenance: {\n _tag: \"cache\",\n cachedAt: source.synchronizedAt,\n sourceRevision: source\n },\n sourceObservedAt: source.lastObservedAt,\n staleAfterSeconds,\n synchronizedAt: scope.committedAt\n }\n const receipt = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: [],\n evidenceItems: [{\n workspaceId: scope.workspaceId,\n evidenceId,\n schemaVersion: 1,\n attribution: {\n _tag: \"plugin\",\n pluginConnectionId: scope.pluginConnectionId,\n sourceEntityId: subject.entityId,\n sourceEntityRevision: LedgerRevision.make(subject.revision)\n },\n verifier: { _tag: \"system\", component: \"normalized-plugin-page-materializer\" },\n observedAt: event.capturedAt,\n recordedAt: scope.committedAt,\n validUntil: null,\n freshness,\n retention: {\n classification: \"evidence\",\n retainUntil: DateTime.add(scope.committedAt, {\n days: settings.retention.evidenceDays\n }),\n legalHold: false\n }\n }],\n evidenceClaims: [{\n workspaceId: scope.workspaceId,\n evidenceClaimId,\n evidenceId,\n subjectNodeId: nodeId,\n predicate,\n value,\n recordedAt: scope.committedAt,\n supersedesEvidenceClaimId: null\n }],\n relationships: []\n }, event.eventId)\n return {\n evidenceItemCount: receipt.evidenceItemCount,\n evidenceClaimCount: receipt.evidenceClaimCount\n }\n})\n\nconst materializeRelationship = Effect.fn(\n \"NormalizedPluginPageMaterialization.proposeRelationship\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n event: RelationshipProposal\n) {\n const resolveEndpoint = Effect.fn(\"NormalizedPluginPageMaterialization.resolveRelationshipEndpoint\")(function*(\n reference: RelationshipProposal[\"from\"]\n ) {\n if (reference.entityType === \"release\") {\n const releaseId = yield* releaseIdFor(cryptoService, scope, reference.vendorImmutableId, event.eventId)\n const release = yield* persistence.releases.get(scope.workspaceId, releaseId).pipe(Effect.result)\n if (Result.isFailure(release)) {\n if (release.failure._tag === \"RecordNotFoundError\") {\n return yield* malformed(\"normalized-relationship-endpoint-missing\", event.eventId)\n }\n return yield* release.failure\n }\n const nodeId = yield* releaseNodeIdFor(cryptoService, scope, reference.vendorImmutableId, event.eventId)\n const existingNode = yield* persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"node\",\n nodeId\n }).pipe(Effect.result)\n if (Result.isFailure(existingNode) && existingNode.failure._tag !== \"RecordNotFoundError\") {\n return yield* existingNode.failure\n }\n return {\n entity: null,\n kind: \"release\",\n node: Result.isSuccess(existingNode)\n ? null\n : {\n workspaceId: scope.workspaceId,\n nodeId,\n endpointKind: \"release\",\n resolution: { _tag: \"resolved\", target: { _tag: \"release\", releaseId } },\n createdAt: scope.committedAt\n },\n nodeId,\n releaseId\n } satisfies RelationshipEndpointResolution\n }\n const entity = yield* findEntity(persistence, scope, reference.vendorImmutableId)\n const kind = canonicalKind(reference.entityType)\n if (entity === null) return yield* malformed(\"normalized-relationship-endpoint-missing\", event.eventId)\n if (kind === null) return yield* malformed(\"normalized-relationship-endpoint-unsupported\", event.eventId)\n return {\n entity,\n kind,\n node: null,\n nodeId: yield* nodeIdFor(cryptoService, scope, reference.vendorImmutableId, event.eventId),\n releaseId: null\n } satisfies RelationshipEndpointResolution\n })\n const source = yield* resolveEndpoint(event.from)\n const target = yield* resolveEndpoint(event.to)\n const kind = yield* Schema.decodeUnknownEffect(RelationshipKind)(event.relationshipType).pipe(\n Effect.mapError(() => malformed(\"normalized-relationship-kind-invalid\", event.eventId))\n )\n const provenanceEntity = source.entity ?? target.entity\n if (provenanceEntity === null) {\n return yield* malformed(\"normalized-relationship-provenance-entity-missing\", event.eventId)\n }\n const relationshipScope: DeliveryRelationship[\"scope\"] = source.releaseId !== null\n ? { _tag: \"release\", releaseId: source.releaseId }\n : null\n const relationshipId = RelationshipId.make(\n yield* stableUuid(\n cryptoService,\n materializationKey(scope, \"relationship\", event.relationshipId),\n event.eventId\n )\n )\n const existing = yield* persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"relationship\",\n relationshipId,\n revision: null\n }).pipe(Effect.result)\n if (Result.isFailure(existing) && existing.failure._tag !== \"RecordNotFoundError\") {\n return yield* existing.failure\n }\n const previous = Result.isSuccess(existing) && existing.success._tag === \"relationship\"\n ? existing.success.value\n : null\n const revision = LedgerRevision.make((previous?.revision ?? 0) + 1)\n const nodes: Array<DeliveryNode> = []\n if (source.node !== null) nodes.push(source.node)\n if (target.node !== null && target.node.nodeId !== source.nodeId) nodes.push(target.node)\n const receipt = yield* writeGraph(\n persistence,\n scope.workspaceId,\n {\n entityProjections: [],\n nodes,\n evidenceItems: [],\n evidenceClaims: [],\n relationships: [\n {\n workspaceId: scope.workspaceId,\n relationshipId,\n relationshipSchemaVersion: 1,\n revision,\n supersedesRevision: previous?.revision ?? null,\n kind,\n sourceNodeId: source.nodeId,\n sourceNodeKind: source.kind,\n targetNodeId: target.nodeId,\n targetNodeKind: target.kind,\n scope: relationshipScope,\n lifecycle: { _tag: \"proposed\", effectiveAt: event.observedAt },\n confidence: {\n _tag: \"inferred\",\n score: event.confidence,\n rationale: `Proposed by ${scope.providerId} normalized synchronization.`\n },\n provenance: {\n _tag: \"plugin\",\n pluginConnectionId: scope.pluginConnectionId,\n sourceEntityId: provenanceEntity.entityId,\n sourceEntityRevision: LedgerRevision.make(provenanceEntity.revision)\n },\n recordedBy: { _tag: \"system\", component: \"normalized-plugin-page-materializer\" },\n evidenceClaimIds: yield* Effect.forEach(\n event.evidenceIds,\n (evidenceId) =>\n stableUuid(cryptoService, materializationKey(scope, \"evidence-claim\", evidenceId), event.eventId).pipe(\n Effect.map(EvidenceClaimId.make)\n )\n ),\n recordedAt: scope.committedAt\n }\n ]\n },\n event.eventId\n )\n return { nodeCount: receipt.nodeCount, relationshipCount: receipt.relationshipCount }\n})\n\nconst hasAuthoritativeJiraFixVersions = (event: NormalizedPluginEventV1): event is EntityUpsert => {\n if (event._tag !== \"UpsertEntity\" || event.entityType !== \"jira.issue\") return false\n const snapshot = Schema.decodeUnknownResult(JiraIssueRelationshipSnapshot)(event.attributes)\n return Result.isSuccess(snapshot) && !snapshot.success.truncatedFields.includes(\"fixVersions\")\n}\n\nconst isReleaseContainmentForIssue = (\n event: NormalizedPluginEventV1,\n issue: EntityUpsert\n): event is RelationshipProposal =>\n event._tag === \"ProposeRelationship\" &&\n event.relationshipType === \"contains\" &&\n event.from.entityType === \"release\" &&\n event.to.entityType === issue.entityType &&\n event.to.vendorImmutableId === issue.vendorImmutableId\n\nconst retireMissingJiraReleaseContainments = Effect.fn(\n \"NormalizedPluginPageMaterialization.retireMissingJiraReleaseContainments\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n scope: NormalizedPluginPageMaterializationScope,\n acceptedEvents: ReadonlyArray<NormalizedPluginEventV1>\n) {\n let relationshipCount = 0\n for (const issue of acceptedEvents) {\n if (!hasAuthoritativeJiraFixVersions(issue)) continue\n const source = yield* findEntity(persistence, scope, issue.vendorImmutableId)\n if (source === null) return yield* malformed(\"normalized-relationship-endpoint-missing\", issue.eventId)\n const issueNodeId = yield* nodeIdFor(cryptoService, scope, issue.vendorImmutableId, issue.eventId)\n const neighborhood = yield* persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"nodeRelationships\",\n nodeId: issueNodeId,\n limit: 500\n })\n if (neighborhood._tag !== \"nodeRelationships\") continue\n if (neighborhood.value.truncated) {\n return yield* malformed(\"normalized-jira-containment-neighborhood-truncated\", issue.eventId)\n }\n const currentRelationshipIds = new Set(\n yield* Effect.forEach(\n acceptedEvents.filter((event) => isReleaseContainmentForIssue(event, issue)),\n ({ relationshipId }) =>\n stableUuid(\n cryptoService,\n materializationKey(scope, \"relationship\", relationshipId),\n issue.eventId\n ).pipe(Effect.map(RelationshipId.make))\n )\n )\n const removed = neighborhood.value.relationships.filter(\n (relationship) =>\n relationship.kind === \"contains\" &&\n relationship.sourceNodeKind === \"release\" &&\n relationship.targetNodeId === issueNodeId &&\n relationship.targetNodeKind === \"issue\" &&\n relationship.provenance._tag === \"plugin\" &&\n relationship.provenance.pluginConnectionId === scope.pluginConnectionId &&\n relationship.provenance.sourceEntityId === source.entityId &&\n !currentRelationshipIds.has(relationship.relationshipId)\n )\n if (removed.length === 0) continue\n\n for (const previous of removed) {\n if (previous.lifecycle._tag === \"rejected\" || previous.lifecycle._tag === \"superseded\") continue\n const receipt = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: [],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: [{\n ...previous,\n revision: LedgerRevision.make(previous.revision + 1),\n supersedesRevision: previous.revision,\n lifecycle: {\n _tag: \"superseded\",\n effectiveAt: issue.observedAt,\n reason: \"No longer present in the latest Jira fixVersion observation.\"\n },\n provenance: {\n _tag: \"plugin\",\n pluginConnectionId: scope.pluginConnectionId,\n sourceEntityId: source.entityId,\n sourceEntityRevision: LedgerRevision.make(source.revision)\n },\n recordedBy: { _tag: \"system\", component: \"normalized-plugin-page-materializer\" },\n recordedAt: scope.committedAt\n }]\n }, issue.eventId)\n relationshipCount += receipt.relationshipCount\n }\n }\n return relationshipCount\n})\n\n/** Host authority supplied separately from provider-controlled normalized data. */\nexport interface NormalizedPluginPageMaterializationScope {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly streamKey: PluginStreamKey\n readonly expectedRevision: number\n readonly committedAt: UtcTimestamp\n readonly successfulHealth: Extract<PluginHealth, { readonly _tag: \"healthy\" | \"degraded\" }>\n readonly expectedAuthority?: PluginSynchronizationAuthority\n}\n\n/** Durable counts from one new page, or zero counts when the exact page is replayed. */\nexport interface NormalizedPluginPageMaterializationReceipt {\n readonly pageCommitted: boolean\n readonly acceptedEventCount: number\n readonly entityProjectionCount: number\n readonly evidenceClaimCount: number\n readonly evidenceItemCount: number\n readonly nodeCount: number\n readonly personCount: number\n readonly relationshipCount: number\n readonly skippedEntityCount: number\n}\n\n/**\n * Commit one decoded page and all accepted canonical projections atomically.\n * The existing plugin checkpoint transaction nests as a savepoint; only its\n * newly accepted event identities cross the materialization seam.\n */\nexport const materializeNormalizedPluginPage = Effect.fn(\n \"NormalizedPluginPageMaterialization.materializePage\"\n)(function*(\n scope: NormalizedPluginPageMaterializationScope,\n page: PluginSyncPageV1\n): Effect.fn.Return<\n NormalizedPluginPageMaterializationReceipt,\n NormalizedPluginPageMaterializationError | PersistenceOperationFailure | PluginConflictFailure,\n Crypto.Crypto | Persistence\n> {\n const cryptoService = yield* Crypto.Crypto\n const persistence = yield* Persistence\n const materializeWithSettings = Effect.fn(\n \"NormalizedPluginPageMaterialization.materializeWithSettings\"\n )(function*(settingsRecord: WorkspaceSettingsRecord) {\n if (scope.expectedAuthority !== undefined) {\n yield* verifyPluginSynchronizationAuthority(persistence, scope.expectedAuthority)\n }\n const settings = settingsRecord.settings\n const materializationPage = yield* sequenceClockifyPersonEvents(persistence, scope, page)\n const pipelineTombstones = materializationPage.events.filter(isCodePipelineTombstone)\n const previousPipelineRecords = pipelineTombstones.length === 0\n ? []\n : yield* persistence.pluginRuntime.getCodePipelineCacheBeforeTombstones(\n scope.workspaceId,\n scope.pluginConnectionId,\n scope.streamKey,\n pipelineTombstones\n )\n const previousPipelineEvents = pipelineTombstones.length === 0\n ? []\n : yield* pipelineEventsFromCacheRecords(previousPipelineRecords, pipelineTombstones[0]?.eventId ?? \"pipeline\")\n const committed = yield* persistence.pluginRuntime.commitNormalizedPageReceipt(\n scope.workspaceId,\n scope.pluginConnectionId,\n scope.providerId,\n scope.streamKey,\n scope.expectedRevision,\n materializationPage,\n scope.committedAt,\n scope.successfulHealth\n )\n const accepted = new Set(committed.acceptedEventIds)\n const acceptedEvents = materializationPage.events.filter(({ eventId }) => accepted.has(eventId))\n const acceptedClockifyTimeEntryIds = new Set(\n acceptedEvents.flatMap((event) =>\n event._tag === \"UpsertEntity\" && canonicalKind(event.entityType) === \"time-entry\"\n ? [event.vendorImmutableId]\n : []\n )\n )\n const backfillEntityEvents = yield* Effect.filter(\n materializationPage.events,\n (event) =>\n !accepted.has(event.eventId) &&\n event._tag === \"UpsertEntity\" &&\n !acceptedClockifyTimeEntryIds.has(event.vendorImmutableId)\n ? requiresMaterializationBackfill(persistence, scope, event)\n : Effect.succeed(false)\n )\n const acceptedPipelineTombstones = new Set(\n acceptedEvents.filter(isCodePipelineTombstone).map(pipelineEntityIdentity)\n )\n const pipelineChanges = [\n ...acceptedEvents.filter(isCodePipelineUpsert),\n ...previousPipelineEvents.filter((event) => acceptedPipelineTombstones.has(pipelineEntityIdentity(event)))\n ]\n const acceptedPipelineEvent = pipelineChanges[0]\n const pipelineSelectors = acceptedPipelineEvent === undefined\n ? []\n : yield* codePipelineCacheSelectors(pipelineChanges).pipe(\n Effect.mapError((error) => malformed(error.diagnosticCode, error.eventId))\n )\n const cachedPipelineEvents = acceptedPipelineEvent === undefined || pipelineSelectors.length === 0\n ? []\n : yield* currentPipelineEvents(persistence, scope, acceptedPipelineEvent.eventId, pipelineSelectors)\n const pipelineEventById = new Map<string, NormalizedPluginEventV1>()\n for (const event of [...acceptedEvents, ...cachedPipelineEvents]) {\n if (isCodePipelineUpsert(event)) pipelineEventById.set(event.eventId, event)\n }\n const pipelineEvents = [...pipelineEventById.values()]\n const affectedExecutions = acceptedPipelineEvent === undefined\n ? []\n : yield* affectedPipelineExecutionEvents(pipelineEvents, pipelineChanges).pipe(\n Effect.mapError((error) => malformed(error.diagnosticCode, error.eventId))\n )\n const acceptedPersonIds = new Set(\n acceptedEvents.flatMap((event) => event._tag === \"UpsertPerson\" ? [event.vendorPersonId] : [])\n )\n const roleBackfillCandidates = materializationPage.events.flatMap((event) => {\n if (\n accepted.has(event.eventId) ||\n event._tag !== \"UpsertEntity\" ||\n canonicalKind(event.entityType) !== \"time-entry\" ||\n acceptedClockifyTimeEntryIds.has(event.vendorImmutableId)\n ) return []\n const attributes = Schema.decodeUnknownResult(EntityAttributes)(event.attributes)\n if (\n Result.isFailure(attributes) ||\n attributes.success.userId === null ||\n attributes.success.userId === undefined\n ) return []\n return [{ event, vendorPersonId: VendorImmutableId.make(attributes.success.userId) }]\n })\n const persistedInactivePersonIds = new Set(\n yield* Effect.filter(\n [...new Set(roleBackfillCandidates.map(({ vendorPersonId }) => vendorPersonId))].filter(\n (vendorPersonId) => !acceptedPersonIds.has(vendorPersonId)\n ),\n (vendorPersonId) =>\n Effect.gen(function*() {\n const person = yield* persistence.people.findPersonBySourceIdentity(scope.workspaceId, {\n pluginConnectionId: scope.pluginConnectionId,\n providerId: scope.providerId,\n vendorPersonId\n }).pipe(Effect.result)\n if (Result.isSuccess(person)) return !person.success.person.isActive\n if (person.failure._tag === \"RecordNotFoundError\") return false\n return yield* person.failure\n }),\n { concurrency: 1 }\n )\n )\n const roleBackfillEntityEvents = roleBackfillCandidates.filter(\n ({ vendorPersonId }) => acceptedPersonIds.has(vendorPersonId) || persistedInactivePersonIds.has(vendorPersonId)\n ).map(({ event }) => event)\n const entityEventById = new Map<string, NormalizedPluginEventV1>()\n for (\n const event of [\n ...acceptedEvents,\n ...backfillEntityEvents,\n ...affectedExecutions.filter(({ eventId }) => !accepted.has(eventId))\n ]\n ) entityEventById.set(event.eventId, event)\n const entityEvents = [...entityEventById.values()]\n const backfillEntityEventIds = new Set(backfillEntityEvents.map(({ eventId }) => eventId))\n const forcedPipelineExecutionEventIds = new Set(affectedExecutions.map(({ eventId }) => eventId))\n let entityProjectionCount = 0\n let evidenceClaimCount = 0\n let evidenceItemCount = 0\n let nodeCount = 0\n let personCount = 0\n let relationshipCount = 0\n let skippedEntityCount = 0\n\n for (const event of acceptedEvents) {\n if (event._tag !== \"UpsertPerson\") continue\n personCount += yield* materializePerson(persistence, cryptoService, scope, event)\n }\n const roleAssignments = new Map<RoleAssignmentId, RoleAssignmentRecord>()\n if (\n roleBackfillEntityEvents.length > 0 || entityEvents.some(\n (event) => event._tag === \"UpsertEntity\" && canonicalKind(event.entityType) === \"time-entry\"\n )\n ) {\n for (const record of yield* persistence.people.listRoleAssignments(scope.workspaceId)) {\n roleAssignments.set(record.assignment.assignmentId, record)\n }\n }\n for (const event of roleBackfillEntityEvents) {\n if (event._tag !== \"UpsertEntity\") continue\n const attributes = Schema.decodeUnknownResult(EntityAttributes)(event.attributes)\n const userId = Result.isSuccess(attributes) ? attributes.success.userId : null\n if (userId === null || userId === undefined) continue\n const existing = yield* findEntity(persistence, scope, event.vendorImmutableId)\n if (existing === null) continue\n yield* reconcileTimeEntryContributor(\n persistence,\n cryptoService,\n scope,\n existing.entityId,\n userId,\n event.eventId,\n roleAssignments\n )\n }\n for (const event of entityEvents) {\n if (event._tag === \"UpsertEntity\") {\n if (event.entityType === \"release\") {\n nodeCount += (yield* materializeRelease(\n persistence,\n cryptoService,\n scope,\n settings,\n event\n )).nodeCount\n continue\n }\n if (event.entityType === \"aws.codepipeline.pipeline\") {\n yield* materializePipelineAuthority(persistence, cryptoService, scope, event)\n continue\n }\n const schemaBackfill = backfillEntityEventIds.has(event.eventId)\n const forcedPipelineProjection = event.entityType === \"aws.codepipeline.execution\" &&\n forcedPipelineExecutionEventIds.has(event.eventId)\n const receipt = yield* materializeUpsertEntity(\n persistence,\n cryptoService,\n scope,\n event,\n event.entityType === \"aws.codepipeline.execution\" ? pipelineEvents : acceptedEvents,\n forcedPipelineProjection || schemaBackfill,\n schemaBackfill,\n roleAssignments\n )\n entityProjectionCount += receipt.entityProjectionCount\n nodeCount += receipt.nodeCount\n skippedEntityCount += receipt.skippedEntityCount\n } else if (event._tag === \"TombstoneEntity\") {\n entityProjectionCount += (yield* materializeTombstoneEntity(persistence, scope, event)).entityProjectionCount\n }\n }\n for (const event of acceptedEvents) {\n if (event._tag !== \"AppendEvidence\") continue\n const receipt = yield* materializeEvidence(\n persistence,\n cryptoService,\n scope,\n settings,\n event\n )\n evidenceItemCount += receipt.evidenceItemCount\n evidenceClaimCount += receipt.evidenceClaimCount\n }\n for (const event of acceptedEvents) {\n if (event._tag !== \"ProposeRelationship\") continue\n const receipt = yield* materializeRelationship(persistence, cryptoService, scope, event)\n nodeCount += receipt.nodeCount\n relationshipCount += receipt.relationshipCount\n }\n relationshipCount += yield* retireMissingJiraReleaseContainments(\n persistence,\n cryptoService,\n scope,\n acceptedEvents\n )\n if (acceptedEvents.length > 0 || entityProjectionCount > 0) {\n const inference = yield* materializeRelationshipInference(\n persistence,\n (identity) => stableUuid(cryptoService, identity, \"relationship-inference\"),\n scope,\n settings\n )\n evidenceClaimCount += inference.evidenceClaimCount\n evidenceItemCount += inference.evidenceItemCount\n nodeCount += inference.nodeCount\n relationshipCount += inference.relationshipCount\n }\n return {\n pageCommitted: committed.pageCommitted,\n acceptedEventCount: acceptedEvents.length,\n entityProjectionCount,\n evidenceClaimCount,\n evidenceItemCount,\n nodeCount,\n personCount,\n relationshipCount,\n skippedEntityCount\n }\n })\n return yield* persistence.workspaceSettings.readAtomically(\n scope.workspaceId,\n materializeWithSettings\n )\n})\n","import * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as Stream from \"effect/Stream\"\n\nimport type { PluginSynchronizationState } from \"../../api/plugins.js\"\nimport { PluginHealth, type PluginHealth as PluginHealthType } from \"../../domain/freshness.js\"\nimport type { PluginConnectionId, WorkspaceId } from \"../../domain/identifiers.js\"\nimport { NegotiatedPluginDescriptorV1 } from \"../../domain/plugins/descriptor.js\"\nimport { PluginCheckpointV1, type PluginSyncPageV1, PluginSyncRequestV1 } from \"../../domain/plugins/events.js\"\nimport type { ProviderId } from \"../../domain/sourceRevision.js\"\nimport type { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport {\n ApplicationInvalidRequest,\n ApplicationResourceNotFound,\n ApplicationServiceUnavailable,\n type PluginAdministrationError\n} from \"../api/ApplicationServices.js\"\nimport type { PersistenceOperationFailure } from \"../persistence/Persistence.js\"\nimport { Persistence } from \"../persistence/Persistence.js\"\nimport type {\n PluginSyncAttemptRecord,\n PluginSyncAttemptState\n} from \"../persistence/repositories/pluginRuntimeModels.js\"\nimport { PluginStreamKey } from \"../persistence/repositories/pluginRuntimeModels.js\"\nimport type { PluginFailure } from \"../plugins/failures.js\"\nimport { pluginFailureClass, PluginMalformedResponseFailure } from \"../plugins/failures.js\"\nimport { firstPartySyncStreamKey, supportsFirstPartySynchronization } from \"../plugins/firstPartySynchronization.js\"\nimport { PluginConnection, type PluginConnectionV1 } from \"../plugins/PluginConnection.js\"\nimport type { PluginConnectionMapV1 } from \"../plugins/PluginConnectionMap.js\"\nimport { DomainEventWakeups } from \"../runtime/DomainEventWakeups.js\"\nimport { materializeNormalizedPluginPage } from \"./normalizedPluginPageMaterialization.js\"\nimport {\n capturePluginSynchronizationAuthority,\n type PluginSynchronizationAuthority,\n verifyPluginSynchronizationAuthority\n} from \"./pluginSynchronizationAuthority.js\"\nimport { appendPortfolioInvalidation } from \"./portfolioInvalidation.js\"\n\nconst MAXIMUM_PAGES_PER_INVOCATION = 100\nconst SYNCHRONIZATION_CLAIM_LIFETIME_MINUTES = 15\nconst SOURCE_UNAVAILABLE_OUTCOME = \"source-unavailable\"\nconst SYNCHRONIZED_OUTCOME = \"synchronized\"\ntype SuccessfulPluginHealth = Extract<PluginHealthType, { readonly _tag: \"healthy\" | \"degraded\" }>\n\nconst successfulHealthAt = (\n health: SuccessfulPluginHealth,\n checkedAt: UtcTimestamp\n): SuccessfulPluginHealth =>\n health._tag === \"healthy\"\n ? { _tag: \"healthy\", checkedAt }\n : {\n ...health,\n checkedAt,\n retryAt: health.retryAt !== null && DateTime.Order(checkedAt, health.retryAt) <= 0\n ? health.retryAt\n : null\n }\n\n/** One provider-neutral manual synchronization driver with a fixed logical stream identity. */\nexport interface ManualPluginSyncDriver {\n readonly providerId: ProviderId\n readonly streamKey: string\n readonly sync: (\n connection: PluginConnectionV1,\n request: typeof PluginSyncRequestV1.Type\n ) => Stream.Stream<PluginSyncPageV1, PluginFailure>\n}\n\n/** Fixed lookup boundary that keeps provider identifiers out of the orchestration state machine. */\nexport interface ManualPluginSyncDriverRegistry {\n readonly get: (providerId: ProviderId) => Option.Option<ManualPluginSyncDriver>\n}\n\n/** Build a deterministic driver registry for production or fixture connections. */\nexport const makeManualPluginSyncDriverRegistry = (\n drivers: ReadonlyArray<ManualPluginSyncDriver>\n): ManualPluginSyncDriverRegistry => {\n const byProvider = new Map<ProviderId, ManualPluginSyncDriver>()\n for (const driver of drivers) byProvider.set(driver.providerId, driver)\n return { get: (providerId) => Option.fromNullishOr(byProvider.get(providerId)) }\n}\n\nconst connectionSync = (\n connection: PluginConnectionV1,\n request: typeof PluginSyncRequestV1.Type\n) => connection.sync(request)\n\n/** Production drivers for first-party connections that currently negotiate synchronization. */\nexport const firstPartyManualPluginSyncDrivers = makeManualPluginSyncDriverRegistry([\n { providerId: \"codecommit\", streamKey: firstPartySyncStreamKey(\"codecommit\"), sync: connectionSync },\n { providerId: \"codepipeline\", streamKey: firstPartySyncStreamKey(\"codepipeline\"), sync: connectionSync },\n { providerId: \"jira\", streamKey: firstPartySyncStreamKey(\"jira\"), sync: connectionSync },\n { providerId: \"clockify\", streamKey: firstPartySyncStreamKey(\"clockify\"), sync: connectionSync },\n { providerId: \"confluence\", streamKey: firstPartySyncStreamKey(\"confluence\"), sync: connectionSync }\n])\n\nconst unavailable = () => new ApplicationServiceUnavailable({ retryAt: null })\n\nconst mapPersistenceRead = (\n failure: PersistenceOperationFailure\n): ApplicationResourceNotFound | ApplicationServiceUnavailable =>\n failure._tag === \"RecordNotFoundError\" ? new ApplicationResourceNotFound() : unavailable()\n\nconst pluginFailureTags = new Set([\n \"PluginAuthenticationFailure\",\n \"PluginAuthorizationFailure\",\n \"PluginRateLimitFailure\",\n \"PluginTimeoutFailure\",\n \"PluginMalformedResponseFailure\",\n \"PluginOutageFailure\",\n \"PluginCancellationFailure\",\n \"PluginConflictFailure\",\n \"PluginUnsupportedCapabilityFailure\",\n \"PluginConfigurationFailure\",\n \"PluginUnknownOutcomeFailure\"\n])\n\nconst isPluginFailure = (failure: unknown): failure is PluginFailure =>\n Predicate.hasProperty(failure, \"_tag\") &&\n typeof failure._tag === \"string\" &&\n pluginFailureTags.has(failure._tag)\n\nconst sourceFailure = (failure: unknown): PluginFailure | null => {\n if (isPluginFailure(failure)) return failure\n if (\n Predicate.hasProperty(failure, \"_tag\") &&\n failure._tag === \"NormalizedPluginPageMaterializationError\"\n ) {\n return new PluginMalformedResponseFailure({\n operation: \"manual-sync\",\n diagnosticCode: \"normalized-plugin-page-rejected\"\n })\n }\n if (\n Predicate.hasProperty(failure, \"_tag\") &&\n failure._tag === \"SourceIdentityMismatchError\" &&\n Predicate.hasProperty(failure, \"recordKind\") &&\n (failure.recordKind === \"plugin-sync-event\" || failure.recordKind === \"plugin-sync-page\")\n ) {\n return new PluginMalformedResponseFailure({\n operation: \"manual-sync\",\n diagnosticCode: \"plugin-sync-source-identity-conflict\"\n })\n }\n return null\n}\n\nconst safeFailureMessage = (failure: PluginFailure): string => {\n switch (failure._tag) {\n case \"PluginAuthenticationFailure\":\n return \"Provider authentication failed.\"\n case \"PluginAuthorizationFailure\":\n return \"Provider permission was denied.\"\n case \"PluginRateLimitFailure\":\n return \"Provider rate limit was reached.\"\n case \"PluginTimeoutFailure\":\n return \"Provider request timed out.\"\n case \"PluginMalformedResponseFailure\":\n return \"Provider returned an invalid response.\"\n case \"PluginOutageFailure\":\n return \"Provider is temporarily unavailable.\"\n case \"PluginCancellationFailure\":\n return \"Provider synchronization was cancelled.\"\n case \"PluginConflictFailure\":\n return \"Provider state changed during synchronization.\"\n case \"PluginUnsupportedCapabilityFailure\":\n return \"Provider synchronization is not supported.\"\n case \"PluginConfigurationFailure\":\n return \"Provider configuration is incomplete.\"\n case \"PluginUnknownOutcomeFailure\":\n return \"Provider synchronization outcome is unknown.\"\n }\n}\n\nconst failureHealth = Effect.fn(\"ManualPluginSynchronization.failureHealth\")(function*(\n failure: PluginFailure,\n checkedAt: UtcTimestamp\n) {\n return yield* Schema.decodeUnknownEffect(Schema.toType(PluginHealth))({\n _tag: \"unavailable\",\n checkedAt,\n failureClass: pluginFailureClass(failure),\n retryAt: failure._tag === \"PluginRateLimitFailure\" ? failure.retryAt : null,\n safeMessage: safeFailureMessage(failure)\n })\n})\n\nconst stateFromAttemptState = (\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n streamKey: string,\n attemptState: PluginSyncAttemptState\n): PluginSynchronizationState => {\n const lastAttempt: PluginSyncAttemptRecord | undefined = attemptState.latestAttempt ?? undefined\n const lastSuccess: PluginSyncAttemptRecord | undefined = attemptState.latestSynchronized ?? undefined\n return {\n pluginConnectionId,\n providerId,\n streamKey,\n lastAttemptAt: lastAttempt?.startedAt ?? null,\n lastSuccessAt: lastSuccess?.completedAt ?? null,\n result: lastAttempt === undefined\n ? \"never\"\n : lastAttempt.outcome === null\n ? \"running\"\n : lastAttempt.outcome,\n pagesCommitted: lastAttempt?.pagesCommitted ?? 0\n }\n}\n\ninterface BoundManualSync {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly driver: ManualPluginSyncDriver\n readonly streamKey: PluginStreamKey\n}\n\ninterface SynchronizationClaim extends BoundManualSync {\n readonly claimId: string\n}\n\nexport interface ManualPluginSynchronizationService {\n readonly state: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<PluginSynchronizationState, ApplicationInvalidRequest | PluginAdministrationError>\n readonly synchronize: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<PluginSynchronizationState, ApplicationInvalidRequest | PluginAdministrationError>\n}\n\n/** Build the bounded synchronization application over a scoped provider runtime map. */\nexport const makeManualPluginSynchronization = Effect.fn(\n \"ManualPluginSynchronization.make\"\n)(function*(\n connections: PluginConnectionMapV1,\n drivers: ManualPluginSyncDriverRegistry = firstPartyManualPluginSyncDrivers\n): Effect.fn.Return<ManualPluginSynchronizationService, never, Crypto.Crypto | DomainEventWakeups | Persistence> {\n const persistence = yield* Persistence\n const wakeups = yield* DomainEventWakeups\n const cryptoService = yield* Crypto.Crypto\n\n const bind = Effect.fn(\"ManualPluginSynchronization.bind\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }): Effect.fn.Return<BoundManualSync, ApplicationInvalidRequest | PluginAdministrationError> {\n const connection = yield* persistence.pluginConnections.get(\n input.workspaceId,\n input.pluginConnectionId\n ).pipe(Effect.mapError(mapPersistenceRead))\n const driver = drivers.get(connection.providerId)\n if (Option.isNone(driver)) return yield* new ApplicationInvalidRequest()\n const runtime = yield* persistence.pluginRuntime.getRuntime(\n input.workspaceId,\n input.pluginConnectionId\n ).pipe(Effect.mapError(mapPersistenceRead))\n const descriptor = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(NegotiatedPluginDescriptorV1))(\n runtime.descriptorJson\n ).pipe(Effect.mapError(() => new ApplicationInvalidRequest()))\n if (!supportsFirstPartySynchronization(connection.providerId, descriptor)) {\n return yield* new ApplicationInvalidRequest()\n }\n const streamKey = yield* Schema.decodeUnknownEffect(PluginStreamKey)(driver.value.streamKey).pipe(\n Effect.mapError(() => new ApplicationInvalidRequest())\n )\n return { ...input, providerId: connection.providerId, driver: driver.value, streamKey }\n })\n\n const releaseSynchronizationAttempt = Effect.fn(\n \"ManualPluginSynchronization.releaseSynchronizationAttempt\"\n )(function*(input: {\n readonly attempt: PluginSyncAttemptRecord\n readonly claim: SynchronizationClaim\n }) {\n const completedAt = DateTime.makeUnsafe(yield* Effect.clockWith((clock) => clock.currentTimeMillis))\n yield* persistence.pluginRuntime.reconcileSyncAttempts(\n input.claim.workspaceId,\n input.claim.pluginConnectionId,\n input.claim.providerId,\n input.claim.streamKey,\n completedAt,\n input.attempt.attemptSequence\n ).pipe(\n Effect.ignore({\n log: \"Error\",\n message: \"Could not reconcile an incomplete manual synchronization attempt\"\n })\n )\n })\n\n const releaseSynchronizationClaim = Effect.fn(\n \"ManualPluginSynchronization.releaseSynchronizationClaim\"\n )(function*(claim: SynchronizationClaim) {\n yield* persistence.pluginRuntime.releaseSyncClaim(\n claim.workspaceId,\n claim.pluginConnectionId,\n claim.streamKey,\n claim.claimId\n ).pipe(Effect.mapError(() => unavailable()))\n })\n\n const claimSynchronization = Effect.fn(\n \"ManualPluginSynchronization.claimSynchronization\"\n )(function*(bound: BoundManualSync) {\n const claimId = yield* cryptoService.randomUUIDv4.pipe(Effect.mapError(() => unavailable()))\n const claimedAt = DateTime.makeUnsafe(yield* Effect.clockWith((clock) => clock.currentTimeMillis))\n const expiresAt = DateTime.add(claimedAt, { minutes: SYNCHRONIZATION_CLAIM_LIFETIME_MINUTES })\n const claimed = yield* persistence.pluginRuntime.claimSync(\n bound.workspaceId,\n bound.pluginConnectionId,\n bound.providerId,\n bound.streamKey,\n claimId,\n claimedAt,\n expiresAt\n ).pipe(Effect.mapError(() => unavailable()))\n if (!claimed) return yield* unavailable()\n return { ...bound, claimId }\n })\n\n const stateFor = Effect.fn(\"ManualPluginSynchronization.stateFor\")(function*(bound: BoundManualSync) {\n const attemptState = yield* persistence.pluginRuntime.getSyncAttemptState(\n bound.workspaceId,\n bound.pluginConnectionId,\n bound.streamKey\n ).pipe(Effect.mapError(() => unavailable()))\n return stateFromAttemptState(\n bound.pluginConnectionId,\n bound.providerId,\n bound.streamKey,\n attemptState\n )\n })\n\n const readState = Effect.fn(\"ManualPluginSynchronization.state\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) {\n const bound = yield* bind(input)\n return yield* stateFor(bound)\n })\n\n const persistHealth = Effect.fn(\"ManualPluginSynchronization.persistHealth\")(function*(\n bound: BoundManualSync,\n authority: PluginSynchronizationAuthority,\n health: PluginHealthType,\n failed: boolean\n ) {\n const persisted = yield* persistence.transact(Effect.gen(function*() {\n yield* verifyPluginSynchronizationAuthority(persistence, authority)\n const runtime = yield* persistence.pluginRuntime.getRuntime(\n bound.workspaceId,\n bound.pluginConnectionId\n )\n yield* persistence.pluginRuntime.recordHealth(\n bound.workspaceId,\n bound.pluginConnectionId,\n runtime.revision,\n health,\n failed ? runtime.consecutiveFailures + 1 : 0\n )\n yield* appendPortfolioInvalidation({\n workspaceId: bound.workspaceId,\n pluginConnectionId: bound.pluginConnectionId,\n releaseId: null,\n occurredAt: health.checkedAt,\n reason: \"plugin-health\"\n }).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.provideService(Persistence, persistence)\n )\n return true\n })).pipe(\n Effect.catchTag(\"PluginConflictFailure\", () => Effect.succeed(false)),\n Effect.mapError(() => unavailable())\n )\n if (persisted) yield* wakeups.notify(bound.workspaceId)\n return persisted\n })\n\n const initialCheckpoint = Effect.fn(\"ManualPluginSynchronization.initialCheckpoint\")(function*(\n bound: BoundManualSync\n ) {\n const current = yield* Effect.result(\n persistence.pluginRuntime.getStream(bound.workspaceId, bound.pluginConnectionId, bound.streamKey)\n )\n if (Result.isFailure(current)) {\n if (current.failure._tag === \"RecordNotFoundError\") return null\n return yield* Effect.fail(current.failure)\n }\n return current.success.checkpointJson === null\n ? null\n : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PluginCheckpointV1))(\n current.success.checkpointJson\n )\n })\n\n const run = Effect.fn(\"ManualPluginSynchronization.run\")(function*(\n bound: BoundManualSync,\n authority: PluginSynchronizationAuthority,\n connection: PluginConnectionV1,\n health: SuccessfulPluginHealth\n ) {\n const checkpoint = yield* initialCheckpoint(bound)\n const request = yield* Schema.decodeUnknownEffect(PluginSyncRequestV1)({\n streamKey: bound.streamKey,\n checkpoint\n })\n const initialStream = yield* Effect.result(\n persistence.pluginRuntime.getStream(bound.workspaceId, bound.pluginConnectionId, bound.streamKey)\n )\n const revision = Result.isSuccess(initialStream) ? initialStream.success.revision : 0\n return yield* Stream.runFoldEffect(\n bound.driver.sync(connection, request).pipe(Stream.take(MAXIMUM_PAGES_PER_INVOCATION)),\n () => ({ health, isTerminal: false, pagesSeen: 0, pagesCommitted: 0, revision }),\n (state, page) =>\n Effect.gen(function*() {\n if (state.isTerminal) {\n return yield* new PluginMalformedResponseFailure({\n operation: \"manual-sync\",\n diagnosticCode: \"manual-sync-page-after-terminal\"\n })\n }\n const committedAt = DateTime.makeUnsafe(yield* Clock.currentTimeMillis)\n const successfulHealth = successfulHealthAt(state.health, committedAt)\n const receipt = yield* materializeNormalizedPluginPage({\n workspaceId: bound.workspaceId,\n pluginConnectionId: bound.pluginConnectionId,\n providerId: bound.providerId,\n streamKey: bound.streamKey,\n expectedRevision: state.revision,\n committedAt,\n successfulHealth,\n expectedAuthority: authority\n }, page).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.provideService(Persistence, persistence)\n )\n const pagesSeen = state.pagesSeen + 1\n return {\n health: successfulHealth,\n isTerminal: !page.hasMore,\n pagesSeen,\n pagesCommitted: state.pagesCommitted + (receipt.pageCommitted ? 1 : 0),\n revision: state.revision + (receipt.pageCommitted ? 1 : 0)\n }\n })\n )\n })\n\n const synchronizeAttempt = Effect.fn(\"ManualPluginSynchronization.synchronizeAttempt\")(function*(\n input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n },\n bound: BoundManualSync,\n attempt: PluginSyncAttemptRecord,\n authority: PluginSynchronizationAuthority\n ) {\n const synchronized = yield* Effect.result(Effect.scoped(\n Effect.flatMap(\n connections.contextEffect({\n workspaceId: bound.workspaceId,\n pluginConnectionId: bound.pluginConnectionId\n }),\n (context) =>\n Effect.gen(function*() {\n const connection = Context.get(context, PluginConnection)\n const health = yield* connection.health\n if (health._tag === \"unavailable\" || health._tag === \"disabled\") return health\n const completed = yield* run(bound, authority, connection, health)\n if (\n !completed.isTerminal &&\n (\n completed.pagesSeen < MAXIMUM_PAGES_PER_INVOCATION ||\n completed.pagesCommitted === 0\n )\n ) {\n return yield* new PluginMalformedResponseFailure({\n operation: \"manual-sync\",\n diagnosticCode: \"manual-sync-terminal-page-missing\"\n })\n }\n return completed.health\n }).pipe(Effect.provide(context))\n )\n ))\n const outcome = yield* Effect.gen(function*() {\n if (Result.isSuccess(synchronized)) {\n const health = synchronized.success\n const sourceUnavailable = health._tag === \"unavailable\" || health._tag === \"disabled\"\n const healthPersisted = yield* persistHealth(bound, authority, health, sourceUnavailable)\n return sourceUnavailable || !healthPersisted ? SOURCE_UNAVAILABLE_OUTCOME : SYNCHRONIZED_OUTCOME\n }\n yield* Effect.logError(\"Manual plugin synchronization failed\", synchronized.failure).pipe(\n Effect.annotateLogs({\n workspaceId: bound.workspaceId,\n pluginConnectionId: bound.pluginConnectionId,\n streamKey: bound.streamKey\n })\n )\n const failure = sourceFailure(synchronized.failure)\n if (failure === null) return yield* unavailable()\n const failedAt = DateTime.makeUnsafe(yield* Effect.clockWith((clock) => clock.currentTimeMillis))\n const health = yield* failureHealth(failure, failedAt).pipe(Effect.mapError(() => unavailable()))\n yield* persistHealth(bound, authority, health, true)\n return SOURCE_UNAVAILABLE_OUTCOME\n })\n const completedAt = DateTime.makeUnsafe(yield* Effect.clockWith((clock) => clock.currentTimeMillis))\n yield* persistence.pluginRuntime.completeSyncAttempt(\n bound.workspaceId,\n bound.pluginConnectionId,\n bound.streamKey,\n attempt.attemptSequence,\n outcome,\n completedAt\n ).pipe(Effect.mapError(() => unavailable()))\n return yield* readState(input)\n })\n\n const synchronizeBound = Effect.fn(\"ManualPluginSynchronization.synchronizeBound\")(function*(\n input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n },\n claim: SynchronizationClaim\n ) {\n const captured = yield* capturePluginSynchronizationAuthority(\n persistence,\n claim.workspaceId,\n claim.pluginConnectionId\n ).pipe(Effect.mapError(mapPersistenceRead))\n if (!captured.connection.isEnabled) return yield* new ApplicationInvalidRequest()\n return yield* Effect.acquireUseRelease(\n Effect.gen(function*() {\n const startedAt = DateTime.makeUnsafe(yield* Effect.clockWith((clock) => clock.currentTimeMillis))\n return yield* persistence.pluginRuntime.beginSyncAttempt(\n claim.workspaceId,\n claim.pluginConnectionId,\n claim.providerId,\n claim.streamKey,\n startedAt\n ).pipe(Effect.mapError(() => unavailable()))\n }),\n (attempt) => synchronizeAttempt(input, claim, attempt, captured.authority),\n (attempt) => releaseSynchronizationAttempt({ attempt, claim })\n )\n })\n\n const synchronize = Effect.fn(\"ManualPluginSynchronization.synchronize\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) {\n const bound = yield* bind(input)\n return yield* Effect.acquireUseRelease(\n claimSynchronization(bound),\n (claim) => synchronizeBound(input, claim),\n releaseSynchronizationClaim\n ).pipe(\n Effect.tapCause((cause) =>\n Effect.logError(\"Manual plugin synchronization orchestration failed\", cause).pipe(\n Effect.annotateLogs({\n workspaceId: bound.workspaceId,\n pluginConnectionId: bound.pluginConnectionId,\n streamKey: bound.streamKey\n })\n )\n )\n )\n })\n\n return { state: readState, synchronize }\n})\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,IAAM,iBAAe,OAAO,YAAY,OAAO,OAAO,OAAO,MAAM,CAAC;AACpE,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AY,8BAA8B;GAAE;GAAS;EAAM,CAAC,CAC/D;CACF,CAAC;CAwBD,OAAO;EAAE,OAAO;EAAW,aAtBP,OAAO,GAAG,yCAAyC,CAAC,CAAC,WAAU,OAGhF;GACD,MAAM,QAAQ,OAAO,KAAK,KAAK;GAC/B,OAAO,OAAO,OAAO,kBACnB,qBAAqB,KAAK,IACzB,UAAU,iBAAiB,OAAO,KAAK,GACxC,2BACF,CAAC,CAAC,KACA,OAAO,UAAU,UACf,OAAO,SAAS,sDAAsD,KAAK,CAAC,CAAC,KAC3E,OAAO,aAAa;IAClB,aAAa,MAAM;IACnB,oBAAoB,MAAM;IAC1B,WAAW,MAAM;GACnB,CAAC,CACH,CACF,CACF;EACF,CAE2B;CAAY;AACzC,CAAC"}
@@ -1,4 +1,4 @@
1
- import { $t as ReadinessFactDefinition, An as deriveReleaseReadinessNextEvaluationAt, Cn as compareReadinessText, Gn as sortedReadinessUnique, Jt as ReadinessCandidateDigest, Kt as ReadinessArtifactRevision, Mn as deriveReleaseReadinessStages, Nn as deriveReleaseReadinessVerdict, Pn as readinessDefinitionsShapeIsV1, Un as readinessPolicyShapeIsV1, dn as ReadinessReleaseRevision, fn as ReadinessRuleId, jn as deriveReleaseReadinessSourceSummaries, kn as deriveReleaseReadinessFindings, mn as ReadinessRuleVersion, rn as ReadinessFactObservation } from "./workspaceSettings-C2Zsk6RI.js";
1
+ import { $t as ReadinessFactDefinition, An as deriveReleaseReadinessNextEvaluationAt, Cn as compareReadinessText, Gn as sortedReadinessUnique, Jt as ReadinessCandidateDigest, Kt as ReadinessArtifactRevision, Mn as deriveReleaseReadinessStages, Nn as deriveReleaseReadinessVerdict, Pn as readinessDefinitionsShapeIsV1, Un as readinessPolicyShapeIsV1, dn as ReadinessReleaseRevision, fn as ReadinessRuleId, jn as deriveReleaseReadinessSourceSummaries, kn as deriveReleaseReadinessFindings, mn as ReadinessRuleVersion, rn as ReadinessFactObservation } from "./workspaceSettings-sv8h_h2P.js";
2
2
  import { At as ShareId, Nt as UtcTimestamp, Tt as ReleaseId, _t as PersonId, at as EntityId, jt as WorkspaceId, kt as SessionId, ot as EnvironmentId, xt as ReadinessAssessmentId } from "./descriptor-CCvNzSZL.js";
3
3
  import * as Schema from "effect/Schema";
4
4
  import * as DateTime from "effect/DateTime";
@@ -132,4 +132,4 @@ var rollUpReleaseReadiness = (input) => {
132
132
  //#endregion
133
133
  export { ReleaseReadinessCandidateMaterial as a, normalizeReadinessRuleMaterial as c, AuthorizedShareTarget as d, ReadinessRuleMaterial as i, normalizeReleaseReadinessCandidateMaterial as l, summarizeEnvironmentReadiness as n, ReleaseReadinessChildMaterial as o, EnvironmentReadinessCandidateMaterial as r, normalizeEnvironmentReadinessCandidateMaterial as s, rollUpReleaseReadiness as t, AuthorizedShareGrant as u };
134
134
 
135
- //# sourceMappingURL=readiness-BtntBhDj.js.map
135
+ //# sourceMappingURL=readiness-31Mqc-9H.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"readiness-BtntBhDj.js","names":[],"sources":["../../../src/domain/authorizedShare.ts","../../../src/domain/readiness/material.ts","../../../src/domain/readiness/rollup.ts"],"sourcesContent":["import * as DateTime from \"effect/DateTime\"\nimport * as Schema from \"effect/Schema\"\n\nimport { EntityId, PersonId, SessionId, ShareId, WorkspaceId } from \"./identifiers.js\"\nimport { UtcTimestamp } from \"./utcTimestamp.js\"\n\n/** Exact normalized entity scope granted to one authenticated person. */\nexport const AuthorizedShareTarget = Schema.TaggedStruct(\"entity\", {\n entityId: EntityId\n})\n\n/** Decoded exact authorized-share target. */\nexport type AuthorizedShareTarget = typeof AuthorizedShareTarget.Type\n\n/** Durable authenticated grant with immutable creation and optional revocation evidence. */\nexport const AuthorizedShareGrant = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId,\n target: AuthorizedShareTarget,\n granteePersonId: PersonId,\n createdByPersonId: PersonId,\n createdBySessionId: SessionId,\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp,\n revokedAt: Schema.NullOr(UtcTimestamp)\n}).check(\n Schema.makeFilter(\n ({ createdAt, expiresAt }) => DateTime.Order(createdAt, expiresAt) < 0,\n { expected: \"authorized share expiry after creation\" }\n ),\n Schema.makeFilter(\n ({ createdAt, revokedAt }) => revokedAt === null || DateTime.Order(createdAt, revokedAt) <= 0,\n { expected: \"authorized share revocation at or after creation\" }\n )\n)\n\n/** Decoded durable authorized-share grant. */\nexport type AuthorizedShareGrant = typeof AuthorizedShareGrant.Type\n","import * as Schema from \"effect/Schema\"\n\nimport { EnvironmentId, ReadinessAssessmentId, ReleaseId, WorkspaceId } from \"../identifiers.js\"\nimport {\n MAX_READINESS_EVIDENCE_REFERENCES,\n ReadinessArtifactRevision,\n ReadinessCandidateDigest,\n ReadinessFactDefinition,\n type ReadinessFactDefinition as ReadinessFactDefinitionType,\n ReadinessFactObservation,\n type ReadinessFactObservation as ReadinessFactObservationType,\n ReadinessReleaseRevision,\n ReadinessRuleId,\n ReadinessRuleVersion\n} from \"./model.js\"\nimport { compareReadinessText, readinessDefinitionsShapeIsV1, readinessPolicyShapeIsV1 } from \"./policy.js\"\n\nconst unique = <Value>(values: ReadonlyArray<Value>): boolean => new Set(values).size === values.length\n\nconst CandidateMaterialBase = {\n workspaceId: WorkspaceId,\n releaseRevision: ReadinessReleaseRevision,\n artifactRevision: ReadinessArtifactRevision\n}\n\nconst readinessFactsAreValid = (input: {\n readonly definitions: ReadonlyArray<ReadinessFactDefinitionType>\n readonly observations: ReadonlyArray<ReadinessFactObservationType>\n}): boolean => {\n const definitionsById = new Map(input.definitions.map((definition) => [definition.factId, definition]))\n return unique(input.definitions.map(({ factId }) => factId)) &&\n unique(input.observations.map(({ factId }) => factId)) &&\n input.observations.every((observation) =>\n definitionsById.get(observation.factId)?.kind === observation.state._tag\n ) &&\n readinessPolicyShapeIsV1(input.definitions, input.observations) &&\n input.observations.reduce((total, observation) => total + observation.evidence.length, 0) <=\n MAX_READINESS_EVIDENCE_REFERENCES\n}\n\n/** Digest-free, complete material for one target-environment candidate. */\nexport const EnvironmentReadinessCandidateMaterial = Schema.Struct({\n ...CandidateMaterialBase,\n scope: Schema.TaggedStruct(\"environment\", {\n releaseId: ReleaseId,\n environmentId: EnvironmentId\n }),\n complete: Schema.Boolean,\n definitions: Schema.Array(ReadinessFactDefinition).check(Schema.isMaxLength(512)),\n observations: Schema.Array(ReadinessFactObservation).check(Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(readinessFactsAreValid, {\n expected: \"complete, unique, evidence-bounded V1 readiness candidate material\"\n })\n)\n\n/** Decoded environment candidate material before deterministic normalization. */\nexport type EnvironmentReadinessCandidateMaterial = typeof EnvironmentReadinessCandidateMaterial.Type\n\n/** Exact child assessment bound into a release-scope candidate. */\nexport const ReleaseReadinessChildMaterial = Schema.Struct({\n assessmentId: ReadinessAssessmentId,\n environmentId: EnvironmentId,\n candidateDigest: ReadinessCandidateDigest\n})\n\n/** Decoded release child material. */\nexport type ReleaseReadinessChildMaterial = typeof ReleaseReadinessChildMaterial.Type\n\n/** Digest-free material for one release candidate and its exact environment assessments. */\nexport const ReleaseReadinessCandidateMaterial = Schema.Struct({\n ...CandidateMaterialBase,\n scope: Schema.TaggedStruct(\"release\", { releaseId: ReleaseId }),\n environments: Schema.NonEmptyArray(ReleaseReadinessChildMaterial).check(Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(({ environments }) => unique(environments.map(({ environmentId }) => environmentId)), {\n expected: \"release candidate environment identities to be unique\"\n }),\n Schema.makeFilter(({ environments }) => unique(environments.map(({ assessmentId }) => assessmentId)), {\n expected: \"release candidate assessment identities to be unique\"\n })\n)\n\n/** Decoded release candidate material before deterministic normalization. */\nexport type ReleaseReadinessCandidateMaterial = typeof ReleaseReadinessCandidateMaterial.Type\n\n/** Digest-free immutable readiness-rule snapshot. */\nexport const ReadinessRuleMaterial = Schema.Struct({\n ruleId: ReadinessRuleId,\n version: ReadinessRuleVersion,\n definitions: Schema.Array(ReadinessFactDefinition).check(Schema.isNonEmpty(), Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(({ definitions }) => unique(definitions.map(({ factId }) => factId)), {\n expected: \"readiness rule fact identities to be unique\"\n }),\n Schema.makeFilter(({ definitions }) => readinessDefinitionsShapeIsV1(definitions), {\n expected: \"readiness rule material to contain the complete V1 policy shape\"\n })\n)\n\n/** Decoded rule material before deterministic normalization. */\nexport type ReadinessRuleMaterial = typeof ReadinessRuleMaterial.Type\n\nconst normalizeDefinitions = (\n definitions: ReadonlyArray<ReadinessFactDefinitionType>\n): Array<ReadinessFactDefinitionType> =>\n [...definitions].sort((left, right) => compareReadinessText(left.factId, right.factId))\n\nconst normalizeObservations = (\n observations: ReadonlyArray<ReadinessFactObservationType>\n): Array<ReadinessFactObservationType> =>\n observations\n .map((observation) => ({\n ...observation,\n evidence: [...observation.evidence].sort((left, right) => compareReadinessText(left.evidenceId, right.evidenceId))\n }))\n .sort((left, right) => compareReadinessText(left.factId, right.factId))\n\n/** Return the only JSON ordering accepted for environment-candidate hashing. */\nexport const normalizeEnvironmentReadinessCandidateMaterial = (\n material: EnvironmentReadinessCandidateMaterial\n): EnvironmentReadinessCandidateMaterial => ({\n ...material,\n definitions: normalizeDefinitions(material.definitions),\n observations: normalizeObservations(material.observations)\n})\n\n/** Return the only JSON ordering accepted for release-candidate hashing. */\nexport const normalizeReleaseReadinessCandidateMaterial = (\n material: ReleaseReadinessCandidateMaterial\n): ReleaseReadinessCandidateMaterial => {\n const [first, ...remaining] = material.environments\n const environments: [ReleaseReadinessChildMaterial, ...Array<ReleaseReadinessChildMaterial>] = [\n first,\n ...remaining\n ]\n environments.sort((left, right) => compareReadinessText(left.environmentId, right.environmentId))\n return { ...material, environments }\n}\n\n/** Return the only JSON ordering accepted for rule hashing. */\nexport const normalizeReadinessRuleMaterial = (\n material: ReadinessRuleMaterial\n): ReadinessRuleMaterial => ({\n ...material,\n definitions: normalizeDefinitions(material.definitions)\n})\n","import type {\n EnvironmentReadinessAssessment,\n ReleaseReadinessAssessment,\n ReleaseReadinessRollupInput\n} from \"./model.js\"\nimport {\n compareReadinessText,\n deriveReleaseReadinessFindings,\n deriveReleaseReadinessNextEvaluationAt,\n deriveReleaseReadinessSourceSummaries,\n deriveReleaseReadinessStages,\n deriveReleaseReadinessVerdict,\n sortedReadinessUnique\n} from \"./policy.js\"\n\n/** Exact compact projection retained when an environment is rolled into a release. */\nexport const summarizeEnvironmentReadiness = (\n assessment: EnvironmentReadinessAssessment\n): ReleaseReadinessAssessment[\"environments\"][number] => ({\n assessmentId: assessment.assessmentId,\n environmentId: assessment.candidate.scope.environmentId,\n candidateDigest: assessment.candidate.digest,\n inputComplete: assessment.inputComplete,\n facts: assessment.facts,\n nextEvaluationAt: assessment.nextEvaluationAt,\n verdict: assessment.verdict,\n stages: assessment.stages,\n blockers: assessment.blockers,\n warnings: assessment.warnings,\n gaps: assessment.gaps,\n sourceFreshness: assessment.sourceFreshness,\n evidenceIds: assessment.evidenceIds\n})\n\n/** Pure deterministic roll-up of current target-environment assessments. */\nexport const rollUpReleaseReadiness = (\n input: ReleaseReadinessRollupInput\n): ReleaseReadinessAssessment => {\n const environments = input.environments\n .slice()\n .sort((left, right) => {\n return compareReadinessText(\n left.candidate.scope.environmentId,\n right.candidate.scope.environmentId\n )\n })\n const first = environments.reduce((earliest, assessment) =>\n compareReadinessText(\n assessment.candidate.scope.environmentId,\n earliest.candidate.scope.environmentId\n ) < 0\n ? assessment\n : earliest, input.environments[0])\n const environmentSummaries: ReleaseReadinessAssessment[\"environments\"] = [\n summarizeEnvironmentReadiness(first),\n ...environments.filter((assessment) => assessment !== first).map(summarizeEnvironmentReadiness)\n ]\n const findings = deriveReleaseReadinessFindings(environmentSummaries)\n\n return {\n _tag: \"release\",\n assessmentId: input.assessmentId,\n previousAssessmentId: input.previousAssessmentId,\n candidate: input.candidate,\n rule: first.rule,\n derivationVersion: first.derivationVersion,\n evaluatedAt: input.evaluatedAt,\n nextEvaluationAt: deriveReleaseReadinessNextEvaluationAt(environmentSummaries),\n verdict: deriveReleaseReadinessVerdict(environmentSummaries),\n stages: deriveReleaseReadinessStages(environmentSummaries),\n environments: environmentSummaries,\n blockers: findings.blockers,\n warnings: findings.warnings,\n gaps: findings.gaps,\n sourceFreshness: deriveReleaseReadinessSourceSummaries(environmentSummaries),\n evidenceIds: sortedReadinessUnique(environments.flatMap(({ evidenceIds }) => evidenceIds))\n }\n}\n"],"mappings":";;;;;;AAOA,IAAa,wBAAwB,OAAO,aAAa,UAAU,EACjE,UAAU,SACZ,CAAC;;AAMD,IAAa,uBAAuB,OAAO,OAAO;CAChD,aAAa;CACb,SAAS;CACT,QAAQ;CACR,iBAAiB;CACjB,mBAAmB;CACnB,oBAAoB;CACpB,WAAW;CACX,WAAW;CACX,WAAW,OAAO,OAAO,YAAY;AACvC,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,EAAE,WAAW,gBAAgB,SAAS,MAAM,WAAW,SAAS,IAAI,GACrE,EAAE,UAAU,yCAAyC,CACvD,GACA,OAAO,YACJ,EAAE,WAAW,gBAAgB,cAAc,QAAQ,SAAS,MAAM,WAAW,SAAS,KAAK,GAC5F,EAAE,UAAU,mDAAmD,CACjE,CACF;;;ACjBA,IAAM,UAAiB,WAA0C,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,OAAO;AAEjG,IAAM,wBAAwB;CAC5B,aAAa;CACb,iBAAiB;CACjB,kBAAkB;AACpB;AAEA,IAAM,0BAA0B,UAGjB;CACb,MAAM,kBAAkB,IAAI,IAAI,MAAM,YAAY,KAAK,eAAe,CAAC,WAAW,QAAQ,UAAU,CAAC,CAAC;CACtG,OAAO,OAAO,MAAM,YAAY,KAAK,EAAE,aAAa,MAAM,CAAC,KACzD,OAAO,MAAM,aAAa,KAAK,EAAE,aAAa,MAAM,CAAC,KACrD,MAAM,aAAa,OAAO,gBACxB,gBAAgB,IAAI,YAAY,MAAM,CAAC,EAAE,SAAS,YAAY,MAAM,IACtE,KACA,yBAAyB,MAAM,aAAa,MAAM,YAAY,KA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,OAAO,qBACL,KAAK,UAAU,MAAM,eACrB,MAAM,UAAU,MAAM,aACxB;CACF,CAAC;CACH,MAAM,QAAQ,aAAa,QAAQ,UAAU,eAC3C,qBACI,WAAW,UAAU,MAAM,eAC3B,SAAS,UAAU,MAAM,aAC3B,IAAI,IACF,aACA,UAAU,MAAM,aAAa,EAAE;CACrC,MAAM,uBAAmE,CACvE,8BAA8B,KAAK,GACnC,GAAG,aAAa,QAAQ,eAAe,eAAe,KAAK,CAAC,CAAC,IAAI,6BAA6B,CAChG;CACA,MAAM,WAAW,+BAA+B,oBAAoB;CAEpE,OAAO;EACL,MAAM;EACN,cAAc,MAAM;EACpB,sBAAsB,MAAM;EAC5B,WAAW,MAAM;EACjB,MAAM,MAAM;EACZ,mBAAmB,MAAM;EACzB,aAAa,MAAM;EACnB,kBAAkB,uCAAuC,oBAAoB;EAC7E,SAAS,8BAA8B,oBAAoB;EAC3D,QAAQ,6BAA6B,oBAAoB;EACzD,cAAc;EACd,UAAU,SAAS;EACnB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,iBAAiB,sCAAsC,oBAAoB;EAC3E,aAAa,sBAAsB,aAAa,SAAS,EAAE,kBAAkB,WAAW,CAAC;CAC3F;AACF"}
1
+ {"version":3,"file":"readiness-31Mqc-9H.js","names":[],"sources":["../../../src/domain/authorizedShare.ts","../../../src/domain/readiness/material.ts","../../../src/domain/readiness/rollup.ts"],"sourcesContent":["import * as DateTime from \"effect/DateTime\"\nimport * as Schema from \"effect/Schema\"\n\nimport { EntityId, PersonId, SessionId, ShareId, WorkspaceId } from \"./identifiers.js\"\nimport { UtcTimestamp } from \"./utcTimestamp.js\"\n\n/** Exact normalized entity scope granted to one authenticated person. */\nexport const AuthorizedShareTarget = Schema.TaggedStruct(\"entity\", {\n entityId: EntityId\n})\n\n/** Decoded exact authorized-share target. */\nexport type AuthorizedShareTarget = typeof AuthorizedShareTarget.Type\n\n/** Durable authenticated grant with immutable creation and optional revocation evidence. */\nexport const AuthorizedShareGrant = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId,\n target: AuthorizedShareTarget,\n granteePersonId: PersonId,\n createdByPersonId: PersonId,\n createdBySessionId: SessionId,\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp,\n revokedAt: Schema.NullOr(UtcTimestamp)\n}).check(\n Schema.makeFilter(\n ({ createdAt, expiresAt }) => DateTime.Order(createdAt, expiresAt) < 0,\n { expected: \"authorized share expiry after creation\" }\n ),\n Schema.makeFilter(\n ({ createdAt, revokedAt }) => revokedAt === null || DateTime.Order(createdAt, revokedAt) <= 0,\n { expected: \"authorized share revocation at or after creation\" }\n )\n)\n\n/** Decoded durable authorized-share grant. */\nexport type AuthorizedShareGrant = typeof AuthorizedShareGrant.Type\n","import * as Schema from \"effect/Schema\"\n\nimport { EnvironmentId, ReadinessAssessmentId, ReleaseId, WorkspaceId } from \"../identifiers.js\"\nimport {\n MAX_READINESS_EVIDENCE_REFERENCES,\n ReadinessArtifactRevision,\n ReadinessCandidateDigest,\n ReadinessFactDefinition,\n type ReadinessFactDefinition as ReadinessFactDefinitionType,\n ReadinessFactObservation,\n type ReadinessFactObservation as ReadinessFactObservationType,\n ReadinessReleaseRevision,\n ReadinessRuleId,\n ReadinessRuleVersion\n} from \"./model.js\"\nimport { compareReadinessText, readinessDefinitionsShapeIsV1, readinessPolicyShapeIsV1 } from \"./policy.js\"\n\nconst unique = <Value>(values: ReadonlyArray<Value>): boolean => new Set(values).size === values.length\n\nconst CandidateMaterialBase = {\n workspaceId: WorkspaceId,\n releaseRevision: ReadinessReleaseRevision,\n artifactRevision: ReadinessArtifactRevision\n}\n\nconst readinessFactsAreValid = (input: {\n readonly definitions: ReadonlyArray<ReadinessFactDefinitionType>\n readonly observations: ReadonlyArray<ReadinessFactObservationType>\n}): boolean => {\n const definitionsById = new Map(input.definitions.map((definition) => [definition.factId, definition]))\n return unique(input.definitions.map(({ factId }) => factId)) &&\n unique(input.observations.map(({ factId }) => factId)) &&\n input.observations.every((observation) =>\n definitionsById.get(observation.factId)?.kind === observation.state._tag\n ) &&\n readinessPolicyShapeIsV1(input.definitions, input.observations) &&\n input.observations.reduce((total, observation) => total + observation.evidence.length, 0) <=\n MAX_READINESS_EVIDENCE_REFERENCES\n}\n\n/** Digest-free, complete material for one target-environment candidate. */\nexport const EnvironmentReadinessCandidateMaterial = Schema.Struct({\n ...CandidateMaterialBase,\n scope: Schema.TaggedStruct(\"environment\", {\n releaseId: ReleaseId,\n environmentId: EnvironmentId\n }),\n complete: Schema.Boolean,\n definitions: Schema.Array(ReadinessFactDefinition).check(Schema.isMaxLength(512)),\n observations: Schema.Array(ReadinessFactObservation).check(Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(readinessFactsAreValid, {\n expected: \"complete, unique, evidence-bounded V1 readiness candidate material\"\n })\n)\n\n/** Decoded environment candidate material before deterministic normalization. */\nexport type EnvironmentReadinessCandidateMaterial = typeof EnvironmentReadinessCandidateMaterial.Type\n\n/** Exact child assessment bound into a release-scope candidate. */\nexport const ReleaseReadinessChildMaterial = Schema.Struct({\n assessmentId: ReadinessAssessmentId,\n environmentId: EnvironmentId,\n candidateDigest: ReadinessCandidateDigest\n})\n\n/** Decoded release child material. */\nexport type ReleaseReadinessChildMaterial = typeof ReleaseReadinessChildMaterial.Type\n\n/** Digest-free material for one release candidate and its exact environment assessments. */\nexport const ReleaseReadinessCandidateMaterial = Schema.Struct({\n ...CandidateMaterialBase,\n scope: Schema.TaggedStruct(\"release\", { releaseId: ReleaseId }),\n environments: Schema.NonEmptyArray(ReleaseReadinessChildMaterial).check(Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(({ environments }) => unique(environments.map(({ environmentId }) => environmentId)), {\n expected: \"release candidate environment identities to be unique\"\n }),\n Schema.makeFilter(({ environments }) => unique(environments.map(({ assessmentId }) => assessmentId)), {\n expected: \"release candidate assessment identities to be unique\"\n })\n)\n\n/** Decoded release candidate material before deterministic normalization. */\nexport type ReleaseReadinessCandidateMaterial = typeof ReleaseReadinessCandidateMaterial.Type\n\n/** Digest-free immutable readiness-rule snapshot. */\nexport const ReadinessRuleMaterial = Schema.Struct({\n ruleId: ReadinessRuleId,\n version: ReadinessRuleVersion,\n definitions: Schema.Array(ReadinessFactDefinition).check(Schema.isNonEmpty(), Schema.isMaxLength(512))\n}).check(\n Schema.makeFilter(({ definitions }) => unique(definitions.map(({ factId }) => factId)), {\n expected: \"readiness rule fact identities to be unique\"\n }),\n Schema.makeFilter(({ definitions }) => readinessDefinitionsShapeIsV1(definitions), {\n expected: \"readiness rule material to contain the complete V1 policy shape\"\n })\n)\n\n/** Decoded rule material before deterministic normalization. */\nexport type ReadinessRuleMaterial = typeof ReadinessRuleMaterial.Type\n\nconst normalizeDefinitions = (\n definitions: ReadonlyArray<ReadinessFactDefinitionType>\n): Array<ReadinessFactDefinitionType> =>\n [...definitions].sort((left, right) => compareReadinessText(left.factId, right.factId))\n\nconst normalizeObservations = (\n observations: ReadonlyArray<ReadinessFactObservationType>\n): Array<ReadinessFactObservationType> =>\n observations\n .map((observation) => ({\n ...observation,\n evidence: [...observation.evidence].sort((left, right) => compareReadinessText(left.evidenceId, right.evidenceId))\n }))\n .sort((left, right) => compareReadinessText(left.factId, right.factId))\n\n/** Return the only JSON ordering accepted for environment-candidate hashing. */\nexport const normalizeEnvironmentReadinessCandidateMaterial = (\n material: EnvironmentReadinessCandidateMaterial\n): EnvironmentReadinessCandidateMaterial => ({\n ...material,\n definitions: normalizeDefinitions(material.definitions),\n observations: normalizeObservations(material.observations)\n})\n\n/** Return the only JSON ordering accepted for release-candidate hashing. */\nexport const normalizeReleaseReadinessCandidateMaterial = (\n material: ReleaseReadinessCandidateMaterial\n): ReleaseReadinessCandidateMaterial => {\n const [first, ...remaining] = material.environments\n const environments: [ReleaseReadinessChildMaterial, ...Array<ReleaseReadinessChildMaterial>] = [\n first,\n ...remaining\n ]\n environments.sort((left, right) => compareReadinessText(left.environmentId, right.environmentId))\n return { ...material, environments }\n}\n\n/** Return the only JSON ordering accepted for rule hashing. */\nexport const normalizeReadinessRuleMaterial = (\n material: ReadinessRuleMaterial\n): ReadinessRuleMaterial => ({\n ...material,\n definitions: normalizeDefinitions(material.definitions)\n})\n","import type {\n EnvironmentReadinessAssessment,\n ReleaseReadinessAssessment,\n ReleaseReadinessRollupInput\n} from \"./model.js\"\nimport {\n compareReadinessText,\n deriveReleaseReadinessFindings,\n deriveReleaseReadinessNextEvaluationAt,\n deriveReleaseReadinessSourceSummaries,\n deriveReleaseReadinessStages,\n deriveReleaseReadinessVerdict,\n sortedReadinessUnique\n} from \"./policy.js\"\n\n/** Exact compact projection retained when an environment is rolled into a release. */\nexport const summarizeEnvironmentReadiness = (\n assessment: EnvironmentReadinessAssessment\n): ReleaseReadinessAssessment[\"environments\"][number] => ({\n assessmentId: assessment.assessmentId,\n environmentId: assessment.candidate.scope.environmentId,\n candidateDigest: assessment.candidate.digest,\n inputComplete: assessment.inputComplete,\n facts: assessment.facts,\n nextEvaluationAt: assessment.nextEvaluationAt,\n verdict: assessment.verdict,\n stages: assessment.stages,\n blockers: assessment.blockers,\n warnings: assessment.warnings,\n gaps: assessment.gaps,\n sourceFreshness: assessment.sourceFreshness,\n evidenceIds: assessment.evidenceIds\n})\n\n/** Pure deterministic roll-up of current target-environment assessments. */\nexport const rollUpReleaseReadiness = (\n input: ReleaseReadinessRollupInput\n): ReleaseReadinessAssessment => {\n const environments = input.environments\n .slice()\n .sort((left, right) => {\n return compareReadinessText(\n left.candidate.scope.environmentId,\n right.candidate.scope.environmentId\n )\n })\n const first = environments.reduce((earliest, assessment) =>\n compareReadinessText(\n assessment.candidate.scope.environmentId,\n earliest.candidate.scope.environmentId\n ) < 0\n ? assessment\n : earliest, input.environments[0])\n const environmentSummaries: ReleaseReadinessAssessment[\"environments\"] = [\n summarizeEnvironmentReadiness(first),\n ...environments.filter((assessment) => assessment !== first).map(summarizeEnvironmentReadiness)\n ]\n const findings = deriveReleaseReadinessFindings(environmentSummaries)\n\n return {\n _tag: \"release\",\n assessmentId: input.assessmentId,\n previousAssessmentId: input.previousAssessmentId,\n candidate: input.candidate,\n rule: first.rule,\n derivationVersion: first.derivationVersion,\n evaluatedAt: input.evaluatedAt,\n nextEvaluationAt: deriveReleaseReadinessNextEvaluationAt(environmentSummaries),\n verdict: deriveReleaseReadinessVerdict(environmentSummaries),\n stages: deriveReleaseReadinessStages(environmentSummaries),\n environments: environmentSummaries,\n blockers: findings.blockers,\n warnings: findings.warnings,\n gaps: findings.gaps,\n sourceFreshness: deriveReleaseReadinessSourceSummaries(environmentSummaries),\n evidenceIds: sortedReadinessUnique(environments.flatMap(({ evidenceIds }) => evidenceIds))\n }\n}\n"],"mappings":";;;;;;AAOA,IAAa,wBAAwB,OAAO,aAAa,UAAU,EACjE,UAAU,SACZ,CAAC;;AAMD,IAAa,uBAAuB,OAAO,OAAO;CAChD,aAAa;CACb,SAAS;CACT,QAAQ;CACR,iBAAiB;CACjB,mBAAmB;CACnB,oBAAoB;CACpB,WAAW;CACX,WAAW;CACX,WAAW,OAAO,OAAO,YAAY;AACvC,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,EAAE,WAAW,gBAAgB,SAAS,MAAM,WAAW,SAAS,IAAI,GACrE,EAAE,UAAU,yCAAyC,CACvD,GACA,OAAO,YACJ,EAAE,WAAW,gBAAgB,cAAc,QAAQ,SAAS,MAAM,WAAW,SAAS,KAAK,GAC5F,EAAE,UAAU,mDAAmD,CACjE,CACF;;;ACjBA,IAAM,UAAiB,WAA0C,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,OAAO;AAEjG,IAAM,wBAAwB;CAC5B,aAAa;CACb,iBAAiB;CACjB,kBAAkB;AACpB;AAEA,IAAM,0BAA0B,UAGjB;CACb,MAAM,kBAAkB,IAAI,IAAI,MAAM,YAAY,KAAK,eAAe,CAAC,WAAW,QAAQ,UAAU,CAAC,CAAC;CACtG,OAAO,OAAO,MAAM,YAAY,KAAK,EAAE,aAAa,MAAM,CAAC,KACzD,OAAO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